<?php
// Session must be started before checking $_SESSION
session_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/includes/EmailService.php';

// Auth Check
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: ../login.php");
    exit();
}

// CSRF Protection
if (empty($_SESSION['admin_csrf_token'])) {
    $_SESSION['admin_csrf_token'] = bin2hex(random_bytes(32));
}

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

// =========================================================
// TRANSACTION ACTION HANDLER (APPROVE / REJECT)
// =========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['transaction_id']) && isset($_POST['action'])) {
    // Verify CSRF token
    if (!hash_equals($_SESSION['admin_csrf_token'], $_POST['csrf_token'] ?? '')) {
        $error_msg = "Security Error: Invalid CSRF token.";
    } else {
        $transaction_id = intval($_POST['transaction_id']);
        $action = $_POST['action']; // 'approve' or 'reject'

        try {
            $pdo->beginTransaction();

            if ($action === 'approve') {
                $stmt = $pdo->prepare("
                    SELECT t.user_id, t.amount_paid, p.duration_days, p.plan_name
                    FROM transactions t 
                    JOIN subscription_plans p ON t.plan_id = p.id 
                    WHERE t.id = ? AND t.status = 'pending'
                ");
                $stmt->execute([$transaction_id]);
                $trans_data = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($trans_data) {
                    $user_id = $trans_data['user_id'];
                    $days = intval($trans_data['duration_days']);
                    $amount_paid = $trans_data['amount_paid'];
                    $plan_name = $trans_data['plan_name'];

                    // 1. Update transaction status
                    $pdo->prepare("UPDATE transactions SET status = 'approved' WHERE id = ?")->execute([$transaction_id]);

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

                    // 3. Update user_subscriptions
                    $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([$user_id, $trans_data['plan_id'], $expires_at, $trans_data['plan_id'], $expires_at]);

                    // 4. Upgrade user to VIP
                    $upgrade_sql = "
                        UPDATE users 
                        SET user_tier = 'VIP',
                            vip_expires_at = CASE 
                                WHEN vip_expires_at > NOW() THEN DATE_ADD(vip_expires_at, INTERVAL ? DAY)
                                ELSE DATE_ADD(NOW(), INTERVAL ? DAY)
                            END
                        WHERE id = ?
                    ";
                    $pdo->prepare($upgrade_sql)->execute([$days, $days, $user_id]);

                    // 5. Commit the transaction
                    $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([$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($amount_paid, 2),
                            'currency'       => 'USD',
                            'plan_name'      => $plan_name,
                            'transaction_id' => $transaction_id
                        ]);
                    }
                    // ============================================================

                    $success_msg = "Transaction approved. User upgraded to VIP.";
                } else {
                    $error_msg = "Invalid transaction or already processed.";
                }

            } elseif ($action === 'reject') {
                $pdo->prepare("UPDATE transactions SET status = 'rejected' WHERE id = ?")->execute([$transaction_id]);
                $pdo->commit();
                $success_msg = "Transaction has been rejected.";
            }

        } catch (PDOException $e) {
            $pdo->rollBack();
            $error_msg = "Error processing transaction: " . $e->getMessage();
        }
    }
}

// =========================================================
// FETCH TRANSACTIONS (JOIN WITH USERS AND PLANS)
// =========================================================
try {
    $query = "
        SELECT 
            t.*, 
            u.full_name AS username, 
            u.email, 
            p.plan_name, p.duration_days 
        FROM transactions t
        LEFT JOIN users u ON t.user_id = u.id
        LEFT JOIN subscription_plans p ON t.plan_id = p.id
        ORDER BY 
            CASE WHEN t.status = 'pending' THEN 1 ELSE 2 END, 
            t.created_at DESC
    ";
    $transactions = $pdo->query($query)->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $transactions = [];
    $error_msg = "Database Error: " . $e->getMessage();
}

// Count stats
$total = count($transactions);
$pending = 0;
$approved = 0;
$rejected = 0;
foreach ($transactions as $t) {
    if ($t['status'] === 'pending') $pending++;
    elseif ($t['status'] === 'approved') $approved++;
    elseif ($t['status'] === 'rejected') $rejected++;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Transaction Approvals</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;900&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; }
    </style>
    <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">
        
        <!-- ========== HEADER ========== -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div>
                <div class="inline-flex items-center space-x-2 bg-amber-500/10 border border-amber-500/20 px-3 py-1 rounded-full text-[10px] font-bold tracking-widest uppercase text-amber-400 mb-2">
                    <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"></span>
                    <span>Revenue Operations</span>
                </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">Verify payment receipts and automatically upgrade user tiers.</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 htmlspecialchars($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 htmlspecialchars($error_msg); ?>
            </div>
        <?php endif; ?>

        <!-- ========== STATS CARDS ========== -->
        <div class="grid grid-cols-1 sm:grid-cols-4 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">Total Transactions</span>
                <span class="text-2xl font-extrabold text-slate-900 dark:text-white mt-1 block"><?php echo $total; ?></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">Pending</span>
                <span class="text-2xl font-extrabold <?php echo $pending > 0 ? 'text-amber-500' : 'text-slate-400'; ?> mt-1 block"><?php echo $pending; ?></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; ?></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; ?></span>
            </div>
        </div>

        <!-- ========== TRANSACTIONS TABLE ========== -->
        <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-4 sm:p-6 shadow-sm transition-colors duration-300">
            <h3 class="font-bold text-lg mb-5 text-slate-900 dark:text-white border-b border-slate-200 dark:border-slate-800 pb-3">Transaction Ledger</h3>
            
            <div class="overflow-x-auto -mx-4 sm:-mx-6 px-4 sm:px-6">
                <table class="w-full text-left text-sm border-collapse min-w-[900px]">
                    <thead>
                        <tr class="text-slate-500 dark:text-gray-500 border-b border-slate-200 dark:border-slate-800 text-[10px] font-black tracking-wider uppercase">
                            <th class="py-3 px-2">Date</th>
                            <th class="py-3 px-2">Client</th>
                            <th class="py-3 px-2">Plan</th>
                            <th class="py-3 px-2">Method / Amount</th>
                            <th class="py-3 px-2 text-center">Receipt</th>
                            <th class="py-3 px-2 text-center">Status</th>
                            <th class="py-3 px-2 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 text-xs">
                        <?php foreach($transactions as $t): 
                            $date = date("d M Y H:i", strtotime($t['created_at']));
                            $is_pending = ($t['status'] === 'pending');
                        ?>
                        <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition <?php echo $is_pending ? 'bg-amber-50/30 dark:bg-amber-500/5' : ''; ?>">
                            
                            <td class="py-3 px-2 font-mono text-[10px] text-cyan-600 dark:text-cyan-400"><?php echo $date; ?></td>

                            <td class="py-3 px-2">
                                <div class="font-bold text-slate-900 dark:text-white"><?php echo htmlspecialchars($t['username'] ?? 'Unknown'); ?></div>
                                <div class="text-[10px] text-slate-500 dark:text-gray-400"><?php echo htmlspecialchars($t['email'] ?? 'N/A'); ?></div>
                            </td>

                            <td class="py-3 px-2">
                                <div class="font-bold text-emerald-600 dark:text-emerald-400"><?php echo htmlspecialchars($t['plan_name'] ?? 'N/A'); ?></div>
                                <div class="text-[9px] text-slate-500 dark:text-gray-400"><?php echo intval($t['duration_days'] ?? 0); ?> Days</div>
                            </td>

                            <td class="py-3 px-2">
                                <span class="inline-block bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300 px-2 py-0.5 rounded text-[9px] font-bold uppercase tracking-wider">
                                    <?php echo htmlspecialchars($t['payment_method'] ?? 'N/A'); ?>
                                </span>
                                <div class="font-black text-slate-900 dark:text-white">$<?php echo number_format($t['amount_paid'] ?? 0, 2); ?></div>
                            </td>

                            <td class="py-3 px-2 text-center">
                                <?php if(!empty($t['receipt_path'])): ?>
                                    <a href="<?php echo SITE_URL . '/' . htmlspecialchars($t['receipt_path']); ?>" target="_blank" class="inline-flex items-center gap-1 text-[10px] font-bold text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300 bg-blue-50 dark:bg-blue-500/10 px-2.5 py-1 rounded-lg border border-blue-200 dark:border-blue-500/30 transition">
                                        <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg>
                                        <span>View</span>
                                    </a>
                                <?php else: ?>
                                    <span class="text-[9px] text-slate-400 dark:text-gray-600">No Image</span>
                                <?php endif; ?>
                            </td>

                            <td class="py-3 px-2 text-center">
                                <?php if($t['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-bold uppercase tracking-wider">Pending</span>
                                <?php elseif($t['status'] === 'approved'): ?>
                                    <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-bold 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-bold uppercase tracking-wider">Rejected</span>
                                <?php endif; ?>
                            </td>

                            <td class="py-3 px-2 text-right">
                                <?php if($is_pending): ?>
                                    <form action="" method="POST" class="flex items-center justify-end gap-1.5">
                                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['admin_csrf_token']; ?>">
                                        <input type="hidden" name="transaction_id" value="<?php echo $t['id']; ?>">
                                        
                                        <button type="submit" name="action" value="reject" onclick="return confirm('Reject this payment?');" class="bg-rose-50 text-rose-600 border border-rose-200 hover:bg-rose-100 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/30 dark:hover:bg-rose-500/20 px-2.5 py-1.5 rounded-lg text-[9px] font-bold uppercase tracking-wider transition" title="Reject">❌</button>
                                        
                                        <button type="submit" name="action" value="approve" onclick="return confirm('Approve payment and upgrade user to VIP?');" class="bg-emerald-500 hover:bg-emerald-600 text-white font-bold px-2.5 py-1.5 rounded-lg text-[9px] uppercase tracking-wider transition shadow-sm shadow-emerald-500/20" title="Approve">✅</button>
                                    </form>
                                <?php else: ?>
                                    <span class="text-[9px] text-slate-400 dark:text-gray-600 italic">Processed</span>
                                <?php endif; ?>
                            </td>

                        </tr>
                        <?php endforeach; ?>
                        
                        <?php if(empty($transactions)): ?>
                        <tr>
                            <td colspan="7" class="py-12 text-center text-slate-400 dark:text-gray-500 text-xs font-medium uppercase tracking-widest">
                                No transactions found.
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- ========== FOOTER ========== -->
        <div class="text-center text-[10px] text-slate-400 dark:text-gray-600 border-t border-slate-200 dark:border-slate-800 pt-4 mt-2">
            Last sync: <?php echo date('H:i:s'); ?>
        </div>

    </main>
</body>
</html>