<?php

require_once __DIR__ . '/core/auth.php';
require_once __DIR__ . '/core/db.php';
require_once __DIR__ . '/core/license_engine.php';

requireEcosystemAuth();

$actionResult = null;
$errorMsg = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'generate') {
        $npsn = trim($_POST['npsn'] ?? '');
        $schoolName = trim($_POST['school_name'] ?? '');
        $duration = intval($_POST['duration'] ?? 3);

        if (empty($npsn) || empty($schoolName)) {
            $errorMsg = 'NPSN dan Nama Sekolah wajib diisi.';
        } else {
            $gen = createSignedLicenseKey($npsn, $schoolName, $duration);
            if ($gen['success']) {
                $actionResult = $gen;
            } else {
                $errorMsg = $gen['error'] ?? 'Gagal membuat lisensi.';
            }
        }
    } elseif ($action === 'revoke') {
        $id = intval($_POST['id'] ?? 0);
        if ($id > 0) {
            revokeLicenseRecord($id);
            header('Location: index.php?msg=revoked');
            exit;
        }
    } elseif ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);
        if ($id > 0) {
            deleteLicenseRecord($id);
            header('Location: index.php?msg=deleted');
            exit;
        }
    }
}

$search = trim($_GET['q'] ?? '');
$licenses = getLicensesList($search);
$schools = getSchoolsList();

$totalLicenses = count($licenses);
$activeLicenses = 0;
$expiredLicenses = 0;
$today = date('Y-m-d');

foreach ($licenses as $lic) {
    if ($lic['status'] === 'REVOKED') {
        continue;
    }
    if ($lic['expires_at'] >= $today) {
        $activeLicenses++;
    } else {
        $expiredLicenses++;
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - CBT Ecosystem Central</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-slate-900 text-slate-100 min-h-screen">
    <header class="border-b border-slate-800 bg-slate-900/90 backdrop-blur sticky top-0 z-30">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-indigo-600 flex items-center justify-center text-white shadow-md shadow-indigo-600/30">
                    <i class="fa-solid fa-shield-halved text-lg"></i>
                </div>
                <div>
                    <h1 class="text-base font-bold text-white tracking-tight">CBT Ecosystem Central</h1>
                    <p class="text-xs text-slate-400">Developer Licensing & Cryptographic DRM Server</p>
                </div>
            </div>
            <div class="flex items-center gap-3">
                <a href="export_zip.php" class="inline-flex items-center gap-2 bg-emerald-600/20 hover:bg-emerald-600/30 text-emerald-300 border border-emerald-500/30 px-3.5 py-1.5 rounded-xl text-xs font-semibold transition-colors">
                    <i class="fa-solid fa-cloud-arrow-down"></i>
                    <span>Download Paket Portal ZIP</span>
                </a>
                <span class="text-xs text-slate-400 hidden sm:inline">|</span>
                <span class="text-xs text-slate-300 hidden sm:inline"><i class="fa-solid fa-user-shield mr-1.5 text-indigo-400"></i><?= htmlspecialchars($_SESSION['ecosystem_admin']['name'] ?? 'Admin') ?></span>
                <a href="logout.php" class="text-xs bg-slate-800 hover:bg-rose-600/20 hover:text-rose-400 text-slate-300 px-3 py-1.5 rounded-xl border border-slate-700 transition-colors">
                    <i class="fa-solid fa-arrow-right-from-bracket mr-1"></i> Keluar
                </a>
            </div>
        </div>
    </header>

    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-8">
        <?php if (!empty($errorMsg)) : ?>
            <div class="p-4 rounded-2xl bg-rose-500/10 border border-rose-500/20 text-rose-300 text-sm flex items-center gap-3">
                <i class="fa-solid fa-circle-exclamation text-lg"></i>
                <span><?= htmlspecialchars($errorMsg) ?></span>
            </div>
        <?php endif; ?>

        <?php if (isset($_GET['msg']) && $_GET['msg'] === 'revoked') : ?>
            <div class="p-4 rounded-2xl bg-amber-500/10 border border-amber-500/20 text-amber-300 text-sm flex items-center gap-3">
                <i class="fa-solid fa-ban text-lg"></i>
                <span>Status lisensi berhasil dicabut (Revoked).</span>
            </div>
        <?php elseif (isset($_GET['msg']) && $_GET['msg'] === 'deleted') : ?>
            <div class="p-4 rounded-2xl bg-slate-800 border border-slate-700 text-slate-300 text-sm flex items-center gap-3">
                <i class="fa-solid fa-trash-can text-lg"></i>
                <span>Data lisensi berhasil dihapus.</span>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
            <div class="bg-slate-800/80 border border-slate-700/60 p-5 rounded-2xl shadow-sm">
                <div class="text-slate-400 text-xs font-semibold uppercase tracking-wider mb-1">Total Sekolah</div>
                <div class="text-2xl font-bold text-white"><?= count($schools) ?></div>
            </div>
            <div class="bg-slate-800/80 border border-slate-700/60 p-5 rounded-2xl shadow-sm">
                <div class="text-slate-400 text-xs font-semibold uppercase tracking-wider mb-1">Total Lisensi Diterbitkan</div>
                <div class="text-2xl font-bold text-white"><?= $totalLicenses ?></div>
            </div>
            <div class="bg-slate-800/80 border border-slate-700/60 p-5 rounded-2xl shadow-sm">
                <div class="text-emerald-400 text-xs font-semibold uppercase tracking-wider mb-1">Lisensi Aktif</div>
                <div class="text-2xl font-bold text-emerald-400"><?= $activeLicenses ?></div>
            </div>
            <div class="bg-slate-800/80 border border-slate-700/60 p-5 rounded-2xl shadow-sm">
                <div class="text-rose-400 text-xs font-semibold uppercase tracking-wider mb-1">Kedaluwarsa</div>
                <div class="text-2xl font-bold text-rose-400"><?= $expiredLicenses ?></div>
            </div>
        </div>

        <?php if ($actionResult) : ?>
            <div class="bg-gradient-to-br from-indigo-950/60 to-slate-900 border-2 border-indigo-500/40 rounded-2xl p-6 shadow-2xl relative">
                <div class="flex items-start justify-between gap-4 mb-4">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 rounded-xl bg-emerald-500/20 text-emerald-400 flex items-center justify-center">
                            <i class="fa-solid fa-check text-lg"></i>
                        </div>
                        <div>
                            <h3 class="text-lg font-bold text-white">Serial Key Kriptografis Berhasil Diterbitkan!</h3>
                            <p class="text-xs text-slate-400">Salin dan berikan serial di bawah ini kepada proktor sekolah untuk aktivasi.</p>
                        </div>
                    </div>
                    <button onclick="this.closest('.bg-gradient-to-br').remove()" class="text-slate-400 hover:text-white">
                        <i class="fa-solid fa-xmark text-lg"></i>
                    </button>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-4 gap-3 bg-slate-900/80 p-4 rounded-xl border border-slate-700/60 text-xs mb-4">
                    <div>
                        <span class="text-slate-400 block mb-0.5">Nama Sekolah:</span>
                        <span class="font-semibold text-white"><?= htmlspecialchars($actionResult['sekolah']) ?></span>
                    </div>
                    <div>
                        <span class="text-slate-400 block mb-0.5">NPSN:</span>
                        <span class="font-semibold text-indigo-400"><?= htmlspecialchars($actionResult['npsn']) ?></span>
                    </div>
                    <div>
                        <span class="text-slate-400 block mb-0.5">Masa Berlaku:</span>
                        <span class="font-semibold text-emerald-400"><?= $actionResult['durasi_bulan'] ?> Bulan (s/d <?= date('d M Y', strtotime($actionResult['expired_at'])) ?>)</span>
                    </div>
                    <div>
                        <span class="text-slate-400 block mb-0.5">Kode Registrasi:</span>
                        <span class="font-mono text-slate-300"><?= htmlspecialchars($actionResult['serial_code']) ?></span>
                    </div>
                </div>

                <div class="relative">
                    <textarea id="generatedTokenText" rows="3" readonly
                              class="w-full bg-slate-950/90 border border-slate-700 rounded-xl p-3 font-mono text-xs text-indigo-200 focus:outline-none select-all"><?= htmlspecialchars($actionResult['serial_key']) ?></textarea>
                </div>

                <div class="mt-4 flex flex-wrap items-center gap-3">
                    <button onclick="copyGeneratedToken()" class="bg-indigo-600 hover:bg-indigo-500 text-white px-4 py-2 rounded-xl text-xs font-semibold flex items-center gap-2 transition-colors">
                        <i class="fa-regular fa-copy"></i>
                        <span id="btnCopyLabel">Salin Serial Key</span>
                    </button>

                    <?php
                    $waText = "Halo Admin " . $actionResult['sekolah'] . ",\n\nBerikut adalah Serial Key Resmi Aktivasi CandyCBT Anda:\n\n*NPSN:* " . $actionResult['npsn'] . "\n*Masa Aktif:* " . $actionResult['durasi_bulan'] . " Bulan (s/d " . date('d-m-Y', strtotime($actionResult['expired_at'])) . ")\n*Serial Key:*\n" . $actionResult['serial_key'] . "\n\nSilakan masukkan kode tersebut di menu Aktivasi Sistem CBT Anda. Terima kasih!";
                    $waUrl = "https://api.whatsapp.com/send?text=" . rawurlencode($waText);
                    ?>
                    <a href="<?= $waUrl ?>" target="_blank" class="bg-emerald-600 hover:bg-emerald-500 text-white px-4 py-2 rounded-xl text-xs font-semibold flex items-center gap-2 transition-colors">
                        <i class="fa-brands fa-whatsapp text-sm"></i>
                        <span>Bagikan ke WhatsApp Proktor</span>
                    </a>
                </div>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <div class="bg-slate-800/80 border border-slate-700/60 rounded-2xl p-6 shadow-sm">
                <div class="flex items-center gap-3 mb-5">
                    <div class="w-8 h-8 rounded-lg bg-indigo-500/20 text-indigo-400 flex items-center justify-center">
                        <i class="fa-solid fa-key"></i>
                    </div>
                    <div>
                        <h2 class="text-base font-bold text-white">Generate Serial Baru</h2>
                        <p class="text-xs text-slate-400">Terbitkan serial aktivasi kriptografis</p>
                    </div>
                </div>

                <form method="POST" action="" class="space-y-4">
                    <input type="hidden" name="action" value="generate">

                    <div>
                        <label class="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-1.5">NPSN Sekolah (8 Digit)</label>
                        <input type="text" name="npsn" required placeholder="Contoh: 10203040"
                               class="w-full bg-slate-900/80 border border-slate-700 rounded-xl px-3.5 py-2 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500">
                    </div>

                    <div>
                        <label class="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-1.5">Nama Sekolah</label>
                        <input type="text" name="school_name" required placeholder="Contoh: SMAN 1 PARENGGEAN"
                               class="w-full bg-slate-900/80 border border-slate-700 rounded-xl px-3.5 py-2 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500">
                    </div>

                    <div>
                        <label class="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-1.5">Pilihan Masa Aktif</label>
                        <div class="grid grid-cols-2 gap-2 text-xs">
                            <label class="flex items-center gap-2 bg-slate-900/60 border border-slate-700 rounded-xl p-2.5 cursor-pointer hover:border-indigo-500 transition-colors">
                                <input type="radio" name="duration" value="1" class="text-indigo-600 focus:ring-0">
                                <div>
                                    <span class="block font-semibold text-white">1 Bulan</span>
                                    <span class="text-slate-400 text-[10px]">Ulangan Harian / PTS</span>
                                </div>
                            </label>
                            <label class="flex items-center gap-2 bg-slate-900/60 border border-indigo-500/60 bg-indigo-950/20 rounded-xl p-2.5 cursor-pointer hover:border-indigo-500 transition-colors">
                                <input type="radio" name="duration" value="3" checked class="text-indigo-600 focus:ring-0">
                                <div>
                                    <span class="block font-semibold text-indigo-300">3 Bulan</span>
                                    <span class="text-slate-400 text-[10px]">Asesmen Akhir / PAT</span>
                                </div>
                            </label>
                            <label class="flex items-center gap-2 bg-slate-900/60 border border-slate-700 rounded-xl p-2.5 cursor-pointer hover:border-indigo-500 transition-colors">
                                <input type="radio" name="duration" value="6" class="text-indigo-600 focus:ring-0">
                                <div>
                                    <span class="block font-semibold text-white">6 Bulan</span>
                                    <span class="text-slate-400 text-[10px]">1 Semester Penuh</span>
                                </div>
                            </label>
                            <label class="flex items-center gap-2 bg-slate-900/60 border border-slate-700 rounded-xl p-2.5 cursor-pointer hover:border-indigo-500 transition-colors">
                                <input type="radio" name="duration" value="12" class="text-indigo-600 focus:ring-0">
                                <div>
                                    <span class="block font-semibold text-white">1 Tahun</span>
                                    <span class="text-slate-400 text-[10px]">Lisensi Tahunan</span>
                                </div>
                            </label>
                        </div>
                    </div>

                    <div class="pt-2">
                        <button type="submit"
                                class="w-full bg-indigo-600 hover:bg-indigo-500 text-white font-semibold py-2.5 rounded-xl shadow-lg shadow-indigo-600/30 transition-all flex items-center justify-center gap-2 text-sm">
                            <i class="fa-solid fa-wand-magic-sparkles"></i>
                            <span>Generate Serial Key Sekarang</span>
                        </button>
                    </div>
                </form>
            </div>

            <div class="lg:col-span-2 bg-slate-800/80 border border-slate-700/60 rounded-2xl p-6 shadow-sm flex flex-col">
                <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-5">
                    <div>
                        <h2 class="text-base font-bold text-white">Daftar Lisensi Terdaftar</h2>
                        <p class="text-xs text-slate-400">Riwayat serial aktivasi sekolah klien</p>
                    </div>

                    <form method="GET" action="" class="w-full sm:w-64">
                        <div class="relative">
                            <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-slate-500">
                                <i class="fa-solid fa-magnifying-glass text-xs"></i>
                            </span>
                            <input type="text" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="Cari NPSN / Sekolah..."
                                   class="w-full bg-slate-900/80 border border-slate-700 rounded-xl pl-8 pr-3 py-1.5 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500">
                        </div>
                    </form>
                </div>

                <div class="overflow-x-auto -mx-6 flex-1">
                    <table class="w-full text-left text-xs">
                        <thead>
                            <tr class="border-y border-slate-700/60 bg-slate-900/40 text-slate-400 font-semibold uppercase tracking-wider">
                                <th class="py-3 px-4">Sekolah & NPSN</th>
                                <th class="py-3 px-4">Kode Serial</th>
                                <th class="py-3 px-4">Durasi</th>
                                <th class="py-3 px-4">Expired</th>
                                <th class="py-3 px-4">Status</th>
                                <th class="py-3 px-4 text-right">Aksi</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-700/40">
                            <?php if (empty($licenses)) : ?>
                                <tr>
                                    <td colspan="6" class="text-center py-8 text-slate-500">
                                        <i class="fa-solid fa-inbox text-3xl mb-2 block text-slate-600"></i>
                                        Belum ada data lisensi yang diterbitkan.
                                    </td>
                                </tr>
                            <?php else : ?>
                                <?php foreach ($licenses as $lic) : 
                                    $isExpired = ($lic['expires_at'] < $today);
                                    $isRevoked = ($lic['status'] === 'REVOKED');
                                    $remainingDays = round((strtotime($lic['expires_at']) - strtotime($today)) / 86400);
                                ?>
                                    <tr class="hover:bg-slate-700/20 transition-colors">
                                        <td class="py-3 px-4">
                                            <div class="font-bold text-white"><?= htmlspecialchars($lic['school_name']) ?></div>
                                            <div class="text-[11px] text-indigo-400 font-mono">NPSN: <?= htmlspecialchars($lic['npsn']) ?></div>
                                        </td>
                                        <td class="py-3 px-4 font-mono text-slate-300">
                                            <?= htmlspecialchars($lic['serial_code']) ?>
                                        </td>
                                        <td class="py-3 px-4">
                                            <span class="text-slate-300 font-medium"><?= $lic['duration_months'] ?> Bulan</span>
                                        </td>
                                        <td class="py-3 px-4 text-slate-300">
                                            <div><?= date('d M Y', strtotime($lic['expires_at'])) ?></div>
                                            <?php if (!$isRevoked && !$isExpired) : ?>
                                                <div class="text-[10px] text-emerald-400"><?= $remainingDays ?> hari lagi</div>
                                            <?php endif; ?>
                                        </td>
                                        <td class="py-3 px-4">
                                            <?php if ($isRevoked) : ?>
                                                <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold bg-rose-500/10 text-rose-400 border border-rose-500/20">Dicabut</span>
                                            <?php elseif ($isExpired) : ?>
                                                <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold bg-amber-500/10 text-amber-400 border border-amber-500/20">Expired</span>
                                            <?php else : ?>
                                                <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Aktif</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="py-3 px-4 text-right">
                                            <div class="flex items-center justify-end gap-1.5">
                                                <button onclick="copyToClipboard('<?= htmlspecialchars($lic['serial_key'], ENT_QUOTES) ?>')" title="Salin Serial Token"
                                                        class="p-1.5 rounded-lg bg-slate-700/60 hover:bg-indigo-600 text-slate-300 hover:text-white transition-colors">
                                                    <i class="fa-regular fa-copy"></i>
                                                </button>
                                                <?php if (!$isRevoked) : ?>
                                                    <form method="POST" action="" onsubmit="return confirm('Apakah Anda yakin ingin mencabut lisensi ini?')" class="inline">
                                                        <input type="hidden" name="action" value="revoke">
                                                        <input type="hidden" name="id" value="<?= $lic['id'] ?>">
                                                        <button type="submit" title="Cabut Lisensi" class="p-1.5 rounded-lg bg-slate-700/60 hover:bg-amber-600 text-slate-300 hover:text-white transition-colors">
                                                            <i class="fa-solid fa-ban"></i>
                                                        </button>
                                                    </form>
                                                <?php endif; ?>
                                                <form method="POST" action="" onsubmit="return confirm('Hapus permanen riwayat lisensi ini?')" class="inline">
                                                    <input type="hidden" name="action" value="delete">
                                                    <input type="hidden" name="id" value="<?= $lic['id'] ?>">
                                                    <button type="submit" title="Hapus Data" class="p-1.5 rounded-lg bg-slate-700/60 hover:bg-rose-600 text-slate-300 hover:text-white transition-colors">
                                                        <i class="fa-regular fa-trash-can"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>

    <footer class="border-t border-slate-800 py-6 text-center text-xs text-slate-500">
        &copy; <?= date('Y') ?> CBT Ecosystem Central &bull; Standalone DRM & License Management System
    </footer>

    <script>
        function copyGeneratedToken() {
            var el = document.getElementById('generatedTokenText');
            el.select();
            document.execCommand('copy');
            var btn = document.getElementById('btnCopyLabel');
            var old = btn.innerText;
            btn.innerText = 'Tersalin ke Clipboard!';
            setTimeout(function() { btn.innerText = old; }, 2000);
        }

        function copyToClipboard(text) {
            var temp = document.createElement('textarea');
            temp.value = text;
            document.body.appendChild(temp);
            temp.select();
            document.execCommand('copy');
            document.body.removeChild(temp);
            alert('Serial Key berhasil disalin ke clipboard!');
        }
    </script>
</body>
</html>
