<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/includes/EmailService.php';

// Ensure admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit();
}

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$success_msg = '';
$error_msg = '';

// Handle Approval / Rejection actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        die("Security Error: Invalid CSRF Token.");
    }

    $transaction_id = filter_input(INPUT_POST, 'transaction_id', FILTER_VALIDATE_INT);
    $action = trim($_POST['action'] ?? '');

    if ($transaction_id && in_array($action, ['approve', 'reject'])) {
        try {
            $pdo->beginTransaction();

            $stmt = $pdo->prepare("SELECT * FROM transactions WHERE id = ? FOR UPDATE");
            $stmt->execute([$transaction_id]);
            $tx = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($tx && $tx['status'] === 'pending') {
                if ($action === 'approve') {
                    // 1. Update transaction status
                    $pdo->prepare("UPDATE transactions SET status = 'success' WHERE id = ?")->execute([$transaction_id]);

                    // 2. Get plan duration
                    $p_stmt = $pdo->prepare("SELECT duration_days, plan_name FROM subscription_plans WHERE id = ?");
                    $p_stmt->execute([$tx['plan_id']]);
                    $plan = $p_stmt->fetch(PDO::FETCH_ASSOC);
                    $duration = $plan['duration_days'] ?? 30;
                    $plan_name = $plan['plan_name'] ?? 'Subscription';

                    // 3. Calculate expiry and update user_subscriptions
                    $expires_at = date('Y-m-d H:i:s', strtotime("+$duration days"));

                    $sub_stmt = $pdo->prepare("INSERT INTO user_subscriptions (user_id, plan_id, expires_at, is_active) 
                                               VALUES (?, ?, ?, 1) 
                                               ON DUPLICATE KEY UPDATE plan_id = ?, expires_at = ?, is_active = 1");
                    $sub_stmt->execute([$tx['user_id'], $tx['plan_id'], $expires_at, $tx['plan_id'], $expires_at]);

                    // 4. Upgrade user in users table
                    $user_stmt = $pdo->prepare("UPDATE users SET user_tier = 'VIP', vip_expires_at = ? WHERE id = ?");
                    $user_stmt->execute([$expires_at, $tx['user_id']]);

                    // 5. Commit the transaction first
                    $pdo->commit();

                    // ============================================================
                    // 🔥 SEND EMAILS AFTER SUCCESSFUL ADMIN APPROVAL
                    // ============================================================
                    // Fetch user details
                    $user_stmt = $pdo->prepare("SELECT full_name, email FROM users WHERE id = ?");
                    $user_stmt->execute([$tx['user_id']]);
                    $user = $user_stmt->fetch(PDO::FETCH_ASSOC);

                    if ($user) {
                        $emailService = new EmailService($pdo);
                        
                        // Send VIP upgrade email
                        $emailService->sendTemplateEmail('vip_upgrade', $user['email'], [
                            'user_name'   => $user['full_name'],
                            'expiry_date' => date('F j, Y', strtotime($expires_at))
                        ]);
                        
                        // Send payment confirmation
                        $emailService->sendTemplateEmail('payment_confirmation', $user['email'], [
                            'user_name'      => $user['full_name'],
                            'amount'         => '$' . number_format($tx['amount_paid'], 2),
                            'currency'       => 'USD',
                            'plan_name'      => $plan_name,
                            'transaction_id' => $tx['id']
                        ]);
                    }
                    // ============================================================

                    $success_msg = "Transaction approved successfully. User subscription upgraded.";

                } else {
                    // Reject
                    $pdo->prepare("UPDATE transactions SET status = 'rejected' WHERE id = ?")->execute([$transaction_id]);
                    $pdo->commit();
                    $success_msg = "Transaction rejected.";
                }
            } else {
                $error_msg = "Transaction not found or already processed.";
                $pdo->rollBack();
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_msg = "Database Exception: " . $e->getMessage();
        }
    } else {
        $error_msg = "Invalid action or transaction ID.";
    }
}

// Fetch transaction ledger with counts for stats
$transactions = [];
$pending_count = 0;
$approved_count = 0;
$rejected_count = 0;
try {
    $stmt = $pdo->query("
        SELECT t.*, u.email as user_email, p.plan_name 
        FROM transactions t
        LEFT JOIN users u ON t.user_id = u.id
        LEFT JOIN subscription_plans p ON t.plan_id = p.id
        WHERE t.payment_method LIKE '%Cryptocurrency%'
        ORDER BY CASE WHEN t.status = 'pending' THEN 1 ELSE 2 END, t.created_at DESC
    ");
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Count statuses
    foreach ($transactions as $tx) {
        if ($tx['status'] === 'pending') $pending_count++;
        elseif ($tx['status'] === 'success') $approved_count++;
        elseif ($tx['status'] === 'rejected') $rejected_count++;
    }
} catch (PDOException $e) {
    $error_msg = "Database Error: Ensure transactions, users, and subscription_plans tables are configured properly.";
}
?>
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manual Approvals - <?php echo $site_name ?? 'Football Pred Pro'; ?></title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/output.css?v=<?php echo time(); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
        .dark ::-webkit-scrollbar-thumb { background: #334155; }
        [x-cloak] { display: none !important; }
    </style>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <script>
        if (localStorage.getItem('fpp_theme') === 'dark') {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    </script>
</head>
<body class="bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-gray-200 antialiased min-h-screen flex flex-col md:flex-row transition-colors duration-300">

    <?php include __DIR__ . '/includes/admin-sidebar.php'; ?>

    <main class="flex-1 p-4 sm:p-6 md:p-8 overflow-x-hidden flex flex-col gap-6" x-data="approvalEngine()">
        
        <!-- ========== HEADER ========== -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div>
                <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 dark:text-white tracking-wide">Manual Approvals</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-0.5">Audit crypto transactions and authorize VIP upgrades.</p>
            </div>
        </div>

        <!-- ========== MESSAGES ========== -->
        <?php if(!empty($success_msg)): ?>
            <div class="bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-500/10 dark:border-emerald-500/30 dark:text-emerald-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>✅</span> <?php echo $success_msg; ?>
            </div>
        <?php endif; ?>
        <?php if(!empty($error_msg)): ?>
            <div class="bg-rose-50 border-rose-200 text-rose-700 dark:bg-rose-500/10 dark:border-rose-500/30 dark:text-rose-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>❌</span> <?php echo $error_msg; ?>
            </div>
        <?php endif; ?>

        <!-- ========== STATS CARDS ========== -->
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Pending Approvals</span>
                <span class="text-2xl font-extrabold <?php echo $pending_count > 0 ? 'text-amber-500' : 'text-slate-900 dark:text-white'; ?> mt-1 block"><?php echo $pending_count; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Approved</span>
                <span class="text-2xl font-extrabold text-emerald-600 dark:text-emerald-500 mt-1 block"><?php echo $approved_count; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Rejected</span>
                <span class="text-2xl font-extrabold text-rose-600 dark:text-rose-500 mt-1 block"><?php echo $rejected_count; ?></span>
            </div>
        </div>

        <!-- ========== TRANSACTIONS TABLE ========== -->
        <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl overflow-hidden shadow-sm transition-colors duration-300">
            <div class="overflow-x-auto -mx-4 sm:-mx-6 px-4 sm:px-6">
                <table class="w-full text-left text-xs border-collapse min-w-[900px]">
                    <thead class="bg-slate-50 dark:bg-slate-800/30 text-[9px] font-black uppercase tracking-widest text-slate-500 dark:text-gray-400 border-b border-slate-200 dark:border-slate-800">
                        <tr>
                            <th class="px-4 py-3">Date</th>
                            <th class="px-4 py-3">Client</th>
                            <th class="px-4 py-3">Plan</th>
                            <th class="px-4 py-3">Method / Amount</th>
                            <th class="px-4 py-3 text-center">Receipt</th>
                            <th class="px-4 py-3 text-center">Status</th>
                            <th class="px-4 py-3 text-right">Action</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 dark:divide-slate-800/60 text-slate-700 dark:text-gray-300">
                        <?php if(empty($transactions)): ?>
                            <tr>
                                <td colspan="7" class="px-4 py-12 text-center text-slate-400 dark:text-gray-500 font-bold tracking-widest uppercase text-xs">No transactions found.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach($transactions as $tx): ?>
                                <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition-colors">
                                    <td class="px-4 py-3 text-cyan-600 dark:text-cyan-400 font-mono"><?= date('d M H:i', strtotime($tx['created_at'])); ?></td>
                                    <td class="px-4 py-3">
                                        <div class="font-bold text-slate-900 dark:text-white"><?= htmlspecialchars($tx['user_email'] ?? 'Unknown'); ?></div>
                                        <div class="text-[9px] font-mono text-slate-500 dark:text-gray-500">ID: <?= $tx['user_id']; ?></div>
                                    </td>
                                    <td class="px-4 py-3 font-bold text-emerald-600 dark:text-emerald-400"><?= htmlspecialchars($tx['plan_name'] ?? 'N/A'); ?></td>
                                    <td class="px-4 py-3">
                                        <div><?= htmlspecialchars($tx['payment_method']); ?></div>
                                        <div class="font-black text-slate-900 dark:text-white">$<?= number_format($tx['amount_paid'], 2); ?></div>
                                    </td>
                                    <td class="px-4 py-3 text-center">
                                        <?php if(!empty($tx['receipt_path'])): ?>
                                            <button @click="openReceipt('../<?= htmlspecialchars($tx['receipt_path']); ?>')" class="bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 text-slate-700 dark:text-gray-300 text-[9px] font-bold px-3 py-1.5 rounded-lg border border-slate-200 dark:border-slate-700 transition">👁️ View</button>
                                        <?php else: ?>
                                            <span class="text-[9px] text-slate-400 dark:text-gray-600 font-bold">NONE</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-4 py-3 text-center">
                                        <?php if ($tx['status'] == 'pending'): ?>
                                            <span class="bg-amber-50 text-amber-600 border border-amber-200 dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/30 px-2.5 py-0.5 rounded-full text-[9px] font-black uppercase tracking-wider">Pending</span>
                                        <?php elseif ($tx['status'] == 'success'): ?>
                                            <span class="bg-emerald-50 text-emerald-600 border border-emerald-200 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/30 px-2.5 py-0.5 rounded-full text-[9px] font-black uppercase tracking-wider">Approved</span>
                                        <?php else: ?>
                                            <span class="bg-rose-50 text-rose-600 border border-rose-200 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/30 px-2.5 py-0.5 rounded-full text-[9px] font-black uppercase tracking-wider">Rejected</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-4 py-3 text-right">
                                        <?php if($tx['status'] === 'pending'): ?>
                                            <div class="flex items-center justify-end space-x-2">
                                                <form method="POST" class="inline">
                                                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token']; ?>">
                                                    <input type="hidden" name="transaction_id" value="<?= $tx['id']; ?>">
                                                    <input type="hidden" name="action" value="approve">
                                                    <button type="submit" onclick="return confirm('Approve this crypto transfer and unlock user dashboard?')" class="bg-emerald-50 hover:bg-emerald-100 dark:bg-emerald-500/10 dark:hover:bg-emerald-500/20 border border-emerald-200 dark:border-emerald-500/30 text-emerald-600 dark:text-emerald-400 p-2 rounded-lg transition text-sm font-bold" title="Approve">✔️</button>
                                                </form>
                                                <form method="POST" class="inline">
                                                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token']; ?>">
                                                    <input type="hidden" name="transaction_id" value="<?= $tx['id']; ?>">
                                                    <input type="hidden" name="action" value="reject">
                                                    <button type="submit" onclick="return confirm('Reject this transaction proof?')" class="bg-rose-50 hover:bg-rose-100 dark:bg-rose-500/10 dark:hover:bg-rose-500/20 border border-rose-200 dark:border-rose-500/30 text-rose-600 dark:text-rose-400 p-2 rounded-lg transition text-sm font-bold" title="Reject">❌</button>
                                                </form>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-[9px] text-slate-400 dark:text-gray-600 font-black uppercase tracking-widest">Closed</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- ========== RECEIPT MODAL ========== -->
        <div x-show="modalOpen" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4">
            <div class="absolute inset-0 bg-slate-950/90 backdrop-blur-sm" @click="closeReceipt()"></div>
            <div class="relative bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 shadow-2xl rounded-2xl max-w-3xl w-full flex flex-col max-h-full">
                <div class="p-4 border-b border-slate-200 dark:border-slate-800 flex justify-between items-center">
                    <h3 class="text-xs font-black text-slate-900 dark:text-white tracking-widest uppercase">Transaction Receipt</h3>
                    <button @click="closeReceipt()" class="text-slate-400 dark:text-gray-500 hover:text-slate-700 dark:hover:text-white text-lg">&times;</button>
                </div>
                <div class="p-4 overflow-auto flex-1 flex justify-center items-center bg-slate-50 dark:bg-slate-950/40 rounded-b-2xl">
                    <img x-show="!isPdf" :src="receiptSrc" class="max-w-full max-h-[70vh] rounded-xl object-contain shadow-md" alt="Receipt">
                    <div x-show="isPdf" class="text-center py-12">
                        <p class="text-slate-600 dark:text-gray-300 text-xs font-bold mb-4">Receipt is a PDF document.</p>
                        <a :href="receiptSrc" target="_blank" class="bg-emerald-600 hover:bg-emerald-700 text-white px-5 py-2.5 rounded-xl text-[10px] font-black uppercase tracking-widest transition">Open PDF</a>
                    </div>
                </div>
            </div>
        </div>

    </main>

    <script>
        function approvalEngine() {
            return {
                modalOpen: false,
                receiptSrc: '',
                isPdf: false,
                openReceipt(url) {
                    this.receiptSrc = url;
                    this.isPdf = url.toLowerCase().endsWith('.pdf');
                    this.modalOpen = true;
                },
                closeReceipt() {
                    this.modalOpen = false;
                }
            }
        }
    </script>
</body>
</html>