<?php
require_once 'config.php';

// Redirect if cart is empty
if (empty($_SESSION['cart'])) {
    header("Location: index.php");
    exit;
}

// Fetch items details for order summary
$cart_items = [];
$total_price = 0;
$cart_count = 0;

$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_count += $quantity;

        $cart_items[] = [
            'name' => $product['name'],
            'size' => $product['size'],
            'price' => $product['price'],
            'quantity' => $quantity,
            'subtotal' => $subtotal
        ];
    }
} catch (PDOException $e) {
    // Handle error
}
?>
<!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;
        }

        .checkout-card {
            background-color: var(--card-bg);
            border: none;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            padding: 30px;
        }

        .form-control-custom {
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 10px 14px;
            font-size: 0.95rem;
            outline: none;
            transition: border-color 0.2s ease;
        }
        .form-control-custom:focus {
            border-color: var(--accent-color);
            box-shadow: none;
        }

        .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;
        }

        .order-summary-item {
            padding: 12px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }
        .order-summary-item:last-child {
            border-bottom: none;
        }
    </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>
                <?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="cart.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">Shipping Details</h1>
                <p class="text-muted">กรอกข้อมูลการจัดส่งเพื่อดำเนินการสั่งซื้อ</p>
            </div>
        </div>

        <div class="row g-4">
            <!-- Form delivery info -->
            <div class="col-lg-7">
                <div class="checkout-card">
                    <h2 class="h5 fw-semibold text-uppercase mb-4 pb-2 border-bottom">ข้อมูลผู้รับสินค้า</h2>
                    
                    <?php if (isset($_SESSION['checkout_error'])): ?>
                        <div class="alert alert-danger border-0 small py-2.5 mb-4" role="alert">
                            <i class="bi bi-exclamation-triangle-fill me-2"></i><?= htmlspecialchars($_SESSION['checkout_error']) ?>
                        </div>
                        <?php unset($_SESSION['checkout_error']); ?>
                    <?php endif; ?>

                    <form action="process-order.php" method="POST">
                        <div class="mb-3">
                            <label for="customer_name" class="form-label fw-medium">ชื่อ-นามสกุล <span class="text-danger">*</span></label>
                            <input type="text" name="customer_name" id="customer_name" class="form-control form-control-custom" placeholder="ตัวอย่าง: สมชาย รักดี" value="<?= htmlspecialchars($_SESSION['user_name'] ?? '') ?>" required>
                        </div>

                        <div class="mb-3">
                            <label for="phone" class="form-label fw-medium">เบอร์โทรศัพท์ <span class="text-danger">*</span></label>
                            <input type="tel" name="phone" id="phone" class="form-control form-control-custom" placeholder="ตัวอย่าง: 0812345678" pattern="[0-9]{9,10}" title="กรุณากรอกเบอร์โทรศัพท์ที่ถูกต้อง 9-10 หลัก" value="<?= htmlspecialchars($_SESSION['user_phone'] ?? '') ?>" required>
                        </div>

                        <div class="mb-4">
                            <label for="address" class="form-label fw-medium">ที่อยู่การจัดส่ง <span class="text-danger">*</span></label>
                            <textarea name="address" id="address" class="form-control form-control-custom" rows="4" placeholder="กรุณาระบุ บ้านเลขที่, ถนน, ตำบล, อำเภอ, จังหวัด และรหัสไปรษณีย์" required><?= htmlspecialchars($_SESSION['user_address'] ?? '') ?></textarea>
                        </div>

                        <button type="submit" class="btn-dark-custom py-3 text-uppercase fw-semibold tracking-wider">
                            ยืนยันการสั่งซื้อและชำระเงิน <i class="bi bi-check-circle ms-1"></i>
                        </button>
                    </form>
                </div>
            </div>

            <!-- Order Summary -->
            <div class="col-lg-5">
                <div class="checkout-card" style="background-color: #fcfbfa; border: 1px solid rgba(0, 0, 0, 0.05);">
                    <h2 class="h5 fw-semibold text-uppercase mb-4 pb-2 border-bottom">สรุปรายการสั่งซื้อ</h2>
                    
                    <div class="mb-4">
                        <?php foreach ($cart_items as $item): ?>
                            <div class="order-summary-item d-flex justify-content-between align-items-start">
                                <div>
                                    <h4 class="h6 fw-semibold mb-0"><?= htmlspecialchars($item['name']) ?></h4>
                                    <small class="text-muted">ไซส์: <?= htmlspecialchars($item['size']) ?> | จำนวน: <?= $item['quantity'] ?></small>
                                </div>
                                <span class="fw-semibold">฿<?= number_format($item['subtotal'], 2) ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <div class="pt-3 border-top">
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-muted">จำนวนสินค้าทั้งหมด</span>
                            <span><?= $cart_count ?> ชิ้น</span>
                        </div>
                        <div class="d-flex justify-content-between mb-3">
                            <span class="text-muted">ค่าจัดส่ง</span>
                            <span class="text-success fw-medium">ฟรีค่าจัดส่ง</span>
                        </div>
                        <hr>
                        <div class="d-flex justify-content-between pt-2">
                            <span class="fw-semibold">ราคารวมสุทธิ</span>
                            <span class="h4 fw-bold mb-0">฿<?= number_format($total_price, 2) ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </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>
