<?php
require_once '../includes/middleware.php';
require_once '../config/database.php';
require_once '../config/currency.php';
require_once '../includes/functions.php';

// Cart Manager Class
class CartManager {
    private $db;
    private $userId;

    public function __construct($db, $userId = null) {
        $this->db = $db;
        $this->userId = $userId;
    }

    public function getCart() {
        if (!$this->userId) {
            return ['items' => [], 'total' => 0.00, 'currency' => 'USD'];
        }

        $stmt = $this->db->prepare("
            SELECT ci.*,
                   COALESCE(c.title, e.title) as title,
                   COALESCE(c.price, e.price) as price,
                   COALESCE(c.currency, e.currency) as currency,
                   COALESCE(c.is_free, e.is_free) as is_free,
                   COALESCE(c.thumbnail, NULL) as thumbnail,
                   COALESCE(c.max_students, NULL) as max_students,
                   ci.item_type
            FROM cart_items ci
            LEFT JOIN courses c ON ci.item_id = c.id AND ci.item_type = 'course'
            LEFT JOIN exams e ON ci.item_id = e.id AND ci.item_type = 'exam'
            WHERE ci.user_id = ?
            ORDER BY ci.created_at ASC
        ");
        $stmt->execute([$this->userId]);
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $total = 0.00;
        $currency = 'USD';

        foreach ($items as &$item) {
            if (!$item['is_free']) {
                $total += floatval($item['price']);
                $currency = $item['currency'];
            }
        }

        return [
            'items' => $items,
            'total' => $total,
            'currency' => $currency,
            'item_count' => count($items)
        ];
    }
}

$db = getDB();

if (!isLoggedIn()) {
    header('Location: login.php?redirect=checkout.php');
    exit;
}

$userId = $_SESSION['user_id'];
$user = getUserContext();

$cartManager = new CartManager($db, $userId);
$cart = $cartManager->getCart();

$cartItems = $cart['items'];
$subtotal = 0;
foreach ($cartItems as $item) {
    if (!$item['is_free']) {
        $subtotal += floatval($item['price']);
    }
}
$tax = $subtotal * 0.1;
$total = $subtotal + $tax;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($user['username'] ?? 'Student'); ?>'s Checkout | Mutalex Academy</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">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A',
                        'background-light': '#F8FAFC',
                        'text-dark': '#1F2937',
                        'accent-subtle': '#E5E7EB',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        @keyframes fade-in { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
        .animate-fade-in { animation: fade-in 0.4s ease-out forwards; }
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-thumb { background: #CBD5E1; border-radius: 10px; }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen flex flex-col">

    <!-- Header (Synced with student panel) -->
    <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-50 border-b border-accent-subtle">
        <div class="px-4 sm:px-6 lg:px-8 py-3 flex justify-between items-center">
            <div class="flex items-center space-x-3">
                <img src="../assets/images/logo_1757657555.jpg" alt="Logo" class="h-9 w-9">
                <div>
                    <h1 class="text-lg font-bold text-primary-blue leading-none">Mutalex Academy</h1>
                    <p class="text-[11px] text-gray-500 uppercase tracking-wider font-semibold mt-1">Student Portal</p>
                </div>
            </div>

            <div class="flex items-center space-x-4">
                <div class="hidden sm:flex flex-col items-end mr-2">
                    <span class="text-sm font-bold text-slate-800"><?php echo htmlspecialchars($user['username'] ?? 'Student'); ?></span>
                    <span class="text-[10px] text-green-600 font-bold uppercase">Online Status</span>
                </div>
                <img class="h-10 w-10 rounded-xl border-2 border-indigo-50 object-cover shadow-sm" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($user['username'] ?? 'S'), 0, 1); ?>" alt="Avatar">
                <button class="lg:hidden p-2 rounded-lg bg-slate-100 text-slate-600" id="mobileMenuButton">
                    <i class="fas fa-bars"></i>
                </button>
            </div>
        </div>
    </header>

    <div class="flex flex-1 pt-16">
        <!-- Sidebar (Synced with student panel) -->
        <aside class="hidden lg:block w-64 bg-white border-r border-accent-subtle p-6 sticky top-16 h-[calc(100vh-64px)] overflow-y-auto">
            <nav class="space-y-1">
                <a href="dashboard.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-home w-5"></i>
                    <span class="font-medium">Dashboard</span>
                </a>
                <a href="available_courses.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-book-open w-5"></i>
                    <span class="font-medium">Catalog</span>
                </a>
                <a href="courses.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-graduation-cap w-5"></i>
                    <span class="font-medium">My Courses</span>
                </a>
                <div class="pt-4 pb-2">
                    <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest px-3">Account</p>
                </div>
                <a href="reports.php" class="flex items-center space-x-3 p-3 rounded-xl text-slate-600 hover:bg-indigo-50 hover:text-indigo-600 transition duration-150">
                    <i class="fas fa-chart-pie w-5"></i>
                    <span class="font-medium">Grades</span>
                </a>
                <a href="../logout.php" class="flex items-center space-x-3 p-3 rounded-xl text-red-500 hover:bg-red-50 transition duration-150">
                    <i class="fas fa-sign-out-alt w-5"></i>
                    <span class="font-medium">Logout</span>
                </a>
            </nav>
            <div class="mt-10 p-4 bg-slate-50 rounded-2xl border border-slate-100">
                <p class="text-[10px] text-slate-400 font-bold uppercase">Support ID</p>
                <p class="text-xs font-mono text-slate-600 mt-1"><?php echo strtoupper(substr(md5($userId), 0, 8)); ?></p>
            </div>
        </aside>

        <!-- Mobile Menu -->
        <div id="mobileMenu" class="fixed inset-0 bg-slate-900/50 z-[60] hidden backdrop-blur-sm lg:hidden">
            <div class="w-72 bg-white h-full p-6 shadow-2xl animate-fade-in">
                <div class="flex justify-between items-center mb-8">
                    <h2 class="font-bold text-primary-blue">Menu</h2>
                    <button id="closeMobileMenu" class="text-2xl text-slate-400">&times;</button>
                </div>
                <nav class="space-y-2">
                    <a href="dashboard.php" class="block p-3 rounded-xl bg-slate-50 text-slate-700">🏠 Dashboard</a>
                    <a href="available_courses.php" class="block p-3 rounded-xl text-slate-700">📖 Catalog</a>
                    <a href="../logout.php" class="block p-3 rounded-xl text-red-500">🚪 Logout</a>
                </nav>
            </div>
        </div>

        <!-- Main Content -->
        <main class="flex-1 p-4 lg:p-8">
            <div class="max-w-5xl mx-auto">
                
                <!-- Progress Stepper -->
                <div class="flex items-center justify-center mb-10 max-w-xl mx-auto px-4">
                    <?php
                    $currentStep = isset($_GET['step']) ? intval($_GET['step']) : 1;
                    $steps = [['id' => 1, 'l' => 'Details'], ['id' => 2, 'l' => 'Payment'], ['id' => 3, 'l' => 'Review']];
                    foreach ($steps as $i => $s):
                        $active = $currentStep >= $s['id'];
                    ?>
                        <div class="flex flex-col items-center relative">
                            <div class="w-10 h-10 rounded-full flex items-center justify-center border-2 z-10 transition-all <?php echo $active ? 'bg-indigo-600 border-indigo-600 text-white' : 'bg-white border-slate-200 text-slate-400'; ?>">
                                <?php if ($currentStep > $s['id']) echo '<i class="fas fa-check text-sm"></i>'; else echo $s['id']; ?>
                            </div>
                            <span class="text-[10px] mt-2 font-bold uppercase tracking-tighter <?php echo $active ? 'text-indigo-900' : 'text-slate-400'; ?>"><?php echo $s['l']; ?></span>
                        </div>
                        <?php if ($i < 2): ?>
                            <div class="flex-1 h-1 mx-2 -mt-6 transition-all <?php echo $currentStep > $s['id'] ? 'bg-indigo-600' : 'bg-slate-200'; ?>"></div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
                    <!-- Left: Forms -->
                    <div class="lg:col-span-7">
                        <?php if (empty($cartItems)): ?>
                            <div class="bg-white rounded-3xl p-12 text-center border border-slate-200 shadow-sm animate-fade-in">
                                <div class="w-20 h-20 bg-indigo-50 text-indigo-500 rounded-full flex items-center justify-center mx-auto mb-6">
                                    <i class="fas fa-shopping-basket text-3xl"></i>
                                </div>
                                <h2 class="text-2xl font-bold text-slate-900">Your cart is empty</h2>
                                <p class="text-slate-500 mt-2 mb-8">It looks like you haven't added any courses yet.</p>
                                <a href="available_courses.php" class="bg-indigo-600 text-white px-8 py-3 rounded-xl font-bold shadow-lg shadow-indigo-100 hover:bg-indigo-700 transition-all inline-block">Explore Catalog</a>
                            </div>
                        <?php else: ?>
                            <div class="bg-white rounded-3xl shadow-sm border border-slate-200 overflow-hidden animate-fade-in">
                                <div class="p-6 lg:p-10">
                                    <?php if ($currentStep == 1): ?>
                                        <form method="GET" class="space-y-6">
                                            <input type="hidden" name="step" value="2">
                                            <h3 class="text-xl font-bold text-slate-900">Billing Details</h3>
                                            <div class="grid grid-cols-2 gap-4">
                                                <div class="col-span-2">
                                                    <label class="text-xs font-bold text-slate-500 uppercase">Email Address</label>
                                                    <input type="email" value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>" class="w-full mt-1 p-3 rounded-xl bg-slate-50 border border-slate-200 focus:ring-2 focus:ring-indigo-500 outline-none">
                                                </div>
                                                <div class="col-span-2">
                                                    <label class="text-xs font-bold text-slate-500 uppercase">Billing Address</label>
                                                    <input type="text" placeholder="Street Address" class="w-full mt-1 p-3 rounded-xl bg-slate-50 border border-slate-200 focus:ring-2 focus:ring-indigo-500 outline-none">
                                                </div>
                                                <div>
                                                    <label class="text-xs font-bold text-slate-500 uppercase">City</label>
                                                    <input type="text" class="w-full mt-1 p-3 rounded-xl bg-slate-50 border border-slate-200 focus:ring-2 focus:ring-indigo-500 outline-none">
                                                </div>
                                                <div>
                                                    <label class="text-xs font-bold text-slate-500 uppercase">Postal Code</label>
                                                    <input type="text" class="w-full mt-1 p-3 rounded-xl bg-slate-50 border border-slate-200 focus:ring-2 focus:ring-indigo-500 outline-none">
                                                </div>
                                            </div>
                                            <button type="submit" class="w-full bg-indigo-600 text-white py-4 rounded-2xl font-bold hover:bg-indigo-700 shadow-xl shadow-indigo-100 transition-all flex items-center justify-center gap-2">
                                                Continue to Payment <i class="fas fa-arrow-right text-xs"></i>
                                            </button>
                                        </form>
                                    <?php elseif ($currentStep == 2): ?>
                                        <div class="space-y-6">
                                            <h3 class="text-xl font-bold text-slate-900">Payment Method</h3>
                                            <div class="grid grid-cols-3 gap-3">
                                                <button onclick="selectPayment('card')" id="btn-card" class="payment-btn p-4 border-2 rounded-2xl flex flex-col items-center gap-2 transition-all border-indigo-600 bg-indigo-50">
                                                    <i class="fas fa-credit-card text-indigo-600"></i>
                                                    <span class="text-[10px] font-bold uppercase">Card</span>
                                                </button>
                                                <button onclick="selectPayment('paypal')" id="btn-paypal" class="payment-btn p-4 border-2 rounded-2xl flex flex-col items-center gap-2 transition-all border-slate-100 hover:border-indigo-100">
                                                    <i class="fab fa-paypal text-blue-500"></i>
                                                    <span class="text-[10px] font-bold uppercase">PayPal</span>
                                                </button>
                                                <button onclick="selectPayment('paynow')" id="btn-paynow" class="payment-btn p-4 border-2 rounded-2xl flex flex-col items-center gap-2 transition-all border-slate-100 hover:border-indigo-100">
                                                    <i class="fas fa-qrcode text-slate-400"></i>
                                                    <span class="text-[10px] font-bold uppercase">PayNow</span>
                                                </button>
                                            </div>

                                            <div class="mt-8">
                                                <div id="card-form" class="space-y-4">
                                                    <div>
                                                        <label class="text-xs font-bold text-slate-500 uppercase">Card Number</label>
                                                        <input type="text" placeholder="XXXX XXXX XXXX XXXX" class="w-full mt-1 p-3 rounded-xl bg-slate-50 border border-slate-200 outline-none">
                                                    </div>
                                                    <div class="grid grid-cols-2 gap-4">
                                                        <input type="text" placeholder="MM/YY" class="p-3 rounded-xl bg-slate-50 border border-slate-200 outline-none">
                                                        <input type="text" placeholder="CVC" class="p-3 rounded-xl bg-slate-50 border border-slate-200 outline-none">
                                                    </div>
                                                </div>
                                                <div id="paypal-form" class="hidden p-6 bg-blue-50 rounded-2xl border border-blue-100 text-center">
                                                    <p class="text-sm text-blue-700 font-medium italic">Secure redirection to PayPal...</p>
                                                </div>
                                                <div id="paynow-form" class="hidden p-6 bg-slate-50 rounded-2xl border border-slate-200">
                                                    <div class="flex items-center gap-4">
                                                        <div class="w-12 h-12 bg-white rounded-xl flex items-center justify-center border border-slate-100 shadow-sm text-indigo-600">
                                                            <i class="fas fa-qrcode text-xl"></i>
                                                        </div>
                                                        <div>
                                                            <p class="font-bold text-slate-900">PayNow Instant QR</p>
                                                            <p class="text-xs text-slate-500">Scan and pay using any banking app in the next step.</p>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="flex gap-4 pt-6">
                                                <a href="?step=1" class="flex-1 text-center py-4 rounded-2xl font-bold border border-slate-200 text-slate-500 hover:bg-slate-50 transition-all">Back</a>
                                                <a href="?step=3" class="flex-[2] text-center bg-indigo-600 text-white py-4 rounded-2xl font-bold hover:bg-indigo-700 shadow-lg shadow-indigo-100">Review Order</a>
                                            </div>
                                        </div>
                                    <?php elseif ($currentStep == 3): ?>
                                        <div class="text-center py-6 space-y-6">
                                            <div class="w-20 h-20 bg-green-50 text-green-500 rounded-full flex items-center justify-center mx-auto">
                                                <i class="fas fa-shield-check text-4xl"></i>
                                            </div>
                                            <div>
                                                <h3 class="text-2xl font-bold text-slate-900">Ready to complete?</h3>
                                                <p class="text-slate-500 mt-2">Please verify your items and total before finalizing payment.</p>
                                            </div>
                                            <div class="p-4 bg-slate-50 rounded-2xl border border-slate-100 text-left text-sm space-y-2">
                                                <div class="flex justify-between font-medium"><span class="text-slate-400 uppercase text-[10px]">Email</span><span><?php echo htmlspecialchars($user['email']); ?></span></div>
                                                <div class="flex justify-between font-medium"><span class="text-slate-400 uppercase text-[10px]">Currency</span><span>USD</span></div>
                                            </div>
                                            <button class="w-full bg-green-600 text-white py-5 rounded-3xl font-bold text-lg hover:bg-green-700 shadow-xl shadow-green-100 transform active:scale-95 transition-all">
                                                Complete Purchase • $<?php echo number_format($total, 2); ?>
                                            </button>
                                            <a href="?step=2" class="text-indigo-600 font-bold text-sm block">Edit Payment Info</a>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Right: Summary -->
                    <div class="lg:col-span-5">
                        <div class="bg-indigo-900 text-white rounded-3xl p-8 shadow-2xl sticky top-24">
                            <h4 class="text-lg font-bold mb-6 flex items-center gap-3">
                                <i class="fas fa-shopping-cart text-indigo-300"></i> Order Summary
                            </h4>
                            <div class="space-y-4 max-h-[300px] overflow-y-auto pr-2 custom-scroll">
                                <?php foreach ($cartItems as $item): ?>
                                    <div class="flex items-center gap-4">
                                        <img src="<?php echo $item['thumbnail'] ?: 'https://placehold.co/100x100/1E3A8A/ffffff?text=Course'; ?>" class="w-12 h-12 rounded-xl object-cover border border-white/10" />
                                        <div class="flex-1 min-w-0">
                                            <p class="text-sm font-bold truncate"><?php echo htmlspecialchars($item['title']); ?></p>
                                            <p class="text-[10px] text-indigo-300 uppercase font-bold tracking-widest"><?php echo $item['item_type']; ?></p>
                                        </div>
                                        <p class="font-bold text-sm">$<?php echo number_format($item['price'], 2); ?></p>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="mt-8 pt-6 border-t border-white/10 space-y-3">
                                <div class="flex justify-between text-indigo-200 text-sm"><span>Subtotal</span><span>$<?php echo number_format($subtotal, 2); ?></span></div>
                                <div class="flex justify-between text-indigo-200 text-sm"><span>Tax (10%)</span><span>$<?php echo number_format($tax, 2); ?></span></div>
                                <div class="flex justify-between text-2xl font-bold pt-2"><span>Total</span><span class="text-green-400">$<?php echo number_format($total, 2); ?></span></div>
                            </div>
                            <div class="mt-8 flex items-center gap-3 p-4 bg-white/5 rounded-2xl border border-white/10">
                                <i class="fas fa-lock text-indigo-400"></i>
                                <p class="text-[10px] uppercase font-bold tracking-widest text-indigo-200">256-Bit SSL Encrypted Payment</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        // Menu Toggle
        const btn = document.getElementById('mobileMenuButton');
        const menu = document.getElementById('mobileMenu');
        const closeBtn = document.getElementById('closeMobileMenu');

        btn.onclick = () => menu.classList.remove('hidden');
        closeBtn.onclick = () => menu.classList.add('hidden');

        // Payment Toggle
        function selectPayment(m) {
            document.querySelectorAll('.payment-btn').forEach(b => {
                b.classList.remove('border-indigo-600', 'bg-indigo-50');
                b.classList.add('border-slate-100');
            });
            document.getElementById('btn-'+m).classList.add('border-indigo-600', 'bg-indigo-50');
            
            ['card', 'paypal', 'paynow'].forEach(id => document.getElementById(id+'-form').classList.add('hidden'));
            document.getElementById(m+'-form').classList.remove('hidden');
        }
    </script>

</body>
</html>