<?php
// หน้าตะกร้าสินค้าและการชำระเงิน (cart.php)
require_once 'config.php';

$cartItems = $_SESSION['cart'] ?? [];

// คำนวณยอดรวม
$totalAmount = 0;
foreach ($cartItems as $item) {
    $totalAmount += ($item['price'] * $item['qty']);
}

// นับจำนวนสินค้าในตะกร้า
$cartCount = 0;
foreach ($cartItems as $item) {
    $cartCount += $item['qty'];
}
?>
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ตะกร้าสินค้าของคุณ - AMARA STUDIO</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
</head>
<body>

    <!-- Header Navigation -->
    <header>
        <div class="nav-container">
            <a href="index.php" class="logo">AMARA<span>STUDIO</span></a>
            <ul class="nav-menu">
                <li><a href="index.php" class="nav-link">คอลเลกชันทั้งหมด</a></li>
                <li>
                    <a href="cart.php" class="nav-link active cart-icon-wrapper">
                        ตะกร้าสินค้า
                        <span class="cart-count" id="cart-nav-count"><?= $cartCount ?></span>
                    </a>
                </li>
                <li><a href="manual.php" class="nav-link">📖 คู่มือการใช้งาน</a></li>
                <?php if (isLoggedIn()): ?>
                    <li><a href="favorites.php" class="nav-link">❤️ สินค้าที่ถูกใจ</a></li>
                    <?php if (isSellerLoggedIn()): ?>
                        <li><a href="seller_dashboard.php" class="nav-link admin-btn">🏪 แดชบอร์ดผู้ขาย</a></li>
                    <?php endif; ?>
                    <li style="display: flex; align-items: center; gap: 10px; margin-left: 10px;">
                        <span style="color: var(--primary); font-size: 14px; font-weight: 600;">👋 <?= htmlspecialchars(getAdminName()) ?></span>
                        <a href="logout.php" class="nav-link" style="color: #e53e3e;">ออกจากระบบ</a>
                    </li>
                <?php else: ?>
                    <li><a href="login.php" class="nav-link admin-btn">เข้าสู่ระบบ</a></li>
                <?php endif; ?>
            </ul>
        </div>
    </header>

    <!-- Main Container -->
    <div class="container">
        <div id="cart-content-wrapper">
            
            <?php if (empty($cartItems)): ?>
                <!-- กรณีตะกร้าว่าง -->
                <div style="background: white; border: 1px solid var(--border); border-radius: var(--radius); padding: 80px 20px; text-align: center; max-width: 600px; margin: 0 auto;">
                    <span style="font-size: 50px; display: block; margin-bottom: 20px;">🛒</span>
                    <h2>ตะกร้าสินค้าของคุณยังว่างอยู่</h2>
                    <p style="color: var(--text-muted); margin-top: 10px; margin-bottom: 30px;">คุณยังไม่ได้เลือกสินค้าใดๆ เข้ามาในตะกร้าช็อปปิ้ง</p>
                    <a href="index.php" class="btn btn-dark">เลือกซื้อเสื้อผ้าแฟชั่น</a>
                </div>
            <?php else: ?>
                <!-- แสดงรายการสินค้าและฟอร์มจัดส่ง -->
                <div class="cart-layout">
                    
                    <!-- ฝั่งซ้าย: รายการเสื้อผ้าที่เลือก -->
                    <div class="cart-items-panel">
                        <h2 class="cart-title">สรุปรายการสินค้าในตะกร้า</h2>
                        
                        <div id="cart-items-list">
                            <?php foreach ($cartItems as $key => $item): ?>
                                <div class="cart-item" id="cart-item-row-<?= $item['variant_id'] ?>">
                                    <img src="<?= htmlspecialchars($item['image']) ?>" alt="<?= htmlspecialchars($item['name']) ?>" class="cart-item-img">
                                    
                                    <div class="cart-item-details">
                                        <h3 class="cart-item-name"><?= htmlspecialchars($item['name']) ?></h3>
                                        
                                        <!-- เน้นย้ำ สี และ ไซซ์ ให้เป็นตัวหนาชัดเจนเพื่อรีวิวออเดอร์ -->
                                        <div class="cart-item-variant">
                                            ตัวเลือก: 
                                            <strong>สี: <?= htmlspecialchars($item['details']['Color'] ?? '-') ?></strong> &nbsp;
                                            <strong>ไซซ์: <?= htmlspecialchars($item['details']['Size'] ?? '-') ?></strong>
                                        </div>
                                        
                                        <div class="cart-item-actions">
                                            <span style="font-size: 14px; color: var(--text-muted);">จำนวน: <?= $item['qty'] ?> ชิ้น</span>
                                            <button type="button" class="cart-item-remove" onclick="removeFromCart('<?= $key ?>', <?= $item['variant_id'] ?>)">ลบออก</button>
                                        </div>
                                    </div>
                                    
                                    <div class="cart-item-price">
                                        ฿<?= number_format($item['price'] * $item['qty']) ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- ฝั่งขวา: สรุปราคารวมและฟอร์มผู้รับ -->
                    <div class="checkout-panel">
                        <h2 class="cart-title" style="border-bottom: none; margin-bottom: 15px; padding-bottom: 0;">สรุปยอดคำสั่งซื้อ</h2>
                        
                        <div class="summary-row">
                            <span>ราคาสินค้าทั้งหมด</span>
                            <span id="summary-subtotal">฿<?= number_format($totalAmount) ?></span>
                        </div>
                        <div class="summary-row">
                            <span>ค่าจัดส่งสินค้า</span>
                            <span style="color: var(--success); font-weight: 600;">ฟรี (Free)</span>
                        </div>
                        <div class="summary-row total">
                            <span>ยอดชำระสุทธิ</span>
                            <span id="summary-total">฿<?= number_format($totalAmount) ?></span>
                        </div>

                        <!-- ฟอร์มข้อมูลจัดส่ง -->
                        <div style="border-top: 1px solid var(--border); padding-top: 20px; margin-top: 10px;">
                            <h3 class="checkout-form-title">ที่อยู่และข้อมูลผู้รับพัสดุ</h3>
                            
                            <div class="form-group">
                                <label for="customer_name">ชื่อ-นามสกุล ผู้รับ *</label>
                                <input type="text" id="customer_name" placeholder="เช่น คุณ นารี รักดี" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="shipping_address">ที่อยู่จัดส่งพัสดุ (โดยละเอียด) *</label>
                                <textarea id="shipping_address" placeholder="บ้านเลขที่, ถนน, ตำบล, อำเภอ, จังหวัด และรหัสไปรษณีย์" required></textarea>
                            </div>
                            
                            <button type="button" class="checkout-btn" onclick="submitCheckout()">
                                ยืนยันการสั่งซื้อสินค้า
                            </button>
                        </div>
                    </div>

                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Footer -->
    <footer style="background-color: white; border-top: 1px solid var(--border); padding: 40px 0; margin-top: 80px; text-align: center; color: var(--text-muted);">
        <p>© 2026 AMARA STUDIO. All rights reserved. เว็บไซต์นี้จำลองสถาปัตยกรรม E-Commerce แฟชั่นพรีเมียม</p>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        // ลบสินค้าออกจากตะกร้าแบบ AJAX
        function removeFromCart(cartKey, variantId) {
            Swal.fire({
                title: 'ลบสินค้าออก?',
                text: 'ต้องการลบสินค้าชิ้นนี้ออกจากตะกร้าใช่หรือไม่?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#e53e3e',
                cancelButtonColor: '#718096',
                confirmButtonText: 'ลบออก',
                cancelButtonText: 'ยกเลิก'
            }).then((result) => {
                if (!result.isConfirmed) return;

                fetch('api.php?action=remove_from_cart', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ cart_key: cartKey })
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('cart-nav-count').innerText = data.total_count;
                        const row = document.getElementById('cart-item-row-' + variantId);
                        if (row) {
                            row.style.transition = 'opacity 0.3s';
                            row.style.opacity = '0';
                            setTimeout(() => {
                                row.remove();
                                if (data.total_count === 0) window.location.reload();
                            }, 300);
                        }
                        document.getElementById('summary-subtotal').innerText = '฿' + data.total_amount.toLocaleString();
                        document.getElementById('summary-total').innerText = '฿' + data.total_amount.toLocaleString();
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'เกิดข้อผิดพลาด',
                            text: data.message,
                            confirmButtonColor: '#c5a880'
                        });
                    }
                })
                .catch(err => {
                    console.error(err);
                    Swal.fire({
                        icon: 'error',
                        title: 'เชื่อมต่อไม่ได้',
                        text: 'กรุณาลองใหม่อีกครั้ง',
                        confirmButtonColor: '#c5a880'
                    });
                });
            });
        }

        // ยืนยันการสั่งซื้อส่งออเดอร์ไปเซิร์ฟเวอร์
        function submitCheckout() {
            const customerName = document.getElementById('customer_name').value.trim();
            const shippingAddress = document.getElementById('shipping_address').value.trim();

            if (!customerName || !shippingAddress) {
                Swal.fire({
                    icon: 'warning',
                    title: 'ข้อมูลไม่ครบถ้วน',
                    text: 'กรุณากรอกชื่อและที่อยู่จัดส่งสินค้าให้ครบถ้วนก่อนส่งข้อมูล',
                    confirmButtonColor: '#c5a880'
                });
                return;
            }

            const btn = document.querySelector('.checkout-btn');
            btn.disabled = true;
            btn.innerText = 'กำลังประมวลผลสั่งซื้อ...';

            fetch('api.php?action=checkout', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ customer_name: customerName, shipping_address: shippingAddress })
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('cart-nav-count').innerText = '0';
                    const wrapper = document.getElementById('cart-content-wrapper');
                    wrapper.innerHTML = `
                        <div class="success-card">
                            <div class="success-icon">✓</div>
                            <h2 style="font-size: 26px; color: var(--dark);">ขอบคุณสำหรับการสั่งซื้อของคุณ!</h2>
                            <p style="color: var(--text-muted); margin-top: 10px;">เราได้รับออเดอร์ของคุณเรียบร้อยแล้วและกำลังเตรียมการจัดส่งพัสดุ</p>
                            <div style="background: var(--light); border: 1px solid var(--border); border-radius: 8px; padding: 20px; margin: 30px 0; text-align: left; font-size: 14px;">
                                <p style="margin-bottom: 8px;"><strong>เลขออเดอร์อ้างอิง:</strong> #ORD-${data.order_id}</p>
                                <p style="margin-bottom: 8px;"><strong>ชื่อผู้รับ:</strong> ${customerName}</p>
                                <p><strong>ที่อยู่จัดส่ง:</strong> ${shippingAddress}</p>
                            </div>
                            <div style="display: flex; gap: 15px; justify-content: center;">
                                <a href="index.php" class="btn btn-dark">ช็อปเสื้อผ้าต่อ</a>
                                <a href="admin.php" class="btn btn-outline">ไปหน้าดูแลหลังบ้านเพื่อแพ็กของ</a>
                            </div>
                        </div>
                    `;
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'ไม่สามารถสั่งซื้อได้',
                        text: data.message,
                        confirmButtonColor: '#c5a880'
                    });
                    btn.disabled = false;
                    btn.innerText = 'ยืนยันการสั่งซื้อสินค้า';
                }
            })
            .catch(err => {
                console.error(err);
                Swal.fire({
                    icon: 'error',
                    title: 'เกิดข้อผิดพลาดทางเทคนิค',
                    text: 'กรุณาลองใหม่อีกครั้ง',
                    confirmButtonColor: '#c5a880'
                });
                btn.disabled = false;
                btn.innerText = 'ยืนยันการสั่งซื้อสินค้า';
            });
        }
    </script>
</body>
</html>
