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

requireRole(['ADMIN', 'FINANCE']);

$pdo = getDatabaseConnection();

// Fetch Payments / Transactions
$query = "
    SELECT p.*, r.fullName, r.email, r.college, e.title as eventTitle
    FROM payments p
    LEFT JOIN registrations r ON p.registrationId = r.id
    LEFT JOIN events e ON r.eventId = e.id
    ORDER BY p.createdAt DESC
";
$stmt = $pdo->query($query);
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate Metrics
$totalRevenue = 0;
$successfulCount = 0;
$pendingCount = 0;
$failedCount = 0;

foreach ($transactions as $tx) {
    if ($tx['status'] === 'SUCCESSFUL') {
        $totalRevenue += $tx['amount'];
        $successfulCount++;
    } elseif ($tx['status'] === 'PENDING') {
        $pendingCount++;
    } else {
        $failedCount++;
    }
}

function formatCurrency($amt) { return '₹' . number_format($amt); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Finance 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-emerald-400 text-xs font-mono-cyber uppercase mb-1">
                        <i data-lucide="shield-check" class="w-4 h-4 text-emerald-400"></i> SUPERNOVA 2.0 • FINANCE PORTAL
                    </div>
                    <h1 class="text-3xl sm:text-4xl font-heading-cyber font-extrabold text-slate-100">
                        FINANCIAL OVERVIEW & REVENUE LEDGER
                    </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 Data">
                        <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>

            <!-- Metrics Grid -->
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-10">
                <div class="glass-panel p-6 rounded-2xl border border-cyan-500/30 shadow-glow-cyan">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-xs text-cyan-400 font-mono-cyber uppercase">Total Revenue</span>
                        <div class="p-2 rounded-lg bg-cyan-500/10 text-cyan-400 border border-cyan-500/30">
                            <i data-lucide="dollar-sign" class="w-5 h-5"></i>
                        </div>
                    </div>
                    <span class="text-3xl font-mono-cyber font-extrabold text-cyan-400"><?= formatCurrency($totalRevenue) ?></span>
                    <span class="text-xs text-slate-400 block mt-1 font-tech">Verified online festival registrations</span>
                </div>

                <div class="glass-panel p-6 rounded-2xl border border-emerald-500/30 shadow-glow-cyan">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-xs text-emerald-400 font-mono-cyber uppercase">Successful</span>
                        <div class="p-2 rounded-lg bg-emerald-500/10 text-emerald-400 border border-emerald-500/30">
                            <i data-lucide="check-circle-2" class="w-5 h-5"></i>
                        </div>
                    </div>
                    <span class="text-3xl font-mono-cyber font-extrabold text-emerald-400"><?= $successfulCount ?></span>
                    <span class="text-xs text-slate-400 block mt-1 font-tech">Completed checkout transactions</span>
                </div>

                <div class="glass-panel p-6 rounded-2xl border border-amber-500/30">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-xs text-amber-400 font-mono-cyber uppercase">Pending</span>
                        <div class="p-2 rounded-lg bg-amber-500/10 text-amber-400 border border-amber-500/30">
                            <i data-lucide="clock" class="w-5 h-5"></i>
                        </div>
                    </div>
                    <span class="text-3xl font-mono-cyber font-extrabold text-amber-400"><?= $pendingCount ?></span>
                    <span class="text-xs text-slate-400 block mt-1 font-tech">Awaiting Razorpay verification</span>
                </div>

                <div class="glass-panel p-6 rounded-2xl border border-red-500/30">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-xs text-red-400 font-mono-cyber uppercase">Failed / Cancelled</span>
                        <div class="p-2 rounded-lg bg-red-500/10 text-red-400 border border-red-500/30">
                            <i data-lucide="x-circle" class="w-5 h-5"></i>
                        </div>
                    </div>
                    <span class="text-3xl font-mono-cyber font-extrabold text-red-400"><?= $failedCount ?></span>
                    <span class="text-xs text-slate-400 block mt-1 font-tech">Unsuccessful transaction attempts</span>
                </div>
            </div>

            <!-- Transactions Table Section -->
            <div class="glass-panel p-6 rounded-3xl border border-cyan-500/20 shadow-glow-cyan">
                <div class="flex flex-col sm:flex-row items-center justify-between gap-4 mb-6">
                    <div class="flex items-center gap-2 font-mono-cyber" id="status-filters">
                        <button data-status="ALL" class="filter-btn px-3.5 py-1.5 rounded-xl text-xs font-bold transition-all bg-gradient-to-r from-cyan-500 to-blue-600 text-slate-950 font-extrabold shadow-glow-cyan">ALL</button>
                        <button data-status="SUCCESSFUL" class="filter-btn px-3.5 py-1.5 rounded-xl text-xs font-bold transition-all bg-slate-900 border border-cyan-500/20 text-slate-400 hover:text-white">SUCCESSFUL</button>
                        <button data-status="PENDING" class="filter-btn px-3.5 py-1.5 rounded-xl text-xs font-bold transition-all bg-slate-900 border border-cyan-500/20 text-slate-400 hover:text-white">PENDING</button>
                        <button data-status="FAILED" class="filter-btn px-3.5 py-1.5 rounded-xl text-xs font-bold transition-all bg-slate-900 border border-cyan-500/20 text-slate-400 hover:text-white">FAILED</button>
                    </div>

                    <div class="w-full sm:w-64 relative font-mono-cyber">
                        <i data-lucide="search" class="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-500"></i>
                        <input type="text" id="search-input" placeholder="Search transactions..." class="w-full pl-9 pr-4 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>

                <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 tracking-wider">
                            <tr>
                                <th class="p-4 rounded-l-xl">REGISTRATION ID</th>
                                <th class="p-4">PARTICIPANT & COMPETITION</th>
                                <th class="p-4">PAYMENT ID</th>
                                <th class="p-4">AMOUNT</th>
                                <th class="p-4">STATUS</th>
                                <th class="p-4 rounded-r-xl">DATE & TIME</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-white/5 font-tech" id="tx-tbody">
                            <!-- Populated by JS -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        lucide.createIcons();
        const transactions = <?= json_encode($transactions) ?>;
        const tbody = document.getElementById('tx-tbody');
        const searchInput = document.getElementById('search-input');
        const filterBtns = document.querySelectorAll('.filter-btn');
        let currentStatus = 'ALL';
        let currentSearch = '';

        function renderTable() {
            tbody.innerHTML = '';
            const filtered = transactions.filter(tx => {
                const matchStatus = currentStatus === 'ALL' || tx.status === currentStatus;
                const searchStr = (tx.registrationId + tx.fullName + tx.email + tx.eventTitle).toLowerCase();
                const matchSearch = searchStr.includes(currentSearch);
                return matchStatus && matchSearch;
            });

            if(filtered.length === 0) {
                tbody.innerHTML = '<tr><td colSpan="6" class="text-center py-8 text-slate-500 font-mono-cyber">No matching transaction records found.</td></tr>';
                return;
            }

            filtered.forEach(tx => {
                const tr = document.createElement('tr');
                tr.className = 'hover:bg-cyan-500/5 transition-colors';
                
                const statusStyle = tx.status === 'SUCCESSFUL' ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/30' : 
                                  (tx.status === 'PENDING' ? 'bg-amber-500/10 text-amber-400 border-amber-500/30' : 'bg-red-500/10 text-red-400 border-red-500/30');

                tr.innerHTML = `
                    <td class="p-4 font-mono-cyber font-bold text-cyan-400">${tx.registrationId || '-'}</td>
                    <td class="p-4">
                        <div class="font-semibold text-slate-200">${tx.fullName || 'Supernova Participant'}</div>
                        <div class="text-xs text-slate-400 font-mono-cyber">${tx.eventTitle || 'Event'} • ${tx.email || '-'}</div>
                    </td>
                    <td class="p-4 font-mono-cyber text-xs text-purple-400">${tx.razorpayPaymentId || tx.razorpayOrderId || '-'}</td>
                    <td class="p-4 font-mono-cyber font-bold text-slate-100">₹${tx.amount}</td>
                    <td class="p-4">
                        <span class="px-3 py-1 rounded-full text-[10px] font-mono-cyber font-bold uppercase border ${statusStyle}">${tx.status}</span>
                    </td>
                    <td class="p-4 text-xs font-mono-cyber text-slate-400">${new Date(tx.createdAt).toLocaleString()}</td>
                `;
                tbody.appendChild(tr);
            });
        }

        filterBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                currentStatus = btn.getAttribute('data-status');
                filterBtns.forEach(b => b.className = 'filter-btn px-3.5 py-1.5 rounded-xl text-xs font-bold transition-all bg-slate-900 border border-cyan-500/20 text-slate-400 hover:text-white');
                btn.className = 'filter-btn px-3.5 py-1.5 rounded-xl text-xs font-bold transition-all bg-gradient-to-r from-cyan-500 to-blue-600 text-slate-950 font-extrabold shadow-glow-cyan';
                renderTable();
            });
        });

        searchInput.addEventListener('input', (e) => {
            currentSearch = e.target.value.toLowerCase();
            renderTable();
        });

        renderTable();
    </script>
</body>
</html>
