<?php
// update_telegram_guru.php
// Halaman untuk mengupdate Telegram ID guru

include "config.php";
include "telegram_config.php";
session_start();

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: index.php");
    exit;
}

// Proses update
if (isset($_POST['update'])) {
    $telegram_id = trim($_POST['telegram_id']);
    $guru_id = intval($_POST['guru_id']);
    
    if (!empty($telegram_id) && preg_match('/^[0-9]+$/', $telegram_id)) {
        mysqli_query($conn, "UPDATE guru SET telegram_id='$telegram_id' WHERE id=$guru_id");
        $_SESSION['success'] = "Telegram ID berhasil diupdate!";
    } else {
        $_SESSION['error'] = "Telegram ID harus berupa angka!";
    }
    header("Location: update_telegram_guru.php");
    exit;
}

// Proses hapus Telegram ID
if (isset($_GET['hapus'])) {
    $id = intval($_GET['hapus']);
    mysqli_query($conn, "UPDATE guru SET telegram_id='' WHERE id=$id");
    $_SESSION['success'] = "Telegram ID berhasil dihapus!";
    header("Location: update_telegram_guru.php");
    exit;
}

// Proses test 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 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: update_telegram_guru.php");
    exit;
}

// Ambil data guru
$q = mysqli_query($conn, "SELECT id, nip, nama, mapel, no_wa, telegram_id FROM guru WHERE status='aktif' ORDER BY nama ASC");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Update Telegram ID Guru</title>
    <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>
        .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;
            margin-bottom: 15px;
        }
        .btn-test-telegram {
            background: linear-gradient(135deg, #0088cc 0%, #006699 100%);
            border: none;
            color: white;
        }
        .btn-test-telegram:hover {
            color: white;
            opacity: 0.9;
        }
        .table-guru th {
            white-space: nowrap;
        }
    </style>
</head>
<body>
<div class="container py-4">
    <h2><i class="fab fa-telegram"></i> Update Telegram ID Guru</h2>
    <a href="dashboard.php" class="btn btn-secondary mb-3">← Kembali</a>
    <a href="guru.php" class="btn btn-primary mb-3">📋 Data Guru</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; ?>
    
    <div class="card">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="fas fa-list"></i> Daftar Guru Aktif</h5>
        </div>
        <div class="card-body">
            <div class="telegram-help">
                <h6><i class="fas fa-info-circle"></i> Cara Mendapatkan Telegram ID:</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>
                    <li>Copy angka ID dan masukkan ke kolom di bawah</li>
                </ol>
            </div>
            
            <div class="table-responsive">
                <table class="table table-bordered table-hover table-striped table-guru">
                    <thead class="table-primary">
                        <tr class="text-center">
                            <th width="5%">No</th>
                            <th width="10%">NIP</th>
                            <th width="18%">Nama</th>
                            <th width="15%">Mata Pelajaran</th>
                            <th width="10%">No. WA</th>
                            <th width="18%">Telegram ID</th>
                            <th width="24%">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $no=1; while($row = mysqli_fetch_assoc($q)): ?>
                        <tr>
                            <td class="text-center"><?= $no++ ?></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 diisi
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="d-flex gap-1 flex-wrap">
                                    <!-- Form Update -->
                                    <form method="post" class="d-flex gap-1">
                                        <input type="hidden" name="guru_id" value="<?= $row['id'] ?>">
                                        <input type="text" name="telegram_id" class="form-control form-control-sm" 
                                               placeholder="Masukkan ID" style="width:130px"
                                               value="<?= $row['telegram_id'] ?>">
                                        <button type="submit" name="update" class="btn btn-sm btn-success" title="Simpan">
                                            <i class="fas fa-save"></i>
                                        </button>
                                    </form>
                                    
                                    <!-- 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']) ?>">
                                                <i class="fab fa-telegram"></i> Test
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                    
                                    <!-- Tombol Hapus -->
                                    <?php if (!empty($row['telegram_id'])): ?>
                                        <a href="update_telegram_guru.php?hapus=<?= $row['id'] ?>" 
                                           class="btn btn-sm btn-danger" 
                                           onclick="return confirm('Hapus Telegram ID <?= htmlspecialchars($row['nama']) ?>?')" 
                                           title="Hapus">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
            
            <?php if (mysqli_num_rows($q) == 0): ?>
                <div class="text-center py-4 text-muted">
                    <i class="fas fa-chalkboard-teacher fa-3x mb-2"></i><br>
                    Belum ada data guru
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Informasi Bot -->
    <div class="card mt-3">
        <div class="card-header bg-info text-white">
            <h6 class="mb-0"><i class="fas fa-info-circle"></i> Informasi Bot Telegram</h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <p><strong>Nama Bot:</strong> Notifikasi Sekolah</p>
                    <p><strong>Username:</strong> @NotifikasiSekolahBot</p>
                </div>
                <div class="col-md-6">
                    <p><strong>Token:</strong> 8755174140:AAH0BpyLwAGohUea6h2-zeOB57BmSoPVcjY</p>
                    <p>
                        <a href="https://api.telegram.org/bot8755174140:AAH0BpyLwAGohUea6h2-zeOB57BmSoPVcjY/getUpdates" 
                           target="_blank" class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-eye"></i> Lihat getUpdates
                        </a>
                    </p>
                </div>
            </div>
            <div class="alert alert-warning mt-2 mb-0">
                <i class="fas fa-exclamation-triangle"></i> 
                <strong>Catatan:</strong> Pastikan guru sudah mengirim pesan <strong>/start</strong> ke bot 
                <strong>@NotifikasiSekolahBot</strong> sebelum mengirim test Telegram.
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>