<?php
// cart.php
session_start();
require_once 'config.php';

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

$user_id = $_SESSION['user_id'];
$error = '';
$success = '';

// --- Handle Items ---
// Initialize cart buffer if not exists
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = ['package' => null, 'topup' => null];
}

$cart = $_SESSION['cart'];
$cart_items = [];
$total_price = 0;

if ($cart['package']) {
    $cart_items[] = [
        'type' => 'package',
        'id' => $cart['package']['id'],
        'name' => $cart['package']['name'],
        'tokens' => $cart['package']['adjusted_tokens'],
        'price' => $cart['package']['adjusted_price'],
        'original_price' => $cart['package']['original_price'],
        'upgrade_from' => $cart['package']['upgrade_from'] ?? null
    ];
    $total_price += $cart['package']['adjusted_price'];
}

if ($cart['topup']) {
    $cart_items[] = [
        'type' => 'topup',
        'id' => null,
        'name' => 'Token Top-Up',
        'tokens' => $cart['topup']['tokens'],
        'price' => $cart['topup']['price']
    ];
    $total_price += $cart['topup']['price'];
}

// --- Order Submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && count($cart_items) > 0) {
    // 1. Process Order Directly (Payment gateway pending)
    $proof_filename = null;

    // 2. Process Order
    if (!$error) {
        $conn->begin_transaction();
        try {
            foreach ($cart_items as $item) {
                // Insert each item as a separate order
                // package_id is NULL for topups
                $pkg_id = $item['id'] ? intval($item['id']) : null;
                $amount = floatval($item['price']);
                $tokens = intval($item['tokens']);
                $method = 'online'; // Placeholder till gateway integration

                $stmt = $conn->prepare("INSERT INTO token_orders (user_id, package_id, amount_paid, tokens_requested, payment_method, payment_proof, status, created_at) VALUES (?, ?, ?, ?, ?, ?, 'pending', NOW())");
                // Note: database schema for created_at might be missing? Assuming standard fields or default value.
                // Re-checking schema: usually created_at has DEFAULT CURRENT_TIMESTAMP. 
                // Let's remove created_at from INSERT just to be safe if schema handles it, or check schema.
                // Actually safer to trust schema defaults.
                $stmt = $conn->prepare("INSERT INTO token_orders (user_id, package_id, amount_paid, tokens_requested, payment_method, payment_proof, status) VALUES (?, ?, ?, ?, ?, ?, 'pending')");

                $stmt->bind_param("iidiss", $user_id, $pkg_id, $amount, $tokens, $method, $proof_filename);
                if (!$stmt->execute()) {
                    throw new Exception("Database error: " . $stmt->error);
                }
                $stmt->close();
            }

            $conn->commit();

            // Send notification to admin using SmtpMailer
            try {
                require_once 'smtp_mailer.php';
                $mailer = new SmtpMailer(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS);
                $admin_email = "ewambui@washvoiceafrica.org";
                $subject = "New SaniBook Token Order - KES " . number_format($total_price);
                $msg = "<h2>New Token Order</h2>";
                $msg .= "<p>A new token order was just placed.</p>";
                $msg .= "<ul><li><strong>User ID:</strong> {$user_id}</li>";
                $msg .= "<li><strong>Total amount:</strong> KES " . number_format($total_price) . "</li></ul>";
                $msg .= "<p>Please login to the admin dashboard to process this new order.</p>";
                $mailer->send($admin_email, $subject, $msg);
            } catch (Exception $email_ex) {
                // Log email error, but do not fail the order completion
                error_log("Failed to send order email notification: " . $email_ex->getMessage());
            }

            $success = "Order submitted successfully! We will review your payment shortly.";

            // Clear cart
            $_SESSION['cart'] = ['package' => null, 'topup' => null];
            $cart_items = [];
            $total_price = 0;

        } catch (Exception $e) {
            $conn->rollback();
            $error = "Transaction failed: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Checkout | SaniBook Kenya</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" />
</head>

<body class="bg-slate-50 font-sans text-slate-900">
    <?php include 'navbar.php'; ?>

    <main class="max-w-4xl mx-auto px-4 py-16">

        <?php if ($success): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-8 rounded-lg text-center">
                <i class="fa-solid fa-check-circle text-4xl mb-4"></i>
                <h2 class="text-2xl font-bold mb-2">Order Received!</h2>
                <p><?= htmlspecialchars($success) ?></p>
                <div class="mt-6">
                    <a href="user_dashboard.php"
                        class="px-6 py-2 bg-green-600 text-white rounded-lg font-bold hover:bg-green-700">Go to
                        Dashboard</a>
                </div>
            </div>
        <?php elseif (!empty($cart_items)): ?>
            <h1 class="text-3xl font-bold mb-8">Secure Checkout</h1>
            <div class="grid md:grid-cols-3 gap-8">
                <!-- Order Summary -->
                <div class="md:col-span-1">
                    <div class="bg-white p-6 rounded-xl shadow-sm border border-slate-200 sticky top-24">
                        <h3 class="text-sm font-bold text-slate-500 uppercase tracking-widest mb-4">Summary</h3>

                        <div class="space-y-4 mb-4 pb-4 border-b border-slate-100">
                            <?php foreach ($cart_items as $item): ?>
                                <div>
                                    <div class="flex justify-between items-start">
                                        <div>
                                            <h4 class="font-bold text-blue-900">
                                                <?= htmlspecialchars($item['name']) ?>
                                            </h4>
                                            <?php if (!empty($item['upgrade_from'])): ?>
                                                <span
                                                    class="text-xs bg-yellow-100 text-yellow-800 px-1.5 py-0.5 rounded">Upgrade</span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="text-right font-semibold text-slate-700">
                                            KES <?= number_format($item['price']) ?>
                                        </div>
                                    </div>
                                    <div class="text-sm text-slate-500 mt-1">
                                        <?= number_format($item['tokens']) ?> Tokens
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <div class="flex justify-between items-center text-lg font-bold border-t border-slate-100 pt-4">
                            <span>Total</span>
                            <span class="text-green-700">KES <?= number_format($total_price) ?></span>
                        </div>


                    </div>
                </div>

                <!-- Payment Form -->
                <div class="md:col-span-2">
                    <div class="bg-white p-8 rounded-xl shadow-sm border border-slate-200">
                        <h2 class="text-xl font-bold mb-6">Payment Details</h2>

                        <?php if ($error): ?>
                            <div class="bg-red-50 text-red-700 p-4 rounded mb-6 border border-red-200">
                                <i class="fa-solid fa-circle-exclamation mr-2"></i> <?= $error ?>
                            </div>
                        <?php endif; ?>

                        <div class="bg-blue-50 p-4 rounded-lg mb-6 text-sm text-blue-800 border border-blue-100">
                            <p class="mb-3"><strong>Provisional Checkout:</strong> Our payment gateway is currently
                                being finalized. For now, you can submit your order and it will be reviewed.</p>
                        </div>

                        <form method="POST" class="space-y-6">
                            <button type="submit"
                                class="w-full bg-blue-600 text-white font-bold py-3 rounded-lg hover:bg-blue-700 transition-colors shadow-lg hover:shadow-xl transform hover:-translate-y-0.5 duration-200">
                                <i class="fa-solid fa-lock mr-2"></i> Submit Order
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <div class="text-center py-20 bg-white rounded-xl border border-slate-200 shadow-sm">
                <div
                    class="w-20 h-20 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-6 text-slate-400">
                    <i class="fa-solid fa-cart-shopping text-3xl"></i>
                </div>
                <h2 class="text-2xl font-bold text-slate-800 mb-2">Your cart is empty</h2>
                <p class="text-slate-500 mb-6">Looks like you haven't added any packages yet.</p>
                <a href="pricing.php"
                    class="px-6 py-3 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 transition-colors inline-block">
                    View Packages
                </a>
            </div>
        <?php endif; ?>

    </main>

    <?php include 'footer.php'; ?>
</body>

</html>