<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/database.php';

requireRole('ADMIN');

$pdo = getDatabaseConnection();

// Fetch Users
$userStmt = $pdo->query("SELECT id, name, email, role, createdAt FROM users ORDER BY createdAt DESC");
$users = $userStmt->fetchAll();

// Fetch Events
$eventStmt = $pdo->query("SELECT * FROM events ORDER BY createdAt DESC");
$events = $eventStmt->fetchAll();
$pendingEvents = array_filter($events, fn($e) => $e['status'] === 'PENDING_APPROVAL');

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_csrf();
    $action = $_POST['action'] ?? '';
    
    if ($action === 'create_user') {
        $name = $_POST['name'] ?? '';
        $email = $_POST['email'] ?? '';
        $password = $_POST['password'] ?? '';
        $role = $_POST['role'] ?? 'ORGANIZER';
        
        if ($name && $email && $password && in_array($role, ['ORGANIZER', 'FINANCE'])) {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (id, name, email, password, role) VALUES (UUID(), ?, ?, ?, ?)");
            $stmt->execute([$name, $email, $hash, $role]);
            header("Location: dashboard.php");
            exit;
        }
    } elseif ($action === 'delete_user') {
        $userId = $_POST['user_id'] ?? '';
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ? AND role != 'ADMIN'");
        $stmt->execute([$userId]);
        header("Location: dashboard.php");
        exit;
    } elseif ($action === 'approve_event') {
        $eventId = $_POST['event_id'] ?? '';
        $stmt = $pdo->prepare("UPDATE events SET status = 'PUBLISHED' WHERE id = ?");
        $stmt->execute([$eventId]);
        header("Location: dashboard.php");
        exit;
    } elseif ($action === 'reject_event') {
        $eventId = $_POST['event_id'] ?? '';
        $stmt = $pdo->prepare("UPDATE events SET status = 'CANCELLED' WHERE id = ?");
        $stmt->execute([$eventId]);
        header("Location: dashboard.php");
        exit;
    } elseif ($action === 'delete_event') {
        $eventId = $_POST['event_id'] ?? '';
        $stmt = $pdo->prepare("DELETE FROM events WHERE id = ?");
        $stmt->execute([$eventId]);
        header("Location: dashboard.php");
        exit;
    }
}

function formatFee($fee) { return $fee == 0 ? 'Free' : '₹' . number_format($fee); }
function formatPrize($prize) { return '₹' . number_format($prize); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - <?= APP_NAME ?></title>
    <link rel="stylesheet" href="<?= APP_URL ?>/assets/css/style.css">
    <script src="https://unpkg.com/lucide@latest"></script>
</head>
<body class="bg-slate-950 text-slate-200 antialiased selection:bg-cyan-500/30 selection:text-cyan-200 min-h-screen">
    <div class="min-h-screen bg-cyber-grid py-10 px-4 sm:px-6 lg:px-8 font-tech">
        <div class="max-w-7xl mx-auto">
            <!-- Header -->
            <div class="flex flex-wrap items-center justify-between gap-4 mb-8 border-b border-cyan-500/20 pb-6">
                <div>
                    <div class="flex items-center gap-2 text-cyan-400 text-xs font-mono-cyber uppercase mb-1">
                        <i data-lucide="shield-check" class="w-4 h-4 text-purple-400"></i> SUPERNOVA 2.0 • MASTER SYSTEM CONTROL PANEL
                    </div>
                    <h1 class="text-3xl sm:text-4xl font-heading-cyber font-extrabold text-slate-100">
                        ADMINISTRATOR CONTROL DESK
                    </h1>
                </div>
                <div class="flex items-center gap-3">
                    <a href="javascript:history.back()" class="px-4 py-2 rounded-xl glass-panel text-slate-300 hover:text-cyan-400 text-xs font-mono-cyber font-semibold flex items-center gap-1.5 border border-cyan-500/20">
                        <i data-lucide="arrow-left" class="w-4 h-4 text-cyan-400"></i> BACK
                    </a>
                    <a href="<?= APP_URL ?>/admin/dashboard.php" class="px-4 py-2 rounded-xl glass-panel text-purple-400 hover:text-white text-xs font-mono-cyber font-semibold flex items-center gap-1.5 border border-purple-500/20">
                        <i data-lucide="shield-check" class="w-4 h-4 text-purple-400"></i> ADMIN DASHBOARD
                    </a>
                    <a href="dashboard.php" class="p-2.5 rounded-xl glass-panel text-cyan-400 hover:text-white border border-cyan-500/20" title="Refresh">
                        <i data-lucide="refresh-cw" class="w-4 h-4"></i>
                    </a>
                    <a href="<?= APP_URL ?>/admin/logout.php" class="px-4 py-2 rounded-xl glass-panel text-slate-400 hover:text-red-400 text-xs font-mono-cyber font-semibold border border-white/10">
                        SIGN OUT
                    </a>
                </div>
            </div>

            <!-- Pending Approvals Alert -->
            <?php if (count($pendingEvents) > 0): ?>
            <div class="mb-8 p-6 rounded-3xl bg-amber-500/10 border border-amber-500/30 text-amber-300 shadow-glow-cyan flex flex-wrap items-center justify-between gap-4">
                <div class="flex items-center gap-3">
                    <i data-lucide="clock" class="w-6 h-6 text-amber-400 shrink-0"></i>
                    <div>
                        <h4 class="font-heading-cyber font-bold text-lg text-white">
                            <?= count($pendingEvents) ?> EVENT PROPOSAL(S) AWAITING YOUR APPROVAL
                        </h4>
                        <p class="text-xs text-amber-200">Organizers have proposed new event templates requiring admin publishing.</p>
                    </div>
                </div>
                <a href="#event-approvals" class="px-4 py-2 rounded-xl bg-amber-400 text-slate-950 font-mono-cyber font-bold text-xs">
                    VIEW PENDING PROPOSALS 👇
                </a>
            </div>
            <?php endif; ?>

            <!-- Quick Portal Cards -->
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-10">
                <a href="<?= APP_URL ?>/organizer/dashboard.php" class="glass-panel p-6 rounded-2xl border border-cyan-500/20 hover:border-cyan-400 transition-all flex items-center justify-between group">
                    <div>
                        <span class="text-xs text-cyan-400 font-mono-cyber uppercase block">Module</span>
                        <h3 class="text-lg font-heading-cyber font-bold text-slate-100 group-hover:text-cyan-400">ORGANIZER PORTAL</h3>
                    </div>
                    <i data-lucide="calendar" class="w-8 h-8 text-cyan-400"></i>
                </a>
                <a href="<?= APP_URL ?>/finance/dashboard.php" class="glass-panel p-6 rounded-2xl border border-cyan-500/20 hover:border-emerald-400 transition-all flex items-center justify-between group">
                    <div>
                        <span class="text-xs text-emerald-400 font-mono-cyber uppercase block">Module</span>
                        <h3 class="text-lg font-heading-cyber font-bold text-slate-100 group-hover:text-emerald-400">FINANCE REVENUE</h3>
                    </div>
                    <i data-lucide="dollar-sign" class="w-8 h-8 text-emerald-400"></i>
                </a>
            </div>

            <!-- Event Approval Section -->
            <div id="event-approvals-queue" class="glass-panel p-6 rounded-3xl border border-amber-500/30 shadow-glow-amber mb-10 bg-amber-500/5">
                <div class="flex items-center justify-between mb-6">
                    <h3 class="text-xl font-heading-cyber font-bold text-amber-400 flex items-center gap-2">
                        <i data-lucide="clock" class="w-5 h-5 text-amber-400"></i> EVENT APPROVAL REQUESTS (<?= count($pendingEvents) ?> PENDING)
                    </h3>
                    <span class="px-3 py-1 rounded-full bg-amber-500/10 text-amber-400 border border-amber-500/30 text-xs font-mono-cyber font-bold uppercase">
                        APPROVAL DESK
                    </span>
                </div>

                <?php if (count($pendingEvents) === 0): ?>
                <div class="p-8 rounded-2xl bg-slate-900/60 border border-white/5 text-center text-slate-400 font-tech flex flex-col items-center gap-2">
                    <i data-lucide="check-circle-2" class="w-8 h-8 text-emerald-400/60"></i>
                    <p class="text-sm font-semibold text-slate-300 font-mono-cyber">No Pending Event Requests</p>
                    <p class="text-xs text-slate-500">All event proposals submitted by organizers have been reviewed and published.</p>
                </div>
                <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="w-full text-left text-xs text-slate-300">
                        <thead class="bg-amber-900/30 text-amber-400 uppercase text-[10px] font-mono-cyber font-bold">
                            <tr>
                                <th class="p-4 rounded-l-xl">EVENT TITLE</th>
                                <th class="p-4">CATEGORY</th>
                                <th class="p-4">REGISTRATION FEE</th>
                                <th class="p-4">VENUE & DATE</th>
                                <th class="p-4 rounded-r-xl text-right">ADMIN DECISION</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-amber-500/10 font-tech">
                            <?php foreach ($pendingEvents as $evt): ?>
                            <tr class="hover:bg-amber-500/10 transition-colors">
                                <td class="p-4 font-bold text-slate-100 text-sm"><?= htmlspecialchars($evt['title']) ?></td>
                                <td class="p-4 text-purple-400 font-semibold"><?= htmlspecialchars($evt['category']) ?></td>
                                <td class="p-4 font-mono-cyber">
                                    <div class="text-amber-400 font-semibold"><?= formatFee($evt['registrationFee']) ?></div>
                                </td>
                                <td class="p-4 text-slate-300">
                                    <div><?= htmlspecialchars($evt['eventDate']) ?></div>
                                    <div class="text-[10px] text-amber-400 font-mono-cyber"><?= htmlspecialchars($evt['venue']) ?></div>
                                </td>
                                <td class="p-4 text-right flex justify-end gap-2">
                                    <form method="POST" style="display:inline;">
                                        <input type="hidden" name="action" value="approve_event"><?= csrf_field() ?>
                                        <input type="hidden" name="event_id" value="<?= $evt['id'] ?>">
                                        <button type="submit" class="px-3 py-1.5 rounded-lg bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500 hover:text-slate-950 font-mono-cyber font-bold text-xs transition-all border border-emerald-500/30">✔ APPROVE</button>
                                    </form>
                                    <form method="POST" style="display:inline;">
                                        <input type="hidden" name="action" value="reject_event"><?= csrf_field() ?>
                                        <input type="hidden" name="event_id" value="<?= $evt['id'] ?>">
                                        <button type="submit" class="px-3 py-1.5 rounded-lg bg-red-500/10 text-red-400 hover:bg-red-500 hover:text-white font-mono-cyber font-bold text-xs transition-all border border-red-500/20">✕ REJECT</button>
                                    </form>
                                    <a href="<?= APP_URL ?>/events/details.php?slug=<?= htmlspecialchars($evt['slug']) ?>" target="_blank" class="inline-block p-1.5 rounded-lg bg-slate-800 text-slate-300 hover:text-cyan-400 border border-white/10" title="Preview Public Page">
                                        <i data-lucide="eye" class="w-3.5 h-3.5"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>

            <!-- Publishing Desk Section -->
            <div id="publishing-desk" class="glass-panel p-6 rounded-3xl border border-cyan-500/20 shadow-glow-cyan mb-10">
                <h3 class="text-xl font-heading-cyber font-bold text-slate-100 mb-6 flex items-center gap-2">
                    <i data-lucide="check-circle-2" class="w-5 h-5 text-cyan-400"></i> PUBLISHING DESK (<?= count($events) ?>)
                </h3>

                <div class="overflow-x-auto">
                    <table class="w-full text-left text-xs text-slate-300">
                        <thead class="bg-slate-900/90 text-cyan-400 uppercase text-[10px] font-mono-cyber font-bold">
                            <tr>
                                <th class="p-4 rounded-l-xl">EVENT TITLE</th>
                                <th class="p-4">CATEGORY</th>
                                <th class="p-4">REGISTRATION FEE</th>
                                <th class="p-4">VENUE & DATE</th>
                                <th class="p-4">STATUS</th>
                                <th class="p-4 rounded-r-xl text-right">ADMIN DECISION</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-white/5 font-tech">
                            <?php foreach ($events as $evt): ?>
                            <tr class="hover:bg-cyan-500/5 transition-colors">
                                <td class="p-4 font-bold text-slate-100 text-sm"><?= htmlspecialchars($evt['title']) ?></td>
                                <td class="p-4 text-purple-400 font-semibold"><?= htmlspecialchars($evt['category']) ?></td>
                                <td class="p-4 font-mono-cyber">
                                    <div class="text-cyan-400 font-semibold"><?= formatFee($evt['registrationFee']) ?></div>
                                </td>
                                <td class="p-4 text-slate-300">
                                    <div><?= htmlspecialchars($evt['eventDate']) ?></div>
                                    <div class="text-[10px] text-cyan-400 font-mono-cyber"><?= htmlspecialchars($evt['venue']) ?></div>
                                </td>
                                <td class="p-4">
                                    <span class="px-3 py-1 rounded-full text-[10px] font-mono-cyber font-bold uppercase inline-flex items-center gap-1 <?= 
                                        $evt['status'] === 'PUBLISHED' ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 
                                        ($evt['status'] === 'PENDING_APPROVAL' ? 'bg-amber-500/10 text-amber-400 border border-amber-500/30' : 'bg-red-500/10 text-red-400 border border-red-500/30') 
                                    ?>">
                                        <?= $evt['status'] === 'PUBLISHED' ? 'LIVE ON SITE' : ($evt['status'] === 'PENDING_APPROVAL' ? 'PENDING APPROVAL' : htmlspecialchars($evt['status'])) ?>
                                    </span>
                                </td>
                                <td class="p-4 text-right flex justify-end gap-2">
                                    <?php if ($evt['status'] !== 'PUBLISHED'): ?>
                                    <form method="POST" style="display:inline;">
                                        <input type="hidden" name="action" value="approve_event"><?= csrf_field() ?>
                                        <input type="hidden" name="event_id" value="<?= $evt['id'] ?>">
                                        <button type="submit" class="px-3 py-1.5 rounded-lg bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500 hover:text-slate-950 font-mono-cyber font-bold text-xs transition-all border border-emerald-500/30">✔ APPROVE</button>
                                    </form>
                                    <?php endif; ?>
                                    <?php if ($evt['status'] === 'PENDING_APPROVAL'): ?>
                                    <form method="POST" style="display:inline;">
                                        <input type="hidden" name="action" value="reject_event"><?= csrf_field() ?>
                                        <input type="hidden" name="event_id" value="<?= $evt['id'] ?>">
                                        <button type="submit" class="px-3 py-1.5 rounded-lg bg-red-500/10 text-red-400 hover:bg-red-500 hover:text-white font-mono-cyber font-bold text-xs transition-all border border-red-500/20">✕ REJECT</button>
                                    </form>
                                    <?php endif; ?>
                                    <a href="<?= APP_URL ?>/events/details.php?slug=<?= htmlspecialchars($evt['slug']) ?>" target="_blank" class="inline-block p-1.5 rounded-lg bg-slate-800 text-slate-300 hover:text-cyan-400 border border-white/10" title="Preview Public Page">
                                        <i data-lucide="eye" class="w-3.5 h-3.5"></i>
                                    </a>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Permanently delete this event?');">
                                        <input type="hidden" name="action" value="delete_event"><?= csrf_field() ?>
                                        <input type="hidden" name="event_id" value="<?= $evt['id'] ?>">
                                        <button type="submit" class="p-1.5 rounded-lg bg-red-500/10 text-red-400 hover:bg-red-500 hover:text-white transition-colors border border-red-500/20" title="Delete Event">
                                            <i data-lucide="trash-2" class="w-3.5 h-3.5"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- User Management Section -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <!-- Create Staff Form -->
                <div class="glass-panel p-6 rounded-3xl border border-cyan-500/20 shadow-glow-cyan h-fit">
                    <h3 class="text-lg font-heading-cyber font-bold text-slate-100 mb-4 flex items-center gap-2">
                        <i data-lucide="user-plus" class="w-5 h-5 text-cyan-400"></i> CREATE STAFF ACCOUNT
                    </h3>

                    <form method="POST" class="space-y-4 font-tech">
                        <input type="hidden" name="action" value="create_user"><?= csrf_field() ?>
                        <div>
                            <label class="block text-xs font-mono-cyber text-cyan-400 uppercase mb-1">Full Name</label>
                            <input type="text" name="name" required placeholder="e.g. Diya Chuphal" class="w-full px-3 py-2 rounded-xl bg-slate-900 border border-cyan-500/30 text-slate-100 text-xs focus:outline-none focus:border-cyan-400" />
                        </div>
                        <div>
                            <label class="block text-xs font-mono-cyber text-cyan-400 uppercase mb-1">Email Address</label>
                            <input type="email" name="email" required placeholder="staff@supernova2026.com" class="w-full px-3 py-2 rounded-xl bg-slate-900 border border-cyan-500/30 text-slate-100 text-xs focus:outline-none focus:border-cyan-400" />
                        </div>
                        <div>
                            <label class="block text-xs font-mono-cyber text-cyan-400 uppercase mb-1">Password</label>
                            <input type="password" name="password" required placeholder="••••••••••••" class="w-full px-3 py-2 rounded-xl bg-slate-900 border border-cyan-500/30 text-slate-100 text-xs focus:outline-none focus:border-cyan-400" />
                        </div>
                        <div>
                            <label class="block text-xs font-mono-cyber text-cyan-400 uppercase mb-1">Account Role</label>
                            <select name="role" class="w-full px-3 py-2 rounded-xl bg-slate-900 border border-cyan-500/30 text-slate-100 text-xs focus:outline-none focus:border-cyan-400">
                                <option value="ORGANIZER">Organizer</option>
                                <option value="FINANCE">Finance Officer</option>
                            </select>
                        </div>
                        <button type="submit" class="w-full py-3 rounded-xl bg-gradient-to-r from-cyan-500 to-purple-600 text-slate-950 font-mono-cyber font-bold text-xs shadow-glow-cyan hover:scale-105 transition-all">
                            CREATE STAFF MEMBER
                        </button>
                    </form>
                </div>

                <!-- Staff Users Table -->
                <div class="lg:col-span-2 glass-panel p-6 rounded-3xl border border-cyan-500/20 shadow-glow-cyan">
                    <h3 class="text-lg font-heading-cyber font-bold text-slate-100 mb-4">STAFF DIRECTORY (<?= count($users) ?>)</h3>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left text-xs text-slate-300">
                            <thead class="bg-slate-900/90 text-cyan-400 uppercase text-[10px] font-mono-cyber font-bold">
                                <tr>
                                    <th class="p-3 rounded-l-lg">NAME</th>
                                    <th class="p-3">EMAIL</th>
                                    <th class="p-3">ROLE</th>
                                    <th class="p-3">JOINED DATE</th>
                                    <th class="p-3 rounded-r-lg text-right">ACTIONS</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-white/5 font-tech">
                                <?php foreach ($users as $u): ?>
                                <tr class="hover:bg-cyan-500/5 transition-colors">
                                    <td class="p-3 font-semibold text-slate-200"><?= htmlspecialchars($u['name']) ?></td>
                                    <td class="p-3 text-slate-400 font-mono-cyber"><?= htmlspecialchars($u['email']) ?></td>
                                    <td class="p-3">
                                        <span class="px-2.5 py-0.5 rounded text-[10px] font-mono-cyber font-bold uppercase <?= 
                                            $u['role'] === 'ADMIN' ? 'bg-purple-500/10 text-purple-400 border border-purple-500/30' : 
                                            ($u['role'] === 'FINANCE' ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-cyan-500/10 text-cyan-400 border border-cyan-500/30') 
                                        ?>">
                                            <?= htmlspecialchars($u['role']) ?>
                                        </span>
                                    </td>
                                    <td class="p-3 text-slate-400"><?= date('Y-m-d', strtotime($u['createdAt'])) ?></td>
                                    <td class="p-3 text-right">
                                        <?php if ($u['role'] !== 'ADMIN'): ?>
                                        <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this staff user?');">
                                            <input type="hidden" name="action" value="delete_user"><?= csrf_field() ?>
                                            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                            <button type="submit" class="p-1.5 rounded bg-red-500/10 text-red-400 hover:bg-red-500 hover:text-white transition-colors" title="Delete User">
                                                <i data-lucide="trash-2" class="w-3.5 h-3.5"></i>
                                            </button>
                                        </form>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        lucide.createIcons();
    </script>
</body>
</html>
