<?php
session_start();
include 'cfg.php';

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: admin_login.php");
    exit();
}

// Update struktur tabel jika kolom belum ada
try {
    $columns = $pdo->query("SHOW COLUMNS FROM vouchers LIKE 'circle_count'");
    if ($columns->rowCount() == 0) {
        $pdo->exec("ALTER TABLE vouchers ADD COLUMN circle_count INT DEFAULT 9 AFTER is_winner");
        error_log("Column circle_count added to vouchers");
    }
    $columns = $pdo->query("SHOW COLUMNS FROM vouchers LIKE 'bomb_position'");
    if ($columns->rowCount() == 0) {
        $pdo->exec("ALTER TABLE vouchers ADD COLUMN bomb_position INT DEFAULT 0 AFTER circle_count");
        error_log("Column bomb_position added to vouchers");
    }
    $columns = $pdo->query("SHOW COLUMNS FROM vouchers LIKE 'used_by'");
    if ($columns->rowCount() == 0) {
        $pdo->exec("ALTER TABLE vouchers ADD COLUMN used_by VARCHAR(100) DEFAULT NULL AFTER is_used");
        error_log("Column used_by added to vouchers");
    }
    $columns = $pdo->query("SHOW COLUMNS FROM vouchers LIKE 'used_at'");
    if ($columns->rowCount() == 0) {
        $pdo->exec("ALTER TABLE vouchers ADD COLUMN used_at TIMESTAMP NULL DEFAULT NULL AFTER used_by");
        error_log("Column used_at added to vouchers");
    }
} catch (PDOException $e) {
    error_log("Error updating table structure: " . $e->getMessage());
}

$limit = 10;
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$page = max($page, 1);
$offset = ($page - 1) * $limit;

$search_query = '';
$search_param = '';
if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search_query = "WHERE code LIKE :search OR used_by LIKE :search";
    $search_param = '%' . $_GET['search'] . '%';
}

$total = (int) $pdo->query("SELECT COUNT(*) FROM vouchers")->fetchColumn();
$totalPages = max(1, (int) ceil($total / $limit));

// ==================== FUNGSI GENERATE KODE VOUCHER ====================
function generateVoucherCode() {
    $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // Angka + Huruf Besar
    $segments = [];

    for ($i = 0; $i < 3; $i++) {
        $segment = '';
        for ($j = 0; $j < 4; $j++) {
            $segment .= $chars[random_int(0, strlen($chars) - 1)];
        }
        $segments[] = $segment;
    }

    return implode('-', $segments); // Format: GK4M-N9XW-7RBT
}
// ===================================================================

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_voucher'])) {
    $is_winner = isset($_POST['is_winner']) ? 1 : 0;
    $circle_count = (int) $_POST['circle_count'];
    if ($circle_count < 3) {
        $circle_count = 9;
    }

    if ($is_winner) {
        $bomb_click = 0;
    } else {
        $bomb_click = rand(1, $circle_count - 1);
    }

    // Generate kode voucher dengan format baru
    $code = generateVoucherCode();

    $stmt = $pdo->prepare("INSERT INTO vouchers (code, is_winner, circle_count, bomb_position, is_used)
                           VALUES (?, ?, ?, ?, 0)");
    $stmt->execute([$code, $is_winner, $circle_count, $bomb_click]);

    header("Location: admin.php?success=1");
    exit();
}

if (isset($_GET['delete'])) {
    $voucher_id = $_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM vouchers WHERE id = ?");
    $stmt->execute([$voucher_id]);
    header("Location: admin.php?page=" . $page);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['remove_all_vouchers'])) {
    $stmt = $pdo->prepare("DELETE FROM vouchers");
    $stmt->execute();
    header("Location: admin.php?page=" . $page);
    exit();
}

$query = "SELECT * FROM vouchers ";
if ($search_query) {
    $query .= $search_query;
}
$query .= " ORDER BY id DESC LIMIT $limit OFFSET $offset";

$stmt = $pdo->prepare($query);
if ($search_query) {
    $stmt->bindParam(':search', $search_param, PDO::PARAM_STR);
}
$stmt->execute();
$vouchers = $stmt->fetchAll();

$winnerCount = 0;
$usedCount = 0;
foreach ($vouchers as $voucherRow) {
    if (!empty($voucherRow['is_winner'])) {
        $winnerCount++;
    }
    if (!empty($voucherRow['is_used'])) {
        $usedCount++;
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - Kelola Voucher</title>
    <style>
        :root {
            --bg-top: #10273d;
            --bg-bottom: #08111d;
            --panel: rgba(248, 251, 255, 0.97);
            --panel-border: rgba(15, 38, 60, 0.08);
            --text: #142638;
            --muted: #647b8d;
            --gold: #df9f36;
            --blue: #2d79c7;
            --blue-dark: #1f5b96;
            --green: #1f9360;
            --red: #cf5144;
            --shadow: rgba(0, 0, 0, 0.16);
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: "Trebuchet MS", "Segoe UI", sans-serif;
            color: var(--text);
            line-height: 1.6;
            background:
                radial-gradient(circle at top, rgba(223, 159, 54, 0.12), transparent 22%),
                radial-gradient(circle at bottom right, rgba(45, 121, 199, 0.12), transparent 26%),
                linear-gradient(180deg, var(--bg-top), var(--bg-bottom));
        }
        .page-shell {
            max-width: 1240px;
            margin: 0 auto;
            padding: 20px 14px 28px;
        }
        .navbar {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 16px;
            margin-bottom: 18px;
            padding: 12px 18px;
            border: 1px solid rgba(255, 255, 255, 0.12);
            border-radius: 18px;
            background: rgba(7, 17, 27, 0.72);
            backdrop-filter: blur(12px);
            box-shadow: 0 16px 30px rgba(0, 0, 0, 0.16);
        }
        .navbar-brand img {
            width: clamp(112px, 18vw, 150px);
            height: auto;
            display: block;
        }
        .navbar-title {
            color: rgba(247, 251, 255, 0.74);
            font-size: 13px;
            font-weight: 800;
            letter-spacing: 0.12em;
            text-transform: uppercase;
        }
        .admin-container {
            padding: 22px;
            background: var(--panel);
            border: 1px solid var(--panel-border);
            border-radius: 28px;
            box-shadow: 0 28px 50px var(--shadow);
        }
        .header-copy h1 {
            margin: 0;
            font-size: 34px;
            line-height: 1.05;
            color: #13263a;
        }
        .header-copy p {
            margin-top: 10px;
            color: var(--muted);
            font-size: 15px;
        }
        .success-box {
            margin-top: 18px;
            padding: 12px 14px;
            border-radius: 16px;
            color: #17603e;
            background: rgba(31, 147, 96, 0.12);
            border: 1px solid rgba(31, 147, 96, 0.2);
            font-weight: 700;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            gap: 14px;
            margin: 22px 0;
        }
        .stat-card {
            padding: 16px;
            border-radius: 20px;
            background: #f4f8fc;
            border: 1px solid rgba(15, 38, 60, 0.06);
        }
        .stat-label {
            display: block;
            color: var(--muted);
            font-size: 12px;
            letter-spacing: 0.08em;
            text-transform: uppercase;
        }
        .stat-value {
            display: block;
            margin-top: 8px;
            color: #142638;
            font-size: 26px;
            font-weight: 900;
        }
        .tools-grid {
            display: grid;
            grid-template-columns: 1.2fr 1fr;
            gap: 18px;
            margin-bottom: 22px;
        }
        .panel-card {
            padding: 18px;
            border-radius: 22px;
            background: #f8fbfe;
            border: 1px solid rgba(15, 38, 60, 0.06);
        }
        .panel-title {
            margin: 0 0 10px;
            font-size: 20px;
            color: #13263a;
        }
        .panel-subtitle {
            margin: 0 0 14px;
            color: var(--muted);
            font-size: 14px;
        }
        .form-grid {
            display: grid;
            grid-template-columns: minmax(0, 1.2fr) auto auto;
            gap: 12px;
            align-items: end;
        }
        .search-stack {
            display: grid;
            gap: 12px;
        }
        .search-grid {
            display: grid;
            grid-template-columns: 1fr auto;
            gap: 12px;
            align-items: end;
        }
        .field {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .field label, .checkbox-wrap {
            color: #25394b;
            font-size: 14px;
            font-weight: 700;
        }
        .checkbox-wrap {
            display: flex;
            align-items: center;
            gap: 10px;
            min-height: 48px;
            padding: 0 2px;
        }
        select, input[type="text"] {
            width: 100%;
            min-height: 46px;
            padding: 12px 14px;
            border: 1px solid rgba(15, 38, 60, 0.12);
            border-radius: 14px;
            outline: none;
            font-size: 14px;
            color: #142638;
            background: #fff;
        }
        select:focus, input[type="text"]:focus {
            border-color: rgba(45, 121, 199, 0.55);
            box-shadow: 0 0 0 4px rgba(45, 121, 199, 0.12);
        }
        button, .btn {
            min-height: 46px;
            padding: 12px 18px;
            border: none;
            border-radius: 14px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 800;
            letter-spacing: 0.02em;
            transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease;
        }
        button:hover, .btn:hover {
            transform: translateY(-1px);
            filter: brightness(1.02);
        }
        .btn-primary {
            color: #fff;
            background: linear-gradient(180deg, var(--blue), var(--blue-dark));
            box-shadow: 0 14px 22px rgba(45, 121, 199, 0.18);
        }
        .btn-danger {
            color: #fff;
            background: linear-gradient(180deg, #e3675b, var(--red));
            box-shadow: 0 14px 22px rgba(207, 81, 68, 0.16);
        }
        .table-wrap {
            overflow-x: auto;
            border: 1px solid rgba(15, 38, 60, 0.06);
            border-radius: 20px;
            background: #fff;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }
        table th {
            padding: 14px 16px;
            text-align: left;
            color: #28445b;
            background: #f3f7fb;
            font-size: 12px;
            font-weight: 800;
            letter-spacing: 0.08em;
            text-transform: uppercase;
        }
        table td {
            padding: 14px 16px;
            border-top: 1px solid #eef3f8;
            vertical-align: middle;
        }
        .code-cell {
            font-weight: 900;
            color: #193149;
            letter-spacing: 0.04em;
        }
        .status, .circle-badge, .bomb-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 6px 10px;
            border-radius: 999px;
            font-size: 12px;
            font-weight: 800;
            white-space: nowrap;
        }
        .status-winner { background: rgba(31, 147, 96, 0.12); color: #17603e; }
        .status-loser { background: rgba(207, 81, 68, 0.12); color: #8e2f28; }
        .status-used { background: rgba(45, 121, 199, 0.12); color: #1d5a95; }
        .status-unused { background: rgba(100, 123, 141, 0.12); color: #4a6174; }
        .circle-badge { background: rgba(45, 121, 199, 0.12); color: #1d5a95; }
        .bomb-badge { background: rgba(207, 81, 68, 0.12); color: #8e2f28; }
        .action-link {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 56px;
            height: 36px;
            border-radius: 12px;
            text-decoration: none;
            font-size: 13px;
            font-weight: 800;
            background: rgba(207, 81, 68, 0.12);
            color: #8e2f28;
        }
        .empty-state {
            padding: 40px 18px;
            text-align: center;
            color: var(--muted);
        }
        @media (max-width: 980px) {
            .stats-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
            .tools-grid { grid-template-columns: 1fr; }
            .form-grid, .search-grid { grid-template-columns: 1fr; }
        }
        @media (max-width: 640px) {
            .admin-container { padding: 16px; border-radius: 22px; }
            .header-copy h1 { font-size: 28px; }
            .stats-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="page-shell">
        <header class="navbar">
            <div class="navbar-brand">
                <img src="logo.png" alt="Logo">
            </div>
            <div class="navbar-title">Admin Dashboard</div>
        </header>

        <div class="admin-container">
            <div class="header-copy">
                <h1>Kelola voucher dan permainan dari satu dashboard.</h1>
                <p>Buat voucher baru, cari riwayat penggunaan, dan pantau status voucher aktif dengan tampilan yang lebih rapi.</p>
            </div>

            <?php if (isset($_GET['success'])): ?>
                <div class="success-box">Voucher baru berhasil dibuat dan siap digunakan.</div>
            <?php endif; ?>

            <div class="stats-grid">
                <div class="stat-card">
                    <span class="stat-label">Voucher Di Halaman Ini</span>
                    <span class="stat-value"><?= count($vouchers) ?></span>
                </div>
                <div class="stat-card">
                    <span class="stat-label">Voucher Menang</span>
                    <span class="stat-value"><?= $winnerCount ?></span>
                </div>
                <div class="stat-card">
                    <span class="stat-label">Sudah Digunakan</span>
                    <span class="stat-value"><?= $usedCount ?></span>
                </div>
                <div class="stat-card">
                    <span class="stat-label">Total Semua Voucher</span>
                    <span class="stat-value"><?= $total ?></span>
                </div>
            </div>

            <div class="tools-grid">
                <!-- Generate Voucher -->
                <div class="panel-card">
                    <h2 class="panel-title">Generate Voucher</h2>
                    <p class="panel-subtitle">Pilih mode permainan dan tentukan apakah voucher ini termasuk voucher pemenang.</p>
                    <form method="POST" class="form-grid">
                        <div class="field">
                            <label for="circle_count">Mode permainan</label>
                            <select name="circle_count" id="circle_count" required>
                                <option value="3">3 Lingkaran - Mudah</option>
                                <option value="6">6 Lingkaran - Sedang</option>
                                <option value="9">9 Lingkaran - Sulit</option>
                                <option value="12">12 Lingkaran - Ekstrim</option>
                            </select>
                        </div>
                        <label class="checkbox-wrap">
                            <input type="checkbox" name="is_winner">
                            Voucher pemenang
                        </label>
                        <button type="submit" name="add_voucher" class="btn btn-primary">Generate</button>
                    </form>
                </div>

                <!-- Pencarian & Aksi -->
                <div class="panel-card">
                    <h2 class="panel-title">Pencarian & Aksi</h2>
                    <p class="panel-subtitle">Cari voucher berdasarkan kode atau nama pemain, lalu kelola data yang tersimpan.</p>
                    <div class="search-stack">
                        <form method="GET" action="admin.php" class="search-grid">
                            <div class="field">
                                <label for="search">Cari voucher</label>
                                <input type="text" id="search" name="search" placeholder="Masukkan kode voucher atau nama pemain" value="<?= isset($_GET['search']) ? htmlspecialchars($_GET['search']) : '' ?>">
                            </div>
                            <button type="submit" class="btn btn-primary">Cari</button>
                        </form>
                        <form method="POST">
                            <button type="submit" name="remove_all_vouchers" class="btn btn-danger" onclick="return confirm('Yakin ingin menghapus semua voucher?')">Hapus Semua Voucher</button>
                        </form>
                    </div>
                </div>
            </div>

            <?php if (count($vouchers) > 0): ?>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Kode Voucher</th>
                                <th>Mode</th>
                                <th>Hasil</th>
                                <th>Posisi Bom</th>
                                <th>Pemain</th>
                                <th>Waktu Pakai</th>
                                <th>Pemakaian</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($vouchers as $voucher): ?>
                                <tr>
                                    <td><?= $voucher['id'] ?></td>
                                    <td class="code-cell"><?= htmlspecialchars($voucher['code']) ?></td>
                                    <td><span class="circle-badge"><?= (int) ($voucher['circle_count'] ?? 9) ?> Lingkaran</span></td>
                                    <td>
                                        <span class="status <?= $voucher['is_winner'] ? 'status-winner' : 'status-loser' ?>">
                                            <?= $voucher['is_winner'] ? 'Pemenang' : 'Non-pemenang' ?>
                                        </span>
                                    </td>
                                    <td><span class="bomb-badge">Posisi <?= ((int) ($voucher['bomb_position'] ?? 0)) + 1 ?></span></td>
                                    <td><?= $voucher['used_by'] ? htmlspecialchars($voucher['used_by']) : '-' ?></td>
                                    <td><?= $voucher['used_at'] ? date('d/m/Y H:i', strtotime($voucher['used_at'])) : '-' ?></td>
                                    <td>
                                        <span class="status <?= $voucher['is_used'] ? 'status-used' : 'status-unused' ?>">
                                            <?= $voucher['is_used'] ? 'Sudah digunakan' : 'Belum digunakan' ?>
                                        </span>
                                    </td>
                                    <td>
                                        <a class="action-link" href="admin.php?delete=<?= $voucher['id'] ?>&page=<?= $page ?>" onclick="return confirm('Hapus voucher ini?')">Hapus</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="empty-state">
                    Belum ada voucher yang tersedia untuk ditampilkan.
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>