<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>ตะกร้าสินค้า | IT Hub</title>
  <link rel="stylesheet" href="/css/cart.css">
  <link href="https://fonts.googleapis.com/css2?family=Prompt:wght@400;600&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
</head>
<body>
  <div class="cart-container">
    <h1 class="cart-title">🛒 ตะกร้าสินค้า</h1>

    <% if (cart && cart.length > 0) { %>
      <!-- อัปเดตจำนวนสินค้า -->
      <form action="/update-cart" method="POST">
        <table class="cart-table">
          <thead>
            <tr>
              <th>สินค้า</th>
              <th>ราคา</th>
              <th>จำนวน</th>
              <th>รวม</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <% let total = 0; %>
            <% cart.forEach((item, index) => { %>
              <% total += item.price * item.quantity; %>
              <tr>
                <td><%= item.name %></td>
                <td>฿<%= item.price %></td>
                <td>
                  <input type="number" name="quantities[]" value="<%= item.quantity %>" min="1">
                  <input type="hidden" name="ids[]" value="<%= item.id %>">
                </td>
                <td>฿<%= item.price * item.quantity %></td>
                <td>
                  <button type="button" class="remove-btn" onclick="removeItem('<%= item.id %>', this)">
                    <i class="fas fa-trash-alt"></i>
                  </button>
                </td>
              </tr>
            <% }) %>
          </tbody>
        </table>

        <div class="cart-summary-box">
          <p>💵 รวมทั้งหมด: <strong>฿<%= total.toLocaleString() %></strong></p>
        </div>

        <div class="cart-actions">
          <button type="submit" class="btn update-btn">
            <i class="fas fa-sync-alt"></i> อัปเดตจำนวนสินค้า
          </button>
      </form>

      <!-- ✅ ฟอร์มสั่งซื้อแยก -->
      <form action="/checkout" method="POST" style="display:inline;">
        <button type="submit" class="btn checkout-btn">
          <i class="fas fa-credit-card"></i> สั่งซื้อสินค้า
        </button>
      </form>

      <!-- ปุ่มอื่นๆ -->
      <a href="/products" class="btn add-more-btn">
        <i class="fas fa-plus-circle"></i> เลือกซื้อสินค้าเพิ่มเติม
      </a>

      <a href="/products" class="btn back-button">
        <i class="fas fa-arrow-left"></i> กลับหน้าสินค้า
      </a>
    </div>

    <% } else { %>
      <!-- ไม่มีสินค้า -->
      <div class="empty-cart">
        <p class="empty">ไม่มีสินค้าในตะกร้า</p>
        <a href="/products" class="back-button">← กลับไปเลือกสินค้า</a>
      </div>
    <% } %>
  </div>

  <!-- ✅ JavaScript ลบสินค้า -->
  <script>
    async function removeItem(id, btn) {
      if (!confirm('ต้องการลบสินค้านี้ใช่ไหม?')) return;

      try {
        const res = await fetch('/remove-from-cart', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id })
        });

        if (res.ok) {
          const row = btn.closest('tr');
          row.remove();

          const productRows = document.querySelectorAll('.cart-table tbody tr');
          if (productRows.length === 0) {
            document.querySelector('.cart-table')?.remove();
            document.querySelector('.cart-summary-box')?.remove();
            document.querySelector('.cart-actions')?.remove();
            const container = document.querySelector('.cart-container');
            container.insertAdjacentHTML('beforeend', `
              <div class="empty-cart">
                <p class="empty">ไม่มีสินค้าในตะกร้า</p>
                <a href="/products" class="back-button">← กลับไปเลือกสินค้า</a>
              </div>
            `);
          }
        } else {
          alert('ลบไม่สำเร็จ');
        }
      } catch (err) {
        console.error(err);
        alert('เกิดข้อผิดพลาด');
      }
    }
  </script>
</body>
</html>