<?php
// Prevent caching
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/auth.php';

$db = getDBConnection();
$userId = isset($_SESSION['user']['id']) ? (int)$_SESSION['user']['id'] : null;
$sessionId = session_id();

if ($userId) {
    $stmt = $db->prepare("SELECT c.*, p.name, p.price, p.main_image as image, p.vendor_id FROM cart_items c JOIN products p ON c.product_id = p.id WHERE c.user_id = ?");
    $stmt->execute([$userId]);
} else {
    $stmt = $db->prepare("SELECT c.*, p.name, p.price, p.main_image as image, p.vendor_id FROM cart_items c JOIN products p ON c.product_id = p.id WHERE c.session_id = ? AND c.user_id IS NULL");
    $stmt->execute([$sessionId]);
}
$cart = $stmt->fetchAll();

$subtotal = 0;
foreach ($cart as $item) {
    $subtotal += $item['price'] * $item['quantity'];
}
$shippingFee = $subtotal > 0 ? 50.00 : 0.00;
$grandTotal = $subtotal + $shippingFee;

$pageTitle = "ตะกร้าสินค้า";
require_once __DIR__ . '/../includes/header.php';
?>

<div class="card card-custom p-4 my-4">
  <h3 class="fw-bold mb-4">🛒 ตะกร้าสินค้าของคุณ</h3>

  <?php if (empty($cart)): ?>
    <div id="emptyCartMessage" class="text-center py-5">
      <div class="fs-1">🛒</div>
      <h4 class="text-muted mt-2">ไม่มีสินค้าในตะกร้า</h4>
      <p class="text-secondary">ไปเลือกช้อปสินค้าเสื้อผ้าแฟชั่นสวยๆ กันเลย!</p>
      <a href="index.php" class="btn btn-primary-custom rounded-pill px-4 py-2 mt-2">กลับไปเลือกซื้อสินค้า</a>
    </div>
  <?php else: ?>
    <div class="table-responsive">
      <table class="table table-borderless align-middle" id="cartTable">
        <thead class="border-bottom">
          <tr>
            <th>สินค้า</th>
            <th>ไซส์ / สี</th>
            <th class="text-center" style="width: 130px;">ราคา</th>
            <th class="text-center" style="width: 150px;">จำนวน</th>
            <th class="text-end" style="width: 130px;">รวม</th>
            <th class="text-center" style="width: 80px;">ลบ</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($cart as $item): $key = $item['id']; ?>
            <tr id="row-<?php echo $key; ?>" class="border-bottom">
              <td>
                <div class="d-flex align-items-center gap-3">
                  <img src="<?php echo sanitize(formatImageUrl($item['image'] ?? '')); ?>" onerror="this.onerror=null; this.src='<?php echo SITE_URL; ?>/assets/images/no-image.png';" class="rounded" style="width: 60px; height: 60px; object-fit: cover;" alt="<?php echo sanitize($item['name']); ?>">
                  <span class="fw-bold"><?php echo sanitize($item['name']); ?></span>
                </div>
              </td>
              <td>
                <span class="badge bg-secondary"><?php echo sanitize($item['size']); ?></span>
                <span class="badge bg-info text-dark"><?php echo sanitize($item['color']); ?></span>
              </td>
              <td class="text-center">฿<?php echo number_format($item['price'], 2); ?></td>
              <td class="text-center">
                <div class="input-group input-group-sm">
                  <button class="btn btn-outline-secondary" onclick="changeQty('<?php echo $key; ?>', -1)">-</button>
                  <input type="number" id="qty-<?php echo $key; ?>" class="form-control text-center" value="<?php echo $item['quantity']; ?>" min="1" readonly>
                  <button class="btn btn-outline-secondary" onclick="changeQty('<?php echo $key; ?>', 1)">+</button>
                </div>
              </td>
              <td class="text-end fw-bold text-primary" id="subtotal-<?php echo $key; ?>">
                ฿<?php echo number_format($item['price'] * $item['quantity'], 2); ?>
              </td>
              <td class="text-center">
                <button class="btn btn-sm btn-outline-danger" onclick="removeItem('<?php echo $key; ?>')">🗑️</button>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <div class="row justify-content-end mt-4">
      <div class="col-md-5 col-lg-4">
        <div class="card card-custom p-3 bg-light">
          <div class="d-flex justify-content-between mb-2">
            <span>ราคารวมสินค้า:</span>
            <strong id="cartSubtotal">฿<?php echo number_format($subtotal, 2); ?></strong>
          </div>
          <div class="d-flex justify-content-between mb-2">
            <span>ค่าจัดส่ง:</span>
            <strong id="cartShipping">฿<?php echo number_format($shippingFee, 2); ?></strong>
          </div>
          <hr>
          <div class="d-flex justify-content-between mb-3 fs-5 fw-bold text-primary">
            <span>ยอดชำระสุทธิ:</span>
            <span id="cartGrandTotal">฿<?php echo number_format($grandTotal, 2); ?></span>
          </div>

          <a href="checkout.php" id="btnProceedCheckout" data-cart-count="<?php echo count($cart); ?>" class="btn btn-primary-custom w-100 py-3 rounded-pill text-center text-white text-decoration-none fs-5 fw-bold shadow-sm">
            ไปที่หน้าชำระเงิน 💳
          </a>
        </div>
      </div>
    </div>
  <?php endif; ?>
</div>

<script>
function changeQty(key, delta) {
    const input = document.getElementById('qty-' + key);
    let newQty = parseInt(input.value) + delta;
    if (newQty < 1) newQty = 1;

    const formData = new FormData();
    formData.append('action', 'update');
    formData.append('key', key);
    formData.append('quantity', newQty);

    fetch(SITE_URL + '/ajax/cart.php', { method: 'POST', body: formData })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            input.value = newQty;
            updateCartBadge(data.total_items);
            location.reload(); // Quick refresh for seamless calculation
        }
    });
}

function removeItem(key) {
    if (!confirm('คุณต้องการลบสินค้านี้ออกจากตะกร้าหรือไม่?')) return;

    const formData = new FormData();
    formData.append('action', 'remove');
    formData.append('key', key);

    fetch(SITE_URL + '/ajax/cart.php', { method: 'POST', body: formData })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            document.getElementById('row-' + key).remove();
            updateCartBadge(data.total_items);
            location.reload();
        }
    });
}

document.addEventListener('DOMContentLoaded', () => {
    const btnCheckout = document.getElementById('btnProceedCheckout');
    if (!btnCheckout) return;

    btnCheckout.addEventListener('click', function(e) {
        e.preventDefault();

        const cartCount = parseInt(this.dataset.cartCount || '0', 10);
        const checkoutUrl = this.getAttribute('href');

        if (cartCount <= 0) {
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    icon: 'warning',
                    title: 'ตะกร้าสินค้าว่างเปล่า',
                    text: 'กรุณาเลือกซื้อสินค้าก่อนดำเนินการชำระเงิน',
                    confirmButtonColor: '#3085d6',
                    confirmButtonText: 'ไปเลือกซื้อสินค้า'
                }).then(() => {
                    window.location.href = SITE_URL + '/index.php';
                });
            } else {
                alert('⚠️ ตะกร้าสินค้าของคุณยังว่างเปล่า กรุณาเลือกซื้อสินค้าก่อนชำระเงิน');
            }
            return;
        }

        this.classList.add('disabled');
        this.innerHTML = `<span class="spinner-border spinner-border-sm me-2"></span>กำลังไปยังหน้าชำระเงิน...`;
        window.location.href = checkoutUrl;
    });
});
</script>

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