<?php
require_once 'config.php';

// Initialize cart if not exists
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

// Handle cart updates (add/subtract/delete)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
    
    if ($product_id) {
        if ($_POST['action'] === 'update') {
            $quantity = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT);
            if ($quantity && $quantity > 0) {
                // Check stock
                $stmt = $pdo->prepare("SELECT stock FROM products WHERE id = ?");
                $stmt->execute([$product_id]);
                $product = $stmt->fetch();
                if ($product) {
                    if ($quantity <= $product['stock']) {
                        $_SESSION['cart'][$product_id] = $quantity;
                    } else {
                        $_SESSION['cart'][$product_id] = $product['stock']; // Limit to maximum stock
                    }
                }
            }
        } elseif ($_POST['action'] === 'remove') {
            unset($_SESSION['cart'][$product_id]);
        }
    }
    
    // Redirect to prevent form resubmission
    header("Location: cart.php");
    exit;
}

// Fetch items details for rendering
$cart_items = [];
$total_price = 0;

if (!empty($_SESSION['cart'])) {
    $placeholders = implode(',', array_fill(0, count($_SESSION['cart']), '?'));
    try {
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id IN ($placeholders)");
        $stmt->execute(array_keys($_SESSION['cart']));
        $products = $stmt->fetchAll();

        foreach ($products as $product) {
            $id = $product['id'];
            $quantity = $_SESSION['cart'][$id];
            $subtotal = $product['price'] * $quantity;
            $total_price += $subtotal;

            $cart_items[] = [
                'id' => $id,
                'name' => $product['name'],
                'size' => $product['size'],
                'price' => $product['price'],
                'image_url' => $product['image_url'],
                'stock' => $product['stock'],
                'quantity' => $quantity,
                'subtotal' => $subtotal
            ];
        }
    } catch (PDOException $e) {
        // Handle error elegantly
    }
}

// Cart items count
$cart_count = 0;
foreach ($_SESSION['cart'] as $qty) {
    $cart_count += $qty;
}
?>
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ตะกร้าสินค้า - Minimalist Closet</title>
    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Sarabun:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.2/font/bootstrap-icons.min.css">
    
    <style>
        :root {
            --primary-color: #1a1a1a;
            --accent-color: #8f8270;
            --bg-color: #faf9f6;
            --card-bg: #ffffff;
            --text-muted: #757575;
            --font-display: 'Outfit', 'Sarabun', sans-serif;
        }

        body {
            font-family: var(--font-display);
            background-color: var(--bg-color);
            color: var(--primary-color);
        }

        .navbar {
            background-color: rgba(255, 255, 255, 0.85);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }
        .navbar-brand {
            font-weight: 700;
            letter-spacing: 2px;
            color: var(--primary-color) !important;
        }

        /* Cart Page Specifics */
        .cart-card {
            background-color: var(--card-bg);
            border: none;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            padding: 24px;
        }
        .cart-item-row {
            padding: 20px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }
        .cart-item-row:last-child {
            border-bottom: none;
        }
        .cart-item-img {
            width: 80px;
            height: 100px;
            object-fit: cover;
            border-radius: 6px;
            background-color: #f5f5f5;
        }
        .quantity-control {
            display: flex;
            align-items: center;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            width: fit-content;
            overflow: hidden;
        }
        .quantity-btn {
            background: none;
            border: none;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .quantity-btn:hover {
            background-color: #f0f0f0;
        }
        .quantity-input {
            width: 40px;
            border: none;
            text-align: center;
            font-size: 0.9rem;
            font-weight: 600;
            outline: none;
            background: transparent;
        }
        .quantity-input::-webkit-inner-spin-button, 
        .quantity-input::-webkit-outer-spin-button { 
            -webkit-appearance: none; 
            margin: 0; 
        }

        .btn-dark-custom {
            background-color: var(--primary-color);
            color: #ffffff;
            border: 1px solid var(--primary-color);
            border-radius: 6px;
            font-weight: 500;
            padding: 12px 24px;
            letter-spacing: 0.5px;
            transition: all 0.2s ease;
            width: 100%;
            text-align: center;
            text-decoration: none;
            display: inline-block;
        }
        .btn-dark-custom:hover {
            background-color: var(--accent-color);
            border-color: var(--accent-color);
            color: white;
        }
        .btn-light-custom {
            background-color: transparent;
            color: var(--primary-color);
            border: 1px solid var(--primary-color);
            border-radius: 6px;
            font-weight: 500;
            padding: 12px 24px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            width: 100%;
            transition: all 0.2s ease;
        }
        .btn-light-custom:hover {
            background-color: rgba(0, 0, 0, 0.03);
        }
        .summary-card {
            background-color: #fcfbfa;
            border: 1px solid rgba(0, 0, 0, 0.05);
            border-radius: 12px;
            padding: 24px;
        }
    </style>
    <!-- Custom Theme & Dark Mode CSS -->
    <link rel="stylesheet" href="assets/css/style.css">
    <script src="assets/js/theme-toggle.js"></script>
</head>
<body>

    <!-- Header Navbar -->
    <nav class="navbar navbar-expand-lg sticky-top navbar-light">
        <div class="container">
            <a class="navbar-brand d-flex align-items-center gap-2" href="index.php">
                <img src="assets/images/logo.png" alt="CMTC Logo" style="height: 42px; width: auto;">
                <div class="d-flex flex-column" style="line-height: 1.2;">
                    <span class="fs-6 fw-bold">วิทยาลัยเทคนิคเชียงใหม่</span>
                    <span class="small text-muted" style="font-size: 0.75rem; letter-spacing: 1px;">MINIMALIST CLOSET</span>
                </div>
            </a>
            <div class="ms-auto d-flex align-items-center gap-2">
                <button type="button" class="theme-toggle-btn me-2" id="themeToggleBtn" title="เปลี่ยนธีม (Light/Dark)">
                    <i class="bi bi-moon-stars-fill" id="themeIcon"></i>
                </button>
                <a href="cart.php" class="nav-link position-relative px-3 me-2">
                    <i class="bi bi-bag fs-4"></i>
                    <?php if ($cart_count > 0): ?>
                        <span class="badge-cart"><?= $cart_count ?></span>
                    <?php endif; ?>
                </a>

                <?php if (isset($_SESSION['user_id'])): ?>
                    <div class="dropdown">
                        <button class="btn btn-outline-dark btn-sm dropdown-toggle d-flex align-items-center gap-2 px-3 py-1.5 rounded-pill" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bi bi-person-circle fs-5"></i>
                            <span><?= htmlspecialchars($_SESSION['user_name']) ?></span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end shadow-sm border-0 mt-2">
                            <?php if (($_SESSION['user_role'] ?? 'customer') === 'seller'): ?>
                                <li><a class="dropdown-item small text-primary fw-semibold" href="add-product.php"><i class="bi bi-plus-circle me-2"></i>จัดการ/เพิ่มสินค้า (ผู้ขาย)</a></li>
                                <li><hr class="dropdown-divider"></li>
                            <?php endif; ?>
                            <li><a class="dropdown-item small text-danger" href="logout.php"><i class="bi bi-box-arrow-right me-2"></i>ออกจากระบบ</a></li>
                        </ul>
                    </div>
                <?php else: ?>
                    <a href="login.php" class="btn btn-outline-dark btn-sm px-3 py-1.5 rounded-pill">เข้าสู่ระบบ</a>
                    <a href="register.php" class="btn btn-dark btn-sm px-3 py-1.5 rounded-pill">สมัครสมาชิก</a>
                <?php endif; ?>
            </div>
        </div>
    </nav>

    <!-- Main Container -->
    <main class="container my-5">
        <div class="row">
            <div class="col-12 mb-4">
                <a href="index.php" class="text-decoration-none text-dark fs-7">
                    <i class="bi bi-arrow-left me-1"></i> กลับไปเลือกสินค้าเพิ่มเติม
                </a>
                <h1 class="h3 fw-semibold text-uppercase mt-3 mb-1">Shopping Cart</h1>
                <p class="text-muted">ตรวจสอบรายการสินค้าในตะกร้าของคุณ</p>
            </div>
        </div>

        <?php if (empty($cart_items)): ?>
            <div class="row">
                <div class="col-12 text-center py-5 cart-card">
                    <i class="bi bi-bag-x fs-1 text-muted"></i>
                    <h3 class="h5 mt-3">ตะกร้าสินค้าของคุณว่างเปล่า</h3>
                    <p class="text-muted mb-4">ออกเดินทางค้นหาคอลเลคชันที่ใช่สำหรับคุณกันเถอะ</p>
                    <a href="index.php" class="btn-dark-custom" style="width: auto;">ไปช้อปเลย</a>
                </div>
            </div>
        <?php else: ?>
            <div class="row g-4">
                <!-- Cart Items List -->
                <div class="col-lg-8">
                    <div class="cart-card">
                        <?php foreach ($cart_items as $item): ?>
                            <div class="cart-item-row d-flex align-items-center justify-content-between">
                                <div class="d-flex align-items-center">
                                    <img src="<?= htmlspecialchars($item['image_url']) ?>" alt="<?= htmlspecialchars($item['name']) ?>" class="cart-item-img me-3">
                                    <div>
                                        <h4 class="h6 fw-semibold mb-1"><?= htmlspecialchars($item['name']) ?></h4>
                                        <p class="text-muted fs-8 mb-2">ไซส์: <span class="badge bg-light text-dark border"><?= htmlspecialchars($item['size']) ?></span></p>
                                        <span class="d-md-none fw-semibold">฿<?= number_format($item['price'], 2) ?></span>
                                    </div>
                                </div>

                                <div class="d-flex align-items-center justify-content-end gap-md-5">
                                    <!-- Price Column (desktop) -->
                                    <div class="d-none d-md-block text-end" style="min-width: 90px;">
                                        <span class="text-muted fs-8">ราคาต่อชิ้น</span>
                                        <div class="fw-semibold">฿<?= number_format($item['price'], 2) ?></div>
                                    </div>

                                    <!-- Quantity Selector -->
                                    <div>
                                        <form action="cart.php" method="POST" class="d-flex align-items-center">
                                            <input type="hidden" name="product_id" value="<?= $item['id'] ?>">
                                            <input type="hidden" name="action" value="update">
                                            
                                            <div class="quantity-control">
                                                <button type="submit" name="quantity" value="<?= $item['quantity'] - 1 ?>" class="quantity-btn" <?= $item['quantity'] <= 1 ? 'disabled' : '' ?>>
                                                    <i class="bi bi-dash"></i>
                                                </button>
                                                <input type="text" class="quantity-input" value="<?= $item['quantity'] ?>" readonly>
                                                <button type="submit" name="quantity" value="<?= $item['quantity'] + 1 ?>" class="quantity-btn" <?= $item['quantity'] >= $item['stock'] ? 'disabled' : '' ?>>
                                                    <i class="bi bi-plus"></i>
                                                </button>
                                            </div>
                                        </form>
                                    </div>

                                    <!-- Subtotal (desktop) -->
                                    <div class="d-none d-md-block text-end" style="min-width: 100px;">
                                        <span class="text-muted fs-8">ราคารวม</span>
                                        <div class="fw-bold">฿<?= number_format($item['subtotal'], 2) ?></div>
                                    </div>

                                    <!-- Remove Button -->
                                    <div>
                                        <form action="cart.php" method="POST" onsubmit="return confirm('ต้องการลบสินค้านี้ออกจากตะกร้าใช่หรือไม่?')">
                                            <input type="hidden" name="product_id" value="<?= $item['id'] ?>">
                                            <input type="hidden" name="action" value="remove">
                                            <button type="submit" class="btn btn-link text-danger p-0 border-0">
                                                <i class="bi bi-trash fs-5"></i>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Summary Panel -->
                <div class="col-lg-4">
                    <div class="cart-card summary-card">
                        <h3 class="h5 fw-semibold text-uppercase mb-4 pb-2 border-bottom">สรุปคำสั่งซื้อ</h3>
                        <div class="d-flex justify-content-between mb-3">
                            <span class="text-muted">จำนวนสินค้าทั้งหมด</span>
                            <span><?= $cart_count ?> ชิ้น</span>
                        </div>
                        <div class="d-flex justify-content-between mb-4">
                            <span class="text-muted">ค่าจัดส่ง</span>
                            <span class="text-success fw-medium">ฟรีค่าจัดส่ง</span>
                        </div>
                        <hr>
                        <div class="d-flex justify-content-between mb-4 pt-2">
                            <span class="fw-semibold">ยอดรวมทั้งสิ้น</span>
                            <span class="h4 fw-bold mb-0">฿<?= number_format($total_price, 2) ?></span>
                        </div>
                        <div class="d-flex flex-column gap-2">
                            <a href="checkout.php" class="btn-dark-custom">ดำเนินการชำระเงิน</a>
                            <a href="index.php" class="btn-light-custom">เลือกสินค้าต่อ</a>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </main>

    <!-- Footer -->
    <footer class="bg-white border-top py-4 text-center mt-5">
        <div class="container">
            <p class="mb-1 text-muted">&copy; 2026 Minimalist Closet. All Rights Reserved.</p>
        </div>
    </footer>

    <!-- Bootstrap 5 JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
