<?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';

// Perbaiki struktur tabel guru jika belum ada
$sql = "CREATE TABLE IF NOT EXISTS guru (
  id INT AUTO_INCREMENT PRIMARY KEY,
  nip VARCHAR(20) NOT NULL UNIQUE,
  nama VARCHAR(100) NOT NULL,
  mapel VARCHAR(50) NOT NULL,
  no_wa VARCHAR(20),
  telegram_id VARCHAR(50),
  foto VARCHAR(255) DEFAULT '',
  status ENUM('aktif','keluar') DEFAULT 'aktif',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

if (!mysqli_query($conn, $sql)) {
    die("Error creating table: " . mysqli_error($conn));
}

// Periksa dan tambahkan kolom jika belum ada
$check_columns = mysqli_query($conn, "DESCRIBE guru");
$columns = [];
while ($row = mysqli_fetch_assoc($check_columns)) {
    $columns[] = $row['Field'];
}

if (!in_array('foto', $columns)) {
    mysqli_query($conn, "ALTER TABLE guru ADD foto VARCHAR(255) DEFAULT '' AFTER no_wa");
}

if (!in_array('telegram_id', $columns)) {
    mysqli_query($conn, "ALTER TABLE guru ADD telegram_id VARCHAR(50) AFTER no_wa");
}

if (!in_array('created_at', $columns)) {
    mysqli_query($conn, "ALTER TABLE guru ADD created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP AFTER status");
}

if (!in_array('updated_at', $columns)) {
    mysqli_query($conn, "ALTER TABLE guru ADD updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER created_at");
}

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

    // Validasi
    if (empty($nip)) {
        $error = "NIP harus diisi";
    } 
    elseif (!preg_match('/^[0-9]{1,20}$/', $nip)) {
        $error = "NIP harus berupa angka (maksimal 20 digit)";
    }
    elseif (empty($nama)) {
        $error = "Nama harus diisi";
    }
    elseif (empty($mapel)) {
        $error = "Mata Pelajaran harus diisi";
    }
    elseif (strlen($mapel) > 50) {
        $error = "Mata Pelajaran maksimal 50 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 guru WHERE nip='$nip' AND status='aktif'")) > 0) {
        $error = "NIP sudah digunakan oleh guru 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_guru/";
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                $new_file_name = "guru_" . $nip . "_" . 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 guru (nip, nama, mapel, no_wa, telegram_id, status, foto) 
                                 VALUES ('$nip', '$nama', '$mapel', '$no_wa', '$telegram_id', 'aktif', '$foto')");

            // Buat akun user untuk guru
            $username = $nip;
            $password = md5($nip);
            $role     = 'guru';

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

            // Generate QR Code
            $qr_dir = "assets/qr_guru/";
            if (!is_dir($qr_dir)) mkdir($qr_dir, 0777, true);
            QRcode::png($nip, $qr_dir . "$nip.png", QR_ECLEVEL_L, 4);

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

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

    // Validasi
    if (empty($nip)) {
        $error = "NIP harus diisi";
    } 
    elseif (!preg_match('/^[0-9]{1,20}$/', $nip)) {
        $error = "NIP harus berupa angka (maksimal 20 digit)";
    }
    elseif (empty($nama)) {
        $error = "Nama harus diisi";
    }
    elseif (empty($mapel)) {
        $error = "Mata Pelajaran harus diisi";
    }
    elseif (strlen($mapel) > 50) {
        $error = "Mata Pelajaran maksimal 50 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 guru WHERE nip='$nip' AND id != $id AND status='aktif'")) > 0) {
        $error = "NIP sudah digunakan oleh guru lain";
    }
    else {
        if (!empty($no_wa) && $no_wa[0] == '0') {
            $no_wa = '62' . substr($no_wa, 1);
        }

        $res_old = mysqli_query($conn, "SELECT nip, foto FROM guru WHERE id=$id LIMIT 1");
        $old     = mysqli_fetch_assoc($res_old);
        $old_nip = $old['nip'];
        $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_guru/";
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                $new_file_name = "guru_" . $nip . "_" . 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 guru 
                                 SET nip='$nip', nama='$nama', mapel='$mapel', no_wa='$no_wa', telegram_id='$telegram_id', foto='$foto' 
                                 WHERE id=$id");

            mysqli_query($conn, "UPDATE users_guru 
                                 SET username='$nip', nama='$nama', password=md5('$nip') 
                                 WHERE username='$old_nip' AND role='guru'");

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

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

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

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

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

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

    mysqli_query($conn, "UPDATE guru SET status='keluar', foto='' WHERE id=$id");
    mysqli_query($conn, "DELETE FROM users_guru WHERE username='$nip_keluar' AND role='guru'");

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

// Generate akun massal untuk guru
if (isset($_POST['generate_akun'])) {
    $q_guru = mysqli_query($conn, "SELECT nip, nama FROM guru WHERE status='aktif'");
    $count = 0;
    while ($g = mysqli_fetch_assoc($q_guru)) {
        $username = $g['nip'];
        $nama     = $g['nama'];
        $password = md5($g['nip']);
        $role     = 'guru';

        $cek = mysqli_query($conn, "SELECT id FROM users_guru WHERE username='$username' LIMIT 1");
        if (mysqli_num_rows($cek) == 0) {
            mysqli_query($conn, "INSERT INTO users_guru (username, nama, password, role) 
                                 VALUES ('$username', '$nama', '$password', '$role')");
            $count++;
        }
    }
    $_SESSION['success'] = "Generate akun guru selesai. $count akun baru dibuat.";
    header("Location: guru.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 guru WHERE id=$id LIMIT 1");
    $edit_data = mysqli_fetch_assoc($res);
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Data Guru</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; }
    .table-responsive { max-height: 70vh; overflow-y: auto; }
  </style>
</head>
<body class="container py-4">

  <h2 class="text-center mb-4"><i class="fas fa-chalkboard-teacher"></i> Data Guru</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"><?= $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 Guru' : 'Tambah Data Guru 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 Guru" 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 Guru</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 Guru -->
            <div class="col-md-9">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label for="nip" class="form-label">NIP *</label>
                        <input type="text" name="nip" class="form-control" placeholder="Contoh: 123456789012345" required 
                               value="<?= $edit_data['nip'] ?? '' ?>" pattern="[0-9]{1,20}" 
                               title="NIP harus berupa angka (1-20 digit)">
                        <div class="input-hint text-muted">1-20 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 guru" required 
                               value="<?= $edit_data['nama'] ?? '' ?>">
                    </div>
                    
                    <div class="col-md-3">
                        <label for="mapel" class="form-label">Mata Pelajaran *</label>
                        <input type="text" name="mapel" class="form-control" placeholder="Contoh: Matematika" required 
                               value="<?= $edit_data['mapel'] ?? '' ?>" maxlength="50"
                               title="Mata Pelajaran maksimal 50 karakter">
                        <div class="input-hint text-muted">Maks. 50 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</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="guru.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 Guru
            </button>
        </form>
        <a href="cetak_kartu_guru.php" class="btn btn-success" target="_blank">
            <i class="fas fa-print"></i> Cetak Semua Kartu QR Guru
        </a>
        <a href="guru_keluar.php" class="btn btn-outline-danger">
            <i class="fas fa-history"></i> Lihat Guru Keluar
        </a>
        <a href="import_guru.php" class="btn btn-info">
            <i class="fas fa-download"></i> Import dari Excel
        </a>
        <a href="update_telegram_guru.php" class="btn btn-primary">
            <i class="fab fa-telegram"></i> Update Telegram ID
        </a>
    </div>
  </div>

  <!-- Tabel Data Guru -->
  <div class="card">
    <div class="card-header bg-light">
        <h5 class="mb-0">
            <i class="fas fa-list"></i> Daftar Guru Aktif
            <span class="badge bg-primary"><?= mysqli_num_rows(mysqli_query($conn, "SELECT id FROM guru WHERE status='aktif'")) ?> Guru</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="10%">NIP</th>
                        <th width="18%">Nama</th>
                        <th width="15%">Mata Pelajaran</th>
                        <th width="10%">No. WhatsApp</th>
                        <th width="12%">Telegram ID</th>
                        <th width="10%">QR Code</th>
                        <th width="12%">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $q = mysqli_query($conn, "SELECT * FROM guru WHERE status='aktif' ORDER BY nama ASC");
                    $no = 1;
                    if (mysqli_num_rows($q) == 0): ?>
                        <tr>
                            <td colspan="9" class="text-center py-4 text-muted">
                                <i class="fas fa-chalkboard-teacher fa-2x mb-2"></i><br>
                                Belum ada data guru
                            </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['nip'] ?></td>
                                <td><?= htmlspecialchars($row['nama']) ?></td>
                                <td><?= htmlspecialchars($row['mapel']) ?></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_guru/{$row['nip']}.png")): ?>
                                        <a href="assets/qr_guru/<?= $row['nip'] ?>.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="guru_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="guru.php?edit=<?= $row['id'] ?>" class="btn btn-sm btn-info btn-action" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="guru.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>