<?php
session_start();
if (!isset($_SESSION['username']) || !in_array($_SESSION['role'], ['admin', 'guru'])) {
    header("Location: index.php");
    exit;
}

include 'config.php';
include 'telegram_config.php';
require 'vendor/phpqrcode/qrlib.php';

// Proses simpan (tambah baru)
if (isset($_POST['simpan'])) {
    $nis   = trim($_POST['nis']);
    $nisn  = trim($_POST['nisn']);
    $nama  = trim($_POST['nama']);
    $kelas = trim($_POST['kelas']);
    $no_wa = trim($_POST['no_wa']);
    $telegram_id = trim($_POST['telegram_id'] ?? '');
    $foto  = '';

    // Validasi
    if (empty($nis)) {
        $error = "NIS harus diisi";
    } 
    elseif (!preg_match('/^[0-9]{1,20}$/', $nis)) {
        $error = "NIS harus berupa angka (maksimal 20 digit)";
    }
    elseif (!preg_match('/^[0-9]{10}$/', $nisn)) {
        $error = "NISN harus 10 digit angka";
    }
    elseif (empty($nama)) {
        $error = "Nama harus diisi";
    }
    elseif (empty($kelas)) {
        $error = "Kelas harus diisi";
    }
    elseif (strlen($kelas) > 10) {
        $error = "Kelas maksimal 10 karakter";
    }
    elseif (!empty($no_wa) && !preg_match('/^[0-9]{10,15}$/', $no_wa)) {
        $error = "Nomor WhatsApp harus berupa angka (10-15 digit)";
    }
    elseif (!empty($telegram_id) && !preg_match('/^[0-9]+$/', $telegram_id)) {
        $error = "Telegram ID harus berupa angka";
    }
    elseif (mysqli_num_rows(mysqli_query($conn, "SELECT id FROM siswa WHERE nis='$nis' AND status='aktif'")) > 0) {
        $error = "NIS sudah digunakan oleh siswa lain";
    }
    elseif (mysqli_num_rows(mysqli_query($conn, "SELECT id FROM siswa WHERE nisn='$nisn' AND status='aktif'")) > 0) {
        $error = "NISN sudah digunakan oleh siswa lain";
    }
    else {
        if (!empty($no_wa) && $no_wa[0] == '0') {
            $no_wa = '62' . substr($no_wa, 1);
        }

        if (isset($_FILES['foto']) && $_FILES['foto']['error'] == 0) {
            $allowed_ext = ['jpg', 'jpeg', 'png', 'gif'];
            $file_name = $_FILES['foto']['name'];
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            $file_size = $_FILES['foto']['size'];
            $file_tmp = $_FILES['foto']['tmp_name'];
            
            if (!in_array($file_ext, $allowed_ext)) {
                $error = "Ekstensi file tidak diizinkan. Gunakan JPG, JPEG, PNG, atau GIF";
            }
            elseif ($file_size > 2097152) {
                $error = "Ukuran file terlalu besar. Maksimal 2MB";
            } else {
                $upload_dir = "uploads/foto_siswa/";
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                $new_file_name = "siswa_" . $nisn . "_" . time() . "." . $file_ext;
                $foto = $upload_dir . $new_file_name;
                if (!move_uploaded_file($file_tmp, $foto)) {
                    $error = "Gagal mengupload foto";
                }
            }
        }

        if (!isset($error)) {
            mysqli_query($conn, "INSERT INTO siswa (nis, nisn, nama, kelas, no_wa, telegram_id, status, foto) 
                                 VALUES ('$nis', '$nisn', '$nama', '$kelas', '$no_wa', '$telegram_id', 'aktif', '$foto')");

            $username = $nisn;
            $password = md5($nisn);
            $role     = 'siswa';

            $cek_user = mysqli_query($conn, "SELECT id FROM users WHERE username='$username' LIMIT 1");
            if (mysqli_num_rows($cek_user) == 0) {
                mysqli_query($conn, "INSERT INTO users (username, nama, password, role) 
                                     VALUES ('$username', '$nama', '$password', '$role')");
            }

            $qr_dir = "assets/qr/";
            if (!is_dir($qr_dir)) mkdir($qr_dir, 0777, true);
            QRcode::png($nisn, $qr_dir . "$nisn.png", QR_ECLEVEL_L, 4);

            $_SESSION['success'] = "Data siswa berhasil ditambahkan!";
            header("Location: siswa.php");
            exit;
        }
    }
}

// Proses update data (edit)
if (isset($_POST['update'])) {
    $id    = intval($_POST['id']);
    $nis   = trim($_POST['nis']);
    $nisn  = trim($_POST['nisn']);
    $nama  = trim($_POST['nama']);
    $kelas = trim($_POST['kelas']);
    $no_wa = trim($_POST['no_wa']);
    $telegram_id = trim($_POST['telegram_id'] ?? '');
    $foto  = '';

    // Validasi
    if (empty($nis)) {
        $error = "NIS harus diisi";
    } 
    elseif (!preg_match('/^[0-9]{1,20}$/', $nis)) {
        $error = "NIS harus berupa angka (maksimal 20 digit)";
    }
    elseif (!preg_match('/^[0-9]{10}$/', $nisn)) {
        $error = "NISN harus 10 digit angka";
    }
    elseif (empty($nama)) {
        $error = "Nama harus diisi";
    }
    elseif (empty($kelas)) {
        $error = "Kelas harus diisi";
    }
    elseif (strlen($kelas) > 10) {
        $error = "Kelas maksimal 10 karakter";
    }
    elseif (!empty($no_wa) && !preg_match('/^[0-9]{10,15}$/', $no_wa)) {
        $error = "Nomor WhatsApp harus berupa angka (10-15 digit)";
    }
    elseif (!empty($telegram_id) && !preg_match('/^[0-9]+$/', $telegram_id)) {
        $error = "Telegram ID harus berupa angka";
    }
    elseif (mysqli_num_rows(mysqli_query($conn, "SELECT id FROM siswa WHERE nis='$nis' AND id != $id AND status='aktif'")) > 0) {
        $error = "NIS sudah digunakan oleh siswa lain";
    }
    elseif (mysqli_num_rows(mysqli_query($conn, "SELECT id FROM siswa WHERE nisn='$nisn' AND id != $id AND status='aktif'")) > 0) {
        $error = "NISN sudah digunakan oleh siswa lain";
    }
    else {
        if (!empty($no_wa) && $no_wa[0] == '0') {
            $no_wa = '62' . substr($no_wa, 1);
        }

        $res_old = mysqli_query($conn, "SELECT nisn, foto FROM siswa WHERE id=$id LIMIT 1");
        $old     = mysqli_fetch_assoc($res_old);
        $old_nisn = $old['nisn'];
        $old_foto = $old['foto'];

        if (isset($_FILES['foto']) && $_FILES['foto']['error'] == 0) {
            $allowed_ext = ['jpg', 'jpeg', 'png', 'gif'];
            $file_name = $_FILES['foto']['name'];
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            $file_size = $_FILES['foto']['size'];
            $file_tmp = $_FILES['foto']['tmp_name'];
            
            if (!in_array($file_ext, $allowed_ext)) {
                $error = "Ekstensi file tidak diizinkan. Gunakan JPG, JPEG, PNG, atau GIF";
            }
            elseif ($file_size > 2097152) {
                $error = "Ukuran file terlalu besar. Maksimal 2MB";
            } else {
                if (!empty($old_foto) && file_exists($old_foto)) {
                    unlink($old_foto);
                }
                $upload_dir = "uploads/foto_siswa/";
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                $new_file_name = "siswa_" . $nisn . "_" . time() . "." . $file_ext;
                $foto = $upload_dir . $new_file_name;
                if (!move_uploaded_file($file_tmp, $foto)) {
                    $error = "Gagal mengupload foto";
                }
            }
        } else {
            $foto = $old_foto;
        }

        if (!isset($error)) {
            mysqli_query($conn, "UPDATE siswa 
                                 SET nis='$nis', nisn='$nisn', nama='$nama', kelas='$kelas', 
                                     no_wa='$no_wa', telegram_id='$telegram_id', foto='$foto' 
                                 WHERE id=$id");

            mysqli_query($conn, "UPDATE users 
                                 SET username='$nisn', nama='$nama', password=md5('$nisn') 
                                 WHERE username='$old_nisn' AND role='siswa'");

            $qr_dir = "assets/qr/";
            if (!is_dir($qr_dir)) mkdir($qr_dir, 0777, true);
            if (file_exists($qr_dir . "$old_nisn.png")) {
                unlink($qr_dir . "$old_nisn.png");
            }
            QRcode::png($nisn, $qr_dir . "$nisn.png", QR_ECLEVEL_L, 4);

            $_SESSION['success'] = "Data siswa berhasil diupdate!";
            header("Location: siswa.php");
            exit;
        }
    }
}

// Test Kirim Telegram
if (isset($_POST['test_telegram'])) {
    $id = intval($_POST['siswa_id']);
    $query = mysqli_query($conn, "SELECT nama, telegram_id FROM siswa WHERE id = $id");
    $siswa = mysqli_fetch_assoc($query);
    
    if ($siswa && !empty($siswa['telegram_id'])) {
        $pesan = "🧪 *TEST NOTIFIKASI TELEGRAM*\n\n";
        $pesan .= "Nama: " . $siswa['nama'] . "\n";
        $pesan .= "Waktu: " . date('d-m-Y H:i:s') . "\n";
        $pesan .= "Status: ✅ Test berhasil\n";
        $pesan .= "\nTerima kasih.";

        $result = kirimTelegramToUser($pesan, $siswa['telegram_id']);
        
        if (strpos($result, 'berhasil') !== false) {
            $_SESSION['success'] = "✅ Test Telegram berhasil dikirim ke " . $siswa['nama'];
        } else {
            $_SESSION['error'] = "❌ Gagal kirim test Telegram: " . $result;
        }
    } else {
        $_SESSION['error'] = "❌ Telegram ID tidak ditemukan untuk siswa ini!";
    }
    header("Location: siswa.php");
    exit;
}

// Tandai siswa keluar
if (isset($_GET['keluar'])) {
    $id = intval($_GET['keluar']);
    $res = mysqli_query($conn, "SELECT nisn, foto FROM siswa WHERE id=$id LIMIT 1");
    $data = mysqli_fetch_assoc($res);
    $nisn_keluar = $data['nisn'];
    $foto_keluar = $data['foto'];

    if (!empty($foto_keluar) && file_exists($foto_keluar)) {
        unlink($foto_keluar);
    }

    mysqli_query($conn, "UPDATE siswa SET status='keluar', foto='' WHERE id=$id");
    mysqli_query($conn, "DELETE FROM users WHERE username='$nisn_keluar' AND role='siswa'");

    $_SESSION['success'] = "Siswa berhasil ditandai keluar!";
    header("Location: siswa.php");
    exit;
}

// Generate akun massal
if (isset($_POST['generate_akun'])) {
    $q_siswa = mysqli_query($conn, "SELECT nisn, nama FROM siswa WHERE status='aktif'");
    $count = 0;
    while ($s = mysqli_fetch_assoc($q_siswa)) {
        $username = $s['nisn'];
        $nama     = $s['nama'];
        $password = md5($s['nisn']);
        $role     = 'siswa';

        $cek = mysqli_query($conn, "SELECT id FROM users WHERE username='$username' LIMIT 1");
        if (mysqli_num_rows($cek) == 0) {
            mysqli_query($conn, "INSERT INTO users (username, nama, password, role) 
                                 VALUES ('$username', '$nama', '$password', '$role')");
            $count++;
        }
    }
    $_SESSION['success'] = "Generate akun selesai. $count akun baru dibuat.";
    header("Location: siswa.php");
    exit;
}

// Ambil data untuk edit jika ada
$edit_data = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $res = mysqli_query($conn, "SELECT * FROM siswa WHERE id=$id LIMIT 1");
    $edit_data = mysqli_fetch_assoc($res);
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Data Siswa</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
  <style>
    .form-control:invalid { border-color: #dc3545; }
    .form-control:valid { border-color: #198754; }
    .input-hint { font-size: 0.875rem; margin-top: 0.25rem; }
    .btn-action { margin: 2px; }
    .foto-preview { max-width: 100px; max-height: 100px; object-fit: cover; border-radius: 5px; border: 1px solid #dee2e6; padding: 2px; }
    .foto-container { text-align: center; margin-bottom: 10px; }
    .photo-placeholder { width: 100px; height: 100px; background-color: #f8f9fa; border: 2px dashed #dee2e6; border-radius: 5px; display: flex; align-items: center; justify-content: center; color: #6c757d; margin: 0 auto; }
    .table-foto { width: 80px; height: 80px; object-fit: cover; border-radius: 5px; }
    .foto-upload-wrapper { border: 2px dashed #dee2e6; padding: 20px; text-align: center; border-radius: 8px; background-color: #f8f9fa; transition: all 0.3s; }
    .foto-upload-wrapper:hover { border-color: #0d6efd; background-color: #e7f1ff; }
    .badge-telegram { background-color: #0088cc; color: white; padding: 3px 10px; border-radius: 15px; font-size: 0.75rem; }
    .badge-no-telegram { background-color: #6c757d; color: white; padding: 3px 10px; border-radius: 15px; font-size: 0.75rem; }
    .telegram-help { background-color: #e8f4fd; border-left: 4px solid #0088cc; padding: 10px 15px; border-radius: 5px; }
    .btn-test-telegram { background: linear-gradient(135deg, #0088cc 0%, #006699 100%); border: none; color: white; }
    .btn-test-telegram:hover { color: white; opacity: 0.9; }
    .btn-test-telegram:disabled { opacity: 0.5; cursor: not-allowed; }
  </style>
</head>
<body class="container py-4">

  <h2 class="text-center mb-4"><i class="fas fa-user-graduate"></i> Data Siswa</h2>

  <a href="dashboard.php" class="btn btn-secondary mb-3">← Kembali ke Dashboard</a>

  <?php if (isset($_SESSION['success'])): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-check-circle"></i> <?= $_SESSION['success'] ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php unset($_SESSION['success']); ?>
  <?php endif; ?>

  <?php if (isset($_SESSION['error'])): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <i class="fas fa-exclamation-circle"></i> <?= $_SESSION['error'] ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php unset($_SESSION['error']); ?>
  <?php endif; ?>

  <?php if (isset($error)): ?>
    <div class="alert alert-danger">
        <i class="fas fa-exclamation-circle"></i> <?= $error ?>
    </div>
  <?php endif; ?>

  <!-- Form Input / Edit -->
  <div class="card mb-4">
    <div class="card-header bg-primary text-white">
        <h5 class="mb-0">
            <i class="fas fa-<?= $edit_data ? 'edit' : 'plus' ?>"></i>
            <?= $edit_data ? 'Edit Data Siswa' : 'Tambah Data Siswa Baru' ?>
        </h5>
    </div>
    <div class="card-body">
        <form method="post" enctype="multipart/form-data" class="row g-3">
            <input type="hidden" name="id" value="<?= $edit_data['id'] ?? '' ?>">
            
            <!-- Kolom 1: Foto -->
            <div class="col-md-3">
                <div class="foto-upload-wrapper">
                    <div class="foto-container">
                        <?php if ($edit_data && !empty($edit_data['foto']) && file_exists($edit_data['foto'])): ?>
                            <img src="<?= $edit_data['foto'] ?>" alt="Foto Siswa" class="foto-preview mb-2" id="fotoPreview">
                            <p class="small text-muted">Foto saat ini</p>
                        <?php else: ?>
                            <div class="photo-placeholder mb-2" id="fotoPreviewPlaceholder">
                                <i class="fas fa-user fa-3x"></i>
                            </div>
                            <img src="" alt="" class="foto-preview mb-2 d-none" id="fotoPreview">
                            <p class="small text-muted" id="fotoPreviewText">Belum ada foto</p>
                        <?php endif; ?>
                    </div>
                    <div class="mb-3">
                        <label for="foto" class="form-label">Upload Foto Siswa</label>
                        <input type="file" name="foto" class="form-control" id="fotoInput" accept="image/*">
                        <div class="input-hint text-muted">JPG, PNG, GIF max 2MB</div>
                    </div>
                </div>
            </div>
            
            <!-- Kolom 2: Data Siswa -->
            <div class="col-md-9">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label for="nis" class="form-label">NIS *</label>
                        <input type="text" name="nis" class="form-control" placeholder="Contoh: 1234567" required 
                               value="<?= $edit_data['nis'] ?? '' ?>" pattern="[0-9]{1,20}" 
                               title="NIS harus berupa angka (1-20 digit)">
                        <div class="input-hint text-muted">1-20 digit angka</div>
                    </div>
                    
                    <div class="col-md-3">
                        <label for="nisn" class="form-label">NISN *</label>
                        <input type="text" name="nisn" class="form-control" placeholder="Contoh: 1234567890" required 
                               value="<?= $edit_data['nisn'] ?? '' ?>" pattern="[0-9]{10}" 
                               title="NISN harus 10 digit angka">
                        <div class="input-hint text-muted">10 digit angka</div>
                    </div>
                    
                    <div class="col-md-6">
                        <label for="nama" class="form-label">Nama Lengkap *</label>
                        <input type="text" name="nama" class="form-control" placeholder="Nama lengkap siswa" required 
                               value="<?= $edit_data['nama'] ?? '' ?>">
                    </div>
                    
                    <div class="col-md-3">
                        <label for="kelas" class="form-label">Kelas *</label>
                        <input type="text" name="kelas" class="form-control" placeholder="Contoh: 7A" required 
                               value="<?= $edit_data['kelas'] ?? '' ?>" maxlength="10"
                               title="Kelas maksimal 10 karakter">
                        <div class="input-hint text-muted">Maks. 10 karakter</div>
                    </div>
                    
                    <div class="col-md-4">
                        <label for="no_wa" class="form-label">Nomor WhatsApp</label>
                        <input type="text" name="no_wa" class="form-control" placeholder="6285xxxx" 
                               value="<?= $edit_data['no_wa'] ?? '' ?>" pattern="[0-9]{10,15}"
                               title="Nomor WhatsApp 10-15 digit">
                        <div class="input-hint text-muted">Opsional - 10-15 digit angka</div>
                    </div>

                    <div class="col-md-5">
                        <label for="telegram_id" class="form-label">
                            <i class="fab fa-telegram text-primary"></i> Telegram ID
                        </label>
                        <input type="text" name="telegram_id" class="form-control" placeholder="Contoh: 123456789" 
                               value="<?= $edit_data['telegram_id'] ?? '' ?>" pattern="[0-9]*"
                               title="Telegram ID hanya angka">
                        <div class="input-hint text-muted">
                            <i class="fas fa-info-circle"></i> 
                            Dapatkan ID dari <strong>@userinfobot</strong> atau <strong>@getmyid_bot</strong> di Telegram.
                        </div>
                    </div>
                    
                    <div class="col-md-12 d-flex align-items-end">
                        <div class="d-flex gap-2 w-100">
                            <?php if ($edit_data): ?>
                                <button type="submit" name="update" class="btn btn-warning flex-fill">
                                    <i class="fas fa-save"></i> Update
                                </button>
                                <a href="siswa.php" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> Batal
                                </a>
                            <?php else: ?>
                                <button type="submit" name="simpan" class="btn btn-success flex-fill">
                                    <i class="fas fa-save"></i> Simpan
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
  </div>

  <!-- Action Buttons -->
  <div class="row mb-3">
    <div class="col-md-12">
        <form method="post" class="d-inline">
            <button type="submit" name="generate_akun" class="btn btn-dark">
                <i class="fas fa-bolt"></i> Generate Akun Siswa
            </button>
        </form>
        <a href="cetak_kartu.php" class="btn btn-success" target="_blank">
            <i class="fas fa-print"></i> Cetak Semua Kartu QR
        </a>
        <a href="import_siswa.php" class="btn btn-info">
            <i class="fas fa-download"></i> Import dari Excel
        </a>
        <a href="update_telegram_id.php" class="btn btn-primary">
            <i class="fab fa-telegram"></i> Update Telegram ID
        </a>
    </div>
  </div>

  <!-- Tabel Data Siswa -->
  <div class="card">
    <div class="card-header bg-light">
        <h5 class="mb-0">
            <i class="fas fa-list"></i> Daftar Siswa Aktif
            <span class="badge bg-primary"><?= mysqli_num_rows(mysqli_query($conn, "SELECT id FROM siswa WHERE status='aktif'")) ?> Siswa</span>
        </h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover mb-0">
                <thead class="table-primary">
                    <tr class="text-center">
                        <th width="5%">No</th>
                        <th width="8%">Foto</th>
                        <th width="8%">NIS</th>
                        <th width="10%">NISN</th>
                        <th width="15%">Nama</th>
                        <th width="7%">Kelas</th>
                        <th width="10%">No. WhatsApp</th>
                        <th width="12%">Telegram ID</th>
                        <th width="9%">QR Code</th>
                        <th width="18%">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $q = mysqli_query($conn, "SELECT * FROM siswa WHERE status='aktif' ORDER BY kelas, nama ASC");
                    $no = 1;
                    if (mysqli_num_rows($q) == 0): ?>
                        <tr>
                            <td colspan="10" class="text-center py-4 text-muted">
                                <i class="fas fa-users fa-2x mb-2"></i><br>
                                Belum ada data siswa
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php while ($row = mysqli_fetch_assoc($q)): ?>
                            <tr>
                                <td class="text-center"><?= $no++ ?></td>
                                <td class="text-center">
                                    <?php if (!empty($row['foto']) && file_exists($row['foto'])): ?>
                                        <img src="<?= $row['foto'] ?>" alt="Foto" class="table-foto" 
                                             data-bs-toggle="tooltip" data-bs-placement="top" title="<?= htmlspecialchars($row['nama']) ?>">
                                    <?php else: ?>
                                        <div class="photo-placeholder table-foto">
                                            <i class="fas fa-user"></i>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center"><?= $row['nis'] ?></td>
                                <td><?= $row['nisn'] ?></td>
                                <td><?= htmlspecialchars($row['nama']) ?></td>
                                <td class="text-center"><?= $row['kelas'] ?></td>
                                <td><?= $row['no_wa'] ?: '<span class="text-muted">-</span>' ?></td>
                                <td class="text-center">
                                    <?php if (!empty($row['telegram_id'])): ?>
                                        <span class="badge-telegram">
                                            <i class="fab fa-telegram"></i> <?= $row['telegram_id'] ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="badge-no-telegram">
                                            <i class="fas fa-times-circle"></i> Belum
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <?php if (file_exists("assets/qr/{$row['nisn']}.png")): ?>
                                        <a href="assets/qr/<?= $row['nisn'] ?>.png" target="_blank" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-qrcode"></i> Lihat QR
                                        </a>
                                    <?php else: ?>
                                        <span class="badge bg-warning text-dark">QR Belum Ada</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <!-- Tombol Test Telegram -->
                                    <?php if (!empty($row['telegram_id'])): ?>
                                        <form method="post" class="d-inline">
                                            <input type="hidden" name="siswa_id" value="<?= $row['id'] ?>">
                                            <button type="submit" name="test_telegram" class="btn btn-sm btn-test-telegram" 
                                                    title="Test kirim Telegram ke <?= htmlspecialchars($row['nama']) ?>"
                                                    onclick="return confirm('Kirim test Telegram ke <?= htmlspecialchars($row['nama']) ?>?')">
                                                <i class="fab fa-telegram"></i> Test
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <button class="btn btn-sm btn-secondary" disabled title="Telegram ID belum diisi">
                                            <i class="fab fa-telegram"></i> Test
                                        </button>
                                    <?php endif; ?>
                                    
                                    <a href="siswa.php?edit=<?= $row['id'] ?>" class="btn btn-sm btn-info btn-action" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="siswa.php?keluar=<?= $row['id'] ?>" class="btn btn-sm btn-warning btn-action" 
                                       onclick="return confirm('Yakin menandai <?= htmlspecialchars($row['nama']) ?> sebagai keluar?')" title="Tandai Keluar">
                                        <i class="fas fa-sign-out-alt"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
  </div>

  <!-- Panduan Telegram ID -->
  <div class="card mt-4">
    <div class="card-header bg-info text-white">
        <h6 class="mb-0"><i class="fab fa-telegram"></i> Panduan Mendapatkan Telegram ID</h6>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-6">
                <div class="telegram-help">
                    <h6><i class="fas fa-robot"></i> Cara 1: @userinfobot</h6>
                    <ol class="mb-0">
                        <li>Buka Telegram dan cari <strong>@userinfobot</strong></li>
                        <li>Kirim pesan <strong>/start</strong></li>
                        <li>Bot akan mengirimkan ID Anda: <code>Your ID: 123456789</code></li>
                    </ol>
                </div>
            </div>
            <div class="col-md-6">
                <div class="telegram-help">
                    <h6><i class="fas fa-robot"></i> Cara 2: @getmyid_bot</h6>
                    <ol class="mb-0">
                        <li>Buka Telegram dan cari <strong>@getmyid_bot</strong></li>
                        <li>Kirim pesan <strong>/start</strong></li>
                        <li>Bot akan mengirimkan ID Anda</li>
                    </ol>
                </div>
            </div>
        </div>
        <div class="alert alert-success mt-3 mb-0">
            <i class="fas fa-check-circle"></i> 
            <strong>Catatan:</strong> Setelah mengisi Telegram ID, klik tombol <strong>"Test"</strong> untuk menguji notifikasi.
        </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Preview foto
        const fotoInput = document.getElementById('fotoInput');
        const fotoPreview = document.getElementById('fotoPreview');
        const fotoPreviewPlaceholder = document.getElementById('fotoPreviewPlaceholder');
        const fotoPreviewText = document.getElementById('fotoPreviewText');

        if (fotoInput) {
            fotoInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        if (fotoPreviewPlaceholder) {
                            fotoPreviewPlaceholder.classList.add('d-none');
                        }
                        if (fotoPreviewText) {
                            fotoPreviewText.textContent = 'Preview foto baru';
                        }
                        fotoPreview.src = e.target.result;
                        fotoPreview.classList.remove('d-none');
                    };
                    reader.readAsDataURL(file);
                }
            });
        }

        // Tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });

        // Validasi ukuran file
        const formsWithFile = document.querySelectorAll('form[enctype="multipart/form-data"]');
        formsWithFile.forEach(form => {
            form.addEventListener('submit', function(e) {
                const fileInput = this.querySelector('input[type="file"]');
                if (fileInput && fileInput.files.length > 0) {
                    const file = fileInput.files[0];
                    const maxSize = 2 * 1024 * 1024;
                    
                    if (file.size > maxSize) {
                        e.preventDefault();
                        alert('Ukuran file terlalu besar. Maksimal 2MB');
                        fileInput.value = '';
                        return false;
                    }
                    
                    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
                    if (!allowedTypes.includes(file.type)) {
                        e.preventDefault();
                        alert('Format file tidak didukung. Gunakan JPG, PNG, atau GIF');
                        fileInput.value = '';
                        return false;
                    }
                }
            });
        });
    });
  </script>
</body>
</html>