<?php
require_once __DIR__ . '/header.php';

// ------------------------------------------------------------
// 1. ตรวจสอบว่าล็อกอินหรือยัง
// ------------------------------------------------------------
if (!is_logged_in()) {
    header('Location: login.php');
    exit;
}

// ------------------------------------------------------------
// 2. ตรวจสอบว่ามีสินค้าในตะกร้าหรือไม่
// ------------------------------------------------------------
if (get_cart_count() === 0) {
    header('Location: cart.php');
    exit;
}

$user = current_user();
$error = '';

// ------------------------------------------------------------
// 3. ดึงรายละเอียดสินค้าจากฐานข้อมูล
// ------------------------------------------------------------
$cart_items = [];
$total_price = 0;

$product_ids = [];
foreach ($_SESSION['cart'] as $cart_key => $item) {
    if (is_array($item)) {
        $product_ids[] = (int)$item['product_id'];
    } else {
        $parts = explode('_', $cart_key);
        $product_ids[] = (int)$parts[0];
    }
}
$product_ids = array_unique($product_ids);
$placeholders = implode(',', array_fill(0, count($product_ids), '?'));

$stmt = $pdo->prepare("SELECT * FROM products WHERE id IN ($placeholders)");
$stmt->execute($product_ids);
$products_db = $stmt->fetchAll();

$products_map = [];
foreach ($products_db as $p) {
    $products_map[$p['id']] = $p;
}

foreach ($_SESSION['cart'] as $cart_key => $item) {
    if (is_array($item)) {
        $p_id  = $item['product_id'];
        $qty   = $item['quantity'];
        $color = $item['color'];
        $size  = $item['size'];
    } else {
        $parts = explode('_', $cart_key);
        $p_id  = (int)$parts[0];
        $qty   = (int)$item;
        $color = $parts[1] ?? '';
        $size  = $parts[2] ?? '';
    }

    if (isset($products_map[$p_id])) {
        $prod = $products_map[$p_id];
        $subtotal = $prod['price'] * $qty;
        $total_price += $subtotal;

        $cart_items[] = [
            'id'       => $p_id,
            'name'     => $prod['name'],
            'price'    => $prod['price'],
            'stock'    => $prod['stock'],
            'color'    => $color,
            'size'     => $size,
            'quantity' => $qty,
            'subtotal' => $subtotal
        ];
    }
}

// ------------------------------------------------------------
// 4. ประมวลผลการสั่งซื้อเมื่อผู้ใช้ยืนยัน (PDO Transaction)
// ------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_checkout'])) {
    try {
        // เริ่มต้น Transaction
        $pdo->beginTransaction();

        // 4.1 บันทึกข้อมูลลงตาราง orders (ตั้งค่าเริ่มต้นเป็น pending รอจัดส่ง)
        $stmt_order = $pdo->prepare("INSERT INTO orders (user_id, total_price, status) VALUES (?, ?, 'pending')");
        $stmt_order->execute([$user['id'], $total_price]);
        $order_id = $pdo->lastInsertId();

        // เตรียม Query สำหรับ order_items และการตัดสต็อก
        $stmt_item = $pdo->prepare("INSERT INTO order_items (order_id, product_id, color, size, quantity, price) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt_stock = $pdo->prepare("UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?");

        // 4.2 Loop บันทึกแต่ละรายการ และตัดสต็อกสินค้า
        foreach ($cart_items as $item) {
            // บันทึกรายการสินค้าในคำสั่งซื้อ (เพิ่มฟิลด์สีและไซส์)
            $stmt_item->execute([$order_id, $item['id'], $item['color'], $item['size'], $item['quantity'], $item['price']]);

            // ตัดสต็อกสินค้าโดยอัตโนมัติ (และป้องกันการตัดติดลบด้วย AND stock >= ?)
            $stmt_stock->execute([$item['quantity'], $item['id'], $item['quantity']]);

            // หากจำนวนแถวที่ถูกอัปเดตเป็น 0 แสดงว่าสต็อกไม่พอชั่วขณะ
            if ($stmt_stock->rowCount() === 0) {
                throw new Exception("สินค้า <strong>" . htmlspecialchars($item['name']) . "</strong> มีจำนวนในสต็อกไม่เพียงพอสำหรับการสั่งซื้อ");
            }
        }

        // ยืนยัน Transaction (Commit)
        $pdo->commit();

        // ล้างตะกร้าสินค้าหลังจากทำรายการสำเร็จ
        unset($_SESSION['cart']);

        // เปลี่ยนหน้าไปยัง success.php พร้อม Order ID
        header("Location: success.php?order_id={$order_id}");
        exit;

    } catch (Exception $e) {
        // ยกเลิกรายการหากเกิดข้อผิดพลาด (Rollback)
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $error = $e->getMessage();
    }
}
?>

<div class="row justify-content-center py-3">
    <div class="col-lg-8">
        
        <div class="d-flex align-items-center mb-4">
            <a href="cart.php" class="btn btn-outline-secondary rounded-circle me-3" style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center;">
                <i class="fa-solid fa-arrow-left"></i>
            </a>
            <div>
                <h3 class="fw-bold mb-0">ยืนยันคำสั่งซื้อและชำระเงิน</h3>
                <p class="text-muted small mb-0">ตรวจสอบรายละเอียดที่อยู่และรายการสินค้าก่อนยืนยัน</p>
            </div>
        </div>

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show rounded-3 mb-4" role="alert">
                <i class="fa-solid fa-triangle-exclamation me-2"></i> <?= $error ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row g-4">
            <!-- Customer Info -->
            <div class="col-md-5">
                <div class="card border-0 shadow-sm rounded-4 mb-3">
                    <div class="card-body p-4">
                        <h5 class="fw-bold mb-3"><i class="fa-solid fa-address-card text-primary me-2"></i>ข้อมูลผู้สั่งซื้อ</h5>
                        
                        <div class="mb-3">
                            <label class="text-muted small d-block">ชื่อ-นามสกุล</label>
                            <span class="fw-semibold text-dark fs-6"><?= htmlspecialchars($user['fullname']) ?></span>
                        </div>
                        <div class="mb-3">
                            <label class="text-muted small d-block">ชื่อผู้ใช้ (Username)</label>
                            <span class="fw-medium text-secondary">@<?= htmlspecialchars($user['username']) ?></span>
                        </div>
                        <div class="mb-3">
                            <label class="text-muted small d-block">อีเมลติดต่อ</label>
                            <span class="fw-medium text-secondary"><?= htmlspecialchars($user['email']) ?></span>
                        </div>
                        <div class="p-3 bg-light rounded-3 border">
                            <small class="text-muted d-block"><i class="fa-solid fa-shield-check text-success me-1"></i>ระบบชำระเงินจำลอง (Demo Payment)</small>
                            <small class="text-secondary">การสั่งซื้อจะทำการตัดสต็อกและบันทึกลงฐานข้อมูลจริงทันที</small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Order Items Summary -->
            <div class="col-md-7">
                <div class="card border-0 shadow-sm rounded-4">
                    <div class="card-body p-4">
                        <h5 class="fw-bold mb-3"><i class="fa-solid fa-list-check text-primary me-2"></i>รายการสินค้าในคำสั่งซื้อ</h5>
                        
                        <div class="table-responsive mb-3">
                            <table class="table align-middle">
                                <thead class="table-light small">
                                    <tr>
                                        <th>สินค้า</th>
                                        <th class="text-center">จำนวน</th>
                                        <th class="text-end">ราคารวม</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($cart_items as $item): ?>
                                        <tr>
                                            <td>
                                                <span class="fw-medium text-dark d-block"><?= htmlspecialchars($item['name']) ?></span>
                                                <small class="text-muted"><?= format_price($item['price']) ?> / ชิ้น</small>
                                            </td>
                                            <td class="text-center fw-semibold"><?= $item['quantity'] ?></td>
                                            <td class="text-end fw-bold text-primary"><?= format_price($item['subtotal']) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <div class="d-flex justify-content-between align-items-center p-3 bg-primary bg-opacity-10 rounded-3 mb-4">
                            <span class="fw-bold text-primary fs-5">ยอดชำระสุทธิ</span>
                            <span class="fw-bold text-primary fs-4"><?= format_price($total_price) ?></span>
                        </div>

                        <form method="POST" action="checkout.php">
                            <button type="submit" name="confirm_checkout" class="btn btn-primary-custom w-100 py-3 rounded-pill fw-bold fs-6 shadow">
                                <i class="fa-solid fa-circle-check me-2"></i>ยืนยันคำสั่งซื้อชำระเงิน
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<?php require_once __DIR__ . '/footer.php'; ?>
