<?php
// admin/orders.php
session_start();
include '../config.php';
include 'auth_check.php';
include '../util/audit_logger.php';

$message = '';
$error = '';

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $order_id = intval($_POST['order_id']);
    $action = $_POST['action'];
    $admin_id = $_SESSION['user_id'];
    // Make sure we have the SmtpMailer available
    require_once '../smtp_mailer.php';

    if ($action === 'approve') {
        // Start Transaction
        $conn->begin_transaction();
        try {
            // 1. Get Order Details
            $stmt = $conn->prepare("SELECT o.*, u.email, u.org_name FROM token_orders o JOIN users u ON o.user_id = u.id WHERE o.id = ? AND o.status = 'pending' FOR UPDATE");
            $stmt->bind_param("i", $order_id);
            $stmt->execute();
            $order = $stmt->get_result()->fetch_assoc();

            if (!$order) {
                throw new Exception("Order not found or already processed.");
            }

            // 2. Update Order Status
            $stmt = $conn->prepare("UPDATE token_orders SET status = 'approved', reviewed_by = ? WHERE id = ?");
            $stmt->bind_param("ii", $admin_id, $order_id);
            $stmt->execute();

            // 3. Add Tokens to User Transaction
            $user_id = $order['user_id'];
            $tokens = $order['tokens_requested'];
            $desc = "Order #" . $order['id'] . " Approved";

            $stmt = $conn->prepare("INSERT INTO token_transactions (user_id, amount, transaction_type, description, reference_id) VALUES (?, ?, 'credit', ?, ?)");
            $ref = 'ORD-' . $order['id'];
            $stmt->bind_param("iiss", $user_id, $tokens, $desc, $ref);
            $stmt->execute();

            // 4. Update User Subscription/Balance
            $check = $conn->query("SELECT id, package_id FROM user_subscriptions WHERE user_id = $user_id AND status = 'active'");
            $new_pkg_id = $order['package_id'];
            if ($check->num_rows > 0) {
                if (!empty($new_pkg_id)) {
                    // Package Upgrade/Purchase: Update package + Add tokens
                    $new_pkg_id = intval($new_pkg_id);
                    $conn->query("UPDATE user_subscriptions SET package_id = $new_pkg_id, tokens_remaining = tokens_remaining + $tokens WHERE user_id = $user_id AND status = 'active'");
                } else {
                    // Token Top-Up: Just add tokens
                    $conn->query("UPDATE user_subscriptions SET tokens_remaining = tokens_remaining + $tokens WHERE user_id = $user_id AND status = 'active'");
                }
            } else {
                // New Subscription
                $pkg_id = $new_pkg_id ?? 1;
                $stmt_new = $conn->prepare("INSERT INTO user_subscriptions (user_id, package_id, tokens_remaining, status) VALUES (?, ?, ?, 'active')");
                $stmt_new->bind_param("iii", $user_id, $pkg_id, $tokens);
                $stmt_new->execute();
            }

            // Audit log
            audit_log(
                $conn,
                'order_approved',
                'token_orders',
                $order_id,
                $user_id,
                $admin_id,
                json_encode(['status' => 'pending']),
                json_encode(['status' => 'approved', 'tokens_added' => $tokens]),
                "Order #$order_id approved. $tokens tokens credited."
            );

            $conn->commit();
            $message = "Order #$order_id approved successfully. $tokens tokens added to user balance.";

            // Send Email Notification
            try {
                $mailer = new SmtpMailer(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS);
                $subject = "Your SaniBook Token Order has been Approved!";
                $body = "<h2>Order Approved</h2>";
                $body .= "<p>Hello " . htmlspecialchars($order['org_name']) . ",</p>";
                $body .= "<p>Your order for <strong>" . number_format($tokens) . " tokens</strong> has been approved and added to your balance.</p>";
                $body .= "<p>You can now continue submitting your data.</p>";
                $mailer->send($order['email'], $subject, $body);
            } catch (Exception $email_ex) {
                error_log("Failed to send approval email: " . $email_ex->getMessage());
            }

        } catch (Exception $e) {
            $conn->rollback();
            $error = "Error: " . $e->getMessage();
        }
    } elseif ($action === 'reject') {
        $stmt = $conn->prepare("UPDATE token_orders SET status = 'rejected', reviewed_by = ? WHERE id = ?");
        $stmt->bind_param("ii", $admin_id, $order_id);
        if ($stmt->execute()) {
            // Get user details for audit and email
            $rstmt = $conn->prepare("SELECT o.user_id, o.tokens_requested, u.email, u.org_name FROM token_orders o JOIN users u ON o.user_id = u.id WHERE o.id = ?");
            $rstmt->bind_param("i", $order_id);
            $rstmt->execute();
            $rrow = $rstmt->get_result()->fetch_assoc();
            audit_log(
                $conn,
                'order_rejected',
                'token_orders',
                $order_id,
                $rrow['user_id'] ?? 0,
                $admin_id,
                json_encode(['status' => 'pending']),
                json_encode(['status' => 'rejected']),
                "Order #$order_id rejected."
            );
            $message = "Order #$order_id rejected.";

            // Send Email Notification
            if ($rrow && !empty($rrow['email'])) {
                try {
                    $mailer = new SmtpMailer(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS);
                    $subject = "Update on your SaniBook Token Order";
                    $body = "<h2>Order Rejected</h2>";
                    $body .= "<p>Hello " . htmlspecialchars($rrow['org_name']) . ",</p>";
                    $body .= "<p>Unfortunately, your recent order for " . number_format($rrow['tokens_requested']) . " tokens was rejected.</p>";
                    $body .= "<p>Please ensure your payment proof is clear or contact support for further assistance.</p>";
                    $mailer->send($rrow['email'], $subject, $body);
                } catch (Exception $email_ex) {
                    error_log("Failed to send rejection email: " . $email_ex->getMessage());
                }
            }

        } else {
            $error = "Error updating order.";
        }
    }
}

// Get filter
$filter = $_GET['filter'] ?? 'all';
$where_clause = "";
if ($filter !== 'all') {
    $where_clause = "WHERE o.status = '" . $conn->real_escape_string($filter) . "'";
}

// Get Statistics
$stats = [
    'total' => 0,
    'pending' => 0,
    'approved' => 0,
    'rejected' => 0,
    'total_revenue' => 0,
    'total_tokens' => 0
];

$stats_query = $conn->query("SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved,
    SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected,
    SUM(CASE WHEN status = 'approved' THEN amount_paid ELSE 0 END) as total_revenue,
    SUM(CASE WHEN status = 'approved' THEN tokens_requested ELSE 0 END) as total_tokens
FROM token_orders");

if ($row = $stats_query->fetch_assoc()) {
    $stats = $row;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Manage Orders - SaniBook Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <style>
        body {
            font-family: 'Inter', system-ui, sans-serif;
        }

        .proof-gallery-modal {
            display: none;
        }

        .proof-gallery-modal.active {
            display: flex;
        }
    </style>
</head>

<body class="bg-gradient-to-br from-slate-50 to-blue-50/30 min-h-screen">
    <?php include 'navbar.php'; ?>

    <div class="max-w-7xl mx-auto p-6">
        <!-- Header -->
        <div class="flex justify-between items-center mb-8">
            <div>
                <h2 class="text-2xl font-bold text-slate-900 flex items-center gap-3">
                    <i class="fa-solid fa-receipt text-blue-600"></i> Token Orders
                </h2>
                <p class="text-slate-600 mt-1">Review and approve token purchase orders</p>
            </div>
        </div>

        <?php if ($message): ?>
            <div
                class="bg-green-50 border-l-4 border-green-500 text-green-800 p-4 rounded-lg mb-6 flex items-center gap-3 shadow-sm">
                <i class="fa-solid fa-check-circle text-2xl"></i>
                <span class="font-medium"><?= htmlspecialchars($message) ?></span>
            </div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div
                class="bg-red-50 border-l-4 border-red-500 text-red-800 p-4 rounded-lg mb-6 flex items-center gap-3 shadow-sm">
                <i class="fa-solid fa-exclamation-triangle text-2xl"></i>
                <span class="font-medium"><?= htmlspecialchars($error) ?></span>
            </div>
        <?php endif; ?>

        <!-- Statistics Panel -->
        <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-8">
            <div class="bg-white rounded-xl shadow-md p-5 border-l-4 border-slate-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-slate-500 text-xs font-semibold uppercase tracking-wide">Total Orders</p>
                        <p class="text-2xl font-bold text-slate-900 mt-1"><?= $stats['total'] ?></p>
                    </div>
                    <i class="fa-solid fa-list text-3xl text-slate-500 opacity-20"></i>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md p-5 border-l-4 border-amber-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-slate-500 text-xs font-semibold uppercase tracking-wide">Pending</p>
                        <p class="text-2xl font-bold text-amber-700 mt-1"><?= $stats['pending'] ?></p>
                    </div>
                    <i class="fa-solid fa-clock text-3xl text-amber-500 opacity-20"></i>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md p-5 border-l-4 border-green-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-slate-500 text-xs font-semibold uppercase tracking-wide">Approved</p>
                        <p class="text-2xl font-bold text-green-700 mt-1"><?= $stats['approved'] ?></p>
                    </div>
                    <i class="fa-solid fa-check-circle text-3xl text-green-500 opacity-20"></i>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md p-5 border-l-4 border-red-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-slate-500 text-xs font-semibold uppercase tracking-wide">Rejected</p>
                        <p class="text-2xl font-bold text-red-700 mt-1"><?= $stats['rejected'] ?></p>
                    </div>
                    <i class="fa-solid fa-times-circle text-3xl text-red-500 opacity-20"></i>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md p-5 border-l-4 border-blue-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-slate-500 text-xs font-semibold uppercase tracking-wide">Total Revenue</p>
                        <p class="text-2xl font-bold text-blue-900 mt-1">KES
                            <?= number_format(floatval($stats['total_revenue'] ?? 0)) ?>
                        </p>
                    </div>
                    <i class="fa-solid fa-coins text-3xl text-blue-500 opacity-20"></i>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md p-5 border-l-4 border-cyan-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-slate-500 text-xs font-semibold uppercase tracking-wide">Tokens Issued</p>
                        <p class="text-2xl font-bold text-cyan-900 mt-1">
                            <?= number_format(floatval($stats['total_tokens'] ?? 0)) ?>
                        </p>
                    </div>
                    <i class="fa-solid fa-certificate text-3xl text-cyan-500 opacity-20"></i>
                </div>
            </div>
        </div>

        <!-- Filter Tabs -->
        <div class="bg-white rounded-xl shadow-md mb-6 p-1">
            <div class="flex gap-2">
                <a href="?filter=all"
                    class="flex-1 text-center py-3 px-4 rounded-lg font-semibold text-sm transition-all <?= $filter === 'all' ? 'bg-blue-600 text-white shadow-md' : 'text-slate-600 hover:bg-slate-50' ?>">
                    <i class="fa-solid fa-list mr-2"></i>All (<?= $stats['total'] ?>)
                </a>
                <a href="?filter=pending"
                    class="flex-1 text-center py-3 px-4 rounded-lg font-semibold text-sm transition-all <?= $filter === 'pending' ? 'bg-amber-500 text-white shadow-md' : 'text-slate-600 hover:bg-slate-50' ?>">
                    <i class="fa-solid fa-clock mr-2"></i>Pending (<?= $stats['pending'] ?>)
                </a>
                <a href="?filter=approved"
                    class="flex-1 text-center py-3 px-4 rounded-lg font-semibold text-sm transition-all <?= $filter === 'approved' ? 'bg-green-600 text-white shadow-md' : 'text-slate-600 hover:bg-slate-50' ?>">
                    <i class="fa-solid fa-check-circle mr-2"></i>Approved (<?= $stats['approved'] ?>)
                </a>
                <a href="?filter=rejected"
                    class="flex-1 text-center py-3 px-4 rounded-lg font-semibold text-sm transition-all <?= $filter === 'rejected' ? 'bg-red-600 text-white shadow-md' : 'text-slate-600 hover:bg-slate-50' ?>">
                    <i class="fa-solid fa-times-circle mr-2"></i>Rejected (<?= $stats['rejected'] ?>)
                </a>
            </div>
        </div>

        <!-- Orders Table -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden border border-slate-200">
            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse">
                    <thead
                        class="bg-gradient-to-r from-slate-700 to-slate-800 text-white uppercase text-xs font-bold tracking-wider">
                        <tr>
                            <th class="p-4">Order ID</th>
                            <th class="p-4">User</th>
                            <th class="p-4">Package</th>
                            <th class="p-4">Amount</th>
                            <th class="p-4">Tokens</th>
                            <th class="p-4">Proof</th>
                            <th class="p-4">Date</th>
                            <th class="p-4">Status</th>
                            <th class="p-4 text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <?php
                        $sql = "SELECT o.*, u.email, u.org_name, p.name as package_name 
                                FROM token_orders o 
                                JOIN users u ON o.user_id = u.id 
                                LEFT JOIN subscription_packages p ON o.package_id = p.id 
                                $where_clause
                                ORDER BY 
                                    CASE o.status 
                                        WHEN 'pending' THEN 1 
                                        WHEN 'approved' THEN 2 
                                        WHEN 'rejected' THEN 3 
                                    END,
                                    o.created_at DESC";
                        $result = $conn->query($sql);

                        if ($result && $result->num_rows > 0):
                            while ($row = $result->fetch_assoc()):
                                $statusClass = [
                                    'pending' => 'bg-amber-50',
                                    'approved' => 'bg-green-50/30',
                                    'rejected' => 'bg-red-50/30'
                                ][$row['status']] ?? '';
                                ?>
                                <tr class="hover:bg-slate-50 transition-colors <?= $statusClass ?>">
                                    <td class="p-4">
                                        <span class="font-bold text-slate-700">#<?= $row['id'] ?></span>
                                    </td>
                                    <td class="p-4">
                                        <div class="font-semibold text-slate-900"><?= htmlspecialchars($row['org_name']) ?>
                                        </div>
                                        <div class="text-xs text-slate-500"><?= htmlspecialchars($row['email']) ?></div>
                                    </td>
                                    <td class="p-4">
                                        <span class="inline-flex items-center gap-1 text-sm text-slate-700">
                                            <i class="fa-solid fa-box text-blue-500"></i>
                                            <?= htmlspecialchars($row['package_name'] ?? 'Token Top-Up') ?>
                                        </span>
                                    </td>
                                    <td class="p-4">
                                        <span class="font-bold text-slate-900"><?= $row['currency'] ?>
                                            <?= number_format($row['amount_paid']) ?></span>
                                    </td>
                                    <td class="p-4">
                                        <span
                                            class="inline-flex items-center gap-1 px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm font-bold">
                                            <i class="fa-solid fa-coins"></i>
                                            <?= number_format($row['tokens_requested']) ?>
                                        </span>
                                    </td>
                                    <td class="p-4">
                                        <?php if ($row['payment_proof']): ?>
                                            <button
                                                onclick="showProof('../uploads/proofs/<?= htmlspecialchars($row['payment_proof']) ?>')"
                                                class="text-blue-600 hover:text-blue-800 font-semibold text-xs flex items-center gap-1">
                                                <i class="fa-solid fa-image"></i> View
                                            </button>
                                        <?php else: ?>
                                            <span class="text-slate-400 text-xs">—</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-4">
                                        <div class="text-xs text-slate-600">
                                            <?= date('M d, Y', strtotime($row['created_at'])) ?>
                                        </div>
                                        <div class="text-[10px] text-slate-400">
                                            <?= date('h:i A', strtotime($row['created_at'])) ?>
                                        </div>
                                    </td>
                                    <td class="p-4">
                                        <?php
                                        $statusBadges = [
                                            'pending' => 'bg-amber-100 text-amber-700 border-amber-300',
                                            'approved' => 'bg-green-100 text-green-700 border-green-300',
                                            'rejected' => 'bg-red-100 text-red-700 border-red-300'
                                        ];
                                        $badge = $statusBadges[$row['status']] ?? 'bg-slate-100 text-slate-500';
                                        $icons = [
                                            'pending' => 'fa-clock',
                                            'approved' => 'fa-check-circle',
                                            'rejected' => 'fa-times-circle'
                                        ];
                                        $icon = $icons[$row['status']] ?? 'fa-circle';
                                        ?>
                                        <span
                                            class="inline-flex items-center gap-2 px-3 py-1 rounded-full text-[10px] font-bold uppercase border <?= $badge ?>">
                                            <i class="fa-solid <?= $icon ?>"></i>
                                            <?= $row['status'] ?>
                                        </span>
                                    </td>
                                    <td class="p-4">
                                        <?php if ($row['status'] === 'pending'): ?>
                                            <div class="flex justify-end gap-2">
                                                <form method="POST"
                                                    onsubmit="return confirm('Approve this order and add <?= number_format($row['tokens_requested']) ?> tokens to user balance?');">
                                                    <input type="hidden" name="order_id" value="<?= $row['id'] ?>">
                                                    <input type="hidden" name="action" value="approve">
                                                    <button type="submit"
                                                        class="px-4 py-2 bg-green-600 text-white rounded-lg text-xs font-bold hover:bg-green-700 shadow-md transition-all flex items-center gap-1">
                                                        <i class="fa-solid fa-check"></i> Approve
                                                    </button>
                                                </form>
                                                <form method="POST" onsubmit="return confirm('Reject this order?');">
                                                    <input type="hidden" name="order_id" value="<?= $row['id'] ?>">
                                                    <input type="hidden" name="action" value="reject">
                                                    <button type="submit"
                                                        class="px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-lg text-xs font-bold hover:bg-red-100 transition-all">
                                                        <i class="fa-solid fa-times"></i> Reject
                                                    </button>
                                                </form>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-xs text-slate-400 italic">Processed</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endwhile; else: ?>
                            <tr>
                                <td colspan="9" class="p-12 text-center">
                                    <i class="fa-solid fa-inbox text-6xl text-slate-300 mb-4"></i>
                                    <p class="text-slate-400 font-semibold">No orders
                                        found<?= $filter !== 'all' ? ' for this filter' : '' ?>.</p>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Proof Gallery Modal -->
    <div id="proofModal" class="proof-gallery-modal fixed inset-0 bg-black/90 items-center justify-center z-50">
        <div class="relative max-w-4xl max-h-[90vh] p-8">
            <button onclick="closeProof()" class="absolute top-4 right-4 text-white hover:text-slate-300 text-4xl z-10">
                <i class="fa-solid fa-xmark"></i>
            </button>
            <img id="proofImage" src="" alt="Payment Proof" class="max-w-full max-h-[85vh] rounded-lg shadow-2xl">
        </div>
    </div>

    <script>
        function showProof(path) {
            document.getElementById('proofImage').src = path;
            document.getElementById('proofModal').classList.add('active');
        }

        function closeProof() {
            document.getElementById('proofModal').classList.remove('active');
        }

        // Close on background click
        document.getElementById('proofModal').addEventListener('click', function (e) {
            if (e.target === this) closeProof();
        });

        // Close on ESC key
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape') closeProof();
        });
    </script>
</body>

</html>
