<?php
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
require_once __DIR__ . '/helpers/currency_helper.php';

// Load products from JSON to match admin-managed products
$products = [];
$dataFile = __DIR__ . '/data/products.json';
if (file_exists($dataFile)) {
    $list = json_decode(file_get_contents($dataFile), true) ?: [];
    foreach ($list as $pr) { $products[$pr['id']] = $pr; }
} else {
    $products = [
      1=>['id'=>1,'title'=>'Floral Midi Dress','price'=>79],
      2=>['id'=>2,'title'=>'Silk Blouse','price'=>49],
      3=>['id'=>3,'title'=>'Wool Coat','price'=>129],
      4=>['id'=>4,'title'=>'Leather Belt','price'=>29],
    ];
}

// initialize cart
if (!isset($_SESSION['cart']) || !is_array($_SESSION['cart'])) $_SESSION['cart'] = [];

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'add') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $qty = isset($_POST['qty']) ? max(1,(int)$_POST['qty']) : 1;
        $size = isset($_POST['size']) ? trim($_POST['size']) : '';
        
        if ($id && isset($products[$id])) {
            // Store cart items with unique key combining id and size
            $cartKey = $id . '_' . $size;
            if (!isset($_SESSION['cart'][$cartKey])) {
                $_SESSION['cart'][$cartKey] = [
                    'id' => $id,
                    'size' => $size,
                    'qty' => 0
                ];
            }
            $_SESSION['cart'][$cartKey]['qty'] += $qty;
        }
        header('Location: cart.php'); exit;
    }

    if ($action === 'update') {
        $quantities = $_POST['qty'] ?? [];
        foreach ($quantities as $cartKey => $q) {
            $q = max(0, (int)$q);
            if ($q > 0 && isset($_SESSION['cart'][$cartKey])) { 
                $_SESSION['cart'][$cartKey]['qty'] = $q; 
            } else if (isset($_SESSION['cart'][$cartKey])) { 
                unset($_SESSION['cart'][$cartKey]); 
            }
        }
        header('Location: cart.php'); exit;
    }

    if ($action === 'remove') {
        $cartKey = isset($_POST['id']) ? $_POST['id'] : '';
        unset($_SESSION['cart'][$cartKey]);
        header('Location: cart.php'); exit;
    }

    if ($action === 'clear') {
        $_SESSION['cart'] = [];
        header('Location: cart.php'); exit;
    }

    if ($action === 'checkout') {
        // collect user info (no real processing in frontend demo)
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $city = trim($_POST['city'] ?? '');
        $postal = trim($_POST['postal'] ?? '');
        $payment_method = $_POST['payment_method'] ?? '';

        $order_valid = $name && $email && $address && $city && $postal && $payment_method;
        if ($order_valid) {
            // create a simple order summary and clear cart
            $order = [
                'name'=>$name,'email'=>$email,'address'=>$address,'phone'=>$phone,
                'city'=>$city,'postal'=>$postal,'payment_method'=>$payment_method,
                'items'=>$_SESSION['cart'], 'time'=>date('c')
            ];
            $_SESSION['last_order'] = $order;
            $_SESSION['cart'] = [];
            $confirmed = true;
        } else {
            $error = 'Please fill all required fields to place order.';
        }
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Shopping Cart</title>
  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css">
</head>
<body>
<?php include __DIR__ . '/header.php'; ?>

<main style="padding:20px 0;">
  <div style="max-width:1320px; margin:0 auto; padding:0 20px;">
    
    <?php if (!empty($confirmed)): ?>
      <div class="newsletter" style="margin-top:12px;">
        <h3>Order Confirmed</h3>
        <p class="muted">Thanks <?php echo htmlspecialchars($_SESSION['last_order']['name']); ?> — we received your order.</p>
        <p class="muted">A confirmation email would be sent to <?php echo htmlspecialchars($_SESSION['last_order']['email']); ?> (demo).</p>
      </div>
    <?php endif; ?>

    <?php if (!empty($error)): ?>
      <p class="muted"><?php echo htmlspecialchars($error); ?></p>
    <?php endif; ?>

    <?php if (empty($_SESSION['cart'])): ?>
      <div style="max-width:1320px; margin:60px auto; padding:0 20px; text-align:center;">
        <h1 style="font-size:42px; font-weight:700; color:#333; margin-bottom:20px;">Shopping Cart</h1>
        <div style="background:#fff; padding:60px 40px; border-radius:8px; box-shadow:0 2px 8px rgba(0,0,0,0.04);">
          <p style="font-size:18px; color:#666; margin-bottom:20px;">Your cart is currently empty.</p>
          <a href="shop.php" style="display:inline-block; background:#F07E2D; color:#fff; padding:12px 30px; text-decoration:none; border-radius:6px; font-weight:600; transition:all 0.3s ease;">Return to shop</a>
        </div>
      </div>
    <?php else: ?>
      <form method="post" action="cart.php">
        <input type="hidden" name="action" value="update">
        <table style="width:100%; border-collapse:collapse; margin-top:12px;">
          <thead>
            <tr>
              <th style="text-align:left;padding:8px">Product</th>
              <th style="padding:8px">Size</th>
              <th style="padding:8px">Price</th>
              <th style="padding:8px">Qty</th>
              <th style="padding:8px">Subtotal</th>
              <th style="padding:8px"></th>
            </tr>
          </thead>
          <tbody>
          <?php 
          $total = 0; 
          foreach ($_SESSION['cart'] as $cartKey=>$item): 
            // Handle both old and new cart structure for backward compatibility
            $id = is_array($item) ? $item['id'] : $cartKey;
            $qty = is_array($item) ? $item['qty'] : $item;
            $size = is_array($item) ? $item['size'] : '';
            
            if (!isset($products[$id])) continue; 
            $p=$products[$id]; 
            // Prices are stored in EUR
            $subtotal=(float)$p['price']*$qty; 
            $total += $subtotal; 
          ?>
            <tr>
              <td style="padding:8px; vertical-align:middle;">
                <div style="display:flex; gap:12px; align-items:center;">
                  <img src="pics_ecom/p<?php echo $id; ?>.png" alt="<?php echo htmlspecialchars($p['title']); ?>" style="width:80px; height:80px; object-fit:cover; border-radius:6px;">
                  <div>
                    <strong><?php echo htmlspecialchars($p['title']); ?></strong>
                  </div>
                </div>
              </td>
              <td style="padding:8px; text-align:center;"><?php echo !empty($size) ? htmlspecialchars($size) : 'N/A'; ?></td>
              <td style="padding:8px; text-align:center;"><?php echo htmlspecialchars(format_currency((float)$p['price'])); ?></td>
              <td style="padding:8px; text-align:center;"><input type="number" name="qty[<?php echo $cartKey; ?>]" value="<?php echo $qty; ?>" min="0" style="width:64px;padding:6px;border:1px solid #e6e6e6;border-radius:6px;"></td>
              <td style="padding:8px; text-align:center;"><?php echo htmlspecialchars(format_currency((float)$subtotal)); ?></td>
              <td style="padding:8px; text-align:center;">
                <button class="btn" type="button" onclick="removeItem('<?php echo htmlspecialchars($cartKey); ?>')" style="background:#999;">Remove</button>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        <div style="margin-top:12px; display:flex; justify-content:space-between; align-items:center;">
          <div>
            <button class="btn" type="submit">Update Cart</button>
            <button class="btn" type="button" onclick="clearAllCart()" style="margin-left:8px; background:#999;">Clear Cart</button>
          </div>
          <div style="font-weight:700;">Total: <?php echo htmlspecialchars(format_currency((float)$total)); ?></div>
        </div>
      </form>

      <section style="margin-top:20px; display:flex; gap:24px;">
        <div style="width:320px;">
          <h3>Order Summary</h3>
          <div style="background:#fff;padding:12px;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,0.04);">
            <?php 
            $totalItems = 0;
            foreach ($_SESSION['cart'] as $item) {
                if (is_array($item)) {
                    $totalItems += (int)($item['qty'] ?? 1);
                } else {
                    $totalItems += (int)$item;
                }
            }
            ?>
            <p class="muted">Items: <?php echo $totalItems; ?></p>
            <p class="muted">Subtotal: <?php echo htmlspecialchars(format_currency((float)$total)); ?></p>
            <?php if (!empty($_SESSION['user_id'])): ?>
            <a href="checkout.php" class="btn" style="display:block;width:100%;margin-top:12px;text-align:center;text-decoration:none;">Proceed to Checkout</a>
            <?php else: ?>
            <button class="btn" type="button" onclick="openCheckoutModal()" style="width:100%; margin-top:12px;">Proceed to Checkout</button>
            <?php endif; ?>
          </div>
        </div>
      </section>
    <?php endif; ?>

  </div>
</main>
<?php include __DIR__ . '/footer.php'; ?>

<!-- Checkout Modal -->
<div id="checkoutModal" class="modal">
  <div class="modal-content">
    <span class="modal-close" onclick="closeCheckoutModal()">&times;</span>
    <h2>Complete Your Order</h2>
    
    <!-- Order Summary with Sizes -->
    <div style="background:#f9f9f9; padding:12px; border-radius:6px; margin-bottom:16px;">
      <h4 style="margin-top:0;">Order Summary:</h4>
      <?php 
      $orderTotal = 0;
      foreach ($_SESSION['cart'] as $cartKey=>$item): 
        $id = is_array($item) ? $item['id'] : $cartKey;
        $qty = is_array($item) ? $item['qty'] : $item;
        $size = is_array($item) ? $item['size'] : '';
        if (!isset($products[$id])) continue; 
        $p=$products[$id]; 
        $subtotal=(float)$p['price']*$qty; 
        $orderTotal += $subtotal;
      ?>
        <div style="padding:8px; border-bottom:1px solid #e6e6e6; display:flex; justify-content:space-between;">
          <div>
            <strong><?php echo htmlspecialchars($p['title']); ?></strong>
            <?php if (!empty($size)): ?>
              <br><small style="color:#666;">Size: <?php echo htmlspecialchars($size); ?></small>
            <?php endif; ?>
          </div>
          <div style="text-align:right;">
            <div><?php echo htmlspecialchars(format_currency((float)$p['price'])); ?> × <?php echo $qty; ?> = <?php echo htmlspecialchars(format_currency((float)$subtotal)); ?></div>
          </div>
        </div>
      <?php endforeach; ?>
      <div style="padding:8px; font-weight:700; font-size:16px; text-align:right;">
        Total: <?php echo htmlspecialchars(format_currency((float)$orderTotal)); ?>
      </div>
    </div>
    
    <form method="post" action="cart.php" style="margin-top:14px;">
      <input type="hidden" name="action" value="checkout">
      
      <div style="margin-bottom:14px;">
        <h4>Delivery Information</h4>
        <input type="text" name="name" placeholder="Full Name" required style="width:100%;padding:10px;margin-bottom:8px;border:1px solid #e6e6e6;border-radius:6px;font-size:14px;">
        <input type="email" name="email" placeholder="Email Address" required style="width:100%;padding:10px;margin-bottom:8px;border:1px solid #e6e6e6;border-radius:6px;font-size:14px;">
        <input type="text" name="phone" placeholder="Phone Number (Optional)" style="width:100%;padding:10px;margin-bottom:8px;border:1px solid #e6e6e6;border-radius:6px;font-size:14px;">
        <textarea name="address" placeholder="Shipping Address" rows="4" required style="width:100%;padding:10px;margin-bottom:8px;border:1px solid #e6e6e6;border-radius:6px;font-size:14px;font-family:inherit;"></textarea>
        <input type="text" name="city" placeholder="City" required style="width:100%;padding:10px;margin-bottom:8px;border:1px solid #e6e6e6;border-radius:6px;font-size:14px;">
        <input type="text" name="postal" placeholder="Postal Code" required style="width:100%;padding:10px;margin-bottom:8px;border:1px solid #e6e6e6;border-radius:6px;font-size:14px;">
      </div>

      <div style="margin-bottom:14px;">
        <h4>Payment Method</h4>
        <div style="display:flex;flex-direction:column;gap:8px;">
          <label style="display:flex;align-items:center;gap:8px;"><input type="radio" name="payment_method" value="credit_card" required> Credit Card</label>
          <label style="display:flex;align-items:center;gap:8px;"><input type="radio" name="payment_method" value="paypal"> PayPal</label>
          <label style="display:flex;align-items:center;gap:8px;"><input type="radio" name="payment_method" value="bank_transfer"> Bank Transfer</label>
          <label style="display:flex;align-items:center;gap:8px;"><input type="radio" name="payment_method" value="cash_on_delivery"> Cash on Delivery</label>
        </div>
      </div>

      <button type="submit" class="btn" style="width:100%;">Place Order</button>
      <button type="button" class="btn" onclick="closeCheckoutModal()" style="width:100%; margin-top:8px; background:#999;">Cancel</button>
    </form>
  </div>
</div>

<style>
.modal {
  display: none;
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.4);
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fefefe;
  padding: 20px;
  border: 1px solid #888;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
}

.modal-close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
}

.modal-close:hover,
.modal-close:focus {
  color: black;
}
</style>

<script>
function removeItem(id) {
  const form = document.createElement('form');
  form.method = 'post';
  form.action = 'cart.php';
  form.innerHTML = '<input type="hidden" name="action" value="remove"><input type="hidden" name="id" value="' + id + '">';
  document.body.appendChild(form);
  form.submit();
}

function clearAllCart() {
  if (confirm('Are you sure you want to clear your entire cart?')) {
    const form = document.createElement('form');
    form.method = 'post';
    form.action = 'cart.php';
    form.innerHTML = '<input type="hidden" name="action" value="clear">';
    document.body.appendChild(form);
    form.submit();
  }
}

function openCheckoutModal() {
  document.getElementById('checkoutModal').style.display = 'flex';
}

function closeCheckoutModal() {
  document.getElementById('checkoutModal').style.display = 'none';
}

window.onclick = function(event) {
  const modal = document.getElementById('checkoutModal');
  if (event.target === modal) {
    modal.style.display = 'none';
  }
}
</script>

</body>
</html>
