<?php
declare(strict_types=1);

require_once __DIR__ . '/lib/tenant.php';
require_once __DIR__ . '/lib/media.php';
require_once __DIR__ . '/lib/products.php';

$tenant = resolve_tenant_from_host();
if (!$tenant) {
    http_response_code(404);
    echo 'Shop not found.';
    exit;
}
$tenantId = (int) $tenant['id'];
$fonts = font_pairing_css((string) $tenant['font_pairing']);
$tenantParam = tenant_param();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'update';
    if ($action === 'update') {
        foreach (($_POST['qty'] ?? []) as $pid => $qty) {
            cart_set((int) $pid, (int) $qty);
        }
    } elseif ($action === 'remove') {
        cart_set((int) ($_POST['product_id'] ?? 0), 0);
    }
    header('Location: ' . APP_BASE . '/cart.php?tenant=' . urlencode($tenantParam));
    exit;
}

$items = cart_items($tenantId);
$totals = cart_totals($items);
$ps = db()->prepare('SELECT business_name FROM page_settings WHERE tenant_id = ?');
$ps->execute([$tenantId]);
$business = shop_company_name($ps->fetch() ?: [], $tenant);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Cart · <?= htmlspecialchars($business) ?></title>
  <link href="<?= htmlspecialchars($fonts['import']) ?>" rel="stylesheet">
  <link rel="stylesheet" href="<?= APP_BASE ?>/assets/public.css">
  <link rel="stylesheet" href="<?= APP_BASE ?>/assets/shop.css">
  <style>:root{--primary:<?= htmlspecialchars((string)$tenant['primary_color']) ?>;--secondary:<?= htmlspecialchars((string)$tenant['secondary_color']) ?>;--font-heading:<?= $fonts['heading'] ?>;--font-body:<?= $fonts['body'] ?>;}</style>
</head>
<body>
<header class="site-header">
  <a class="logo" href="<?= APP_BASE ?>/?tenant=<?= urlencode($tenantParam) ?>"><?= htmlspecialchars($business) ?></a>
  <nav>
    <a href="<?= APP_BASE ?>/shop.php?tenant=<?= urlencode($tenantParam) ?>">Shop</a>
    <a href="<?= APP_BASE ?>/cart.php?tenant=<?= urlencode($tenantParam) ?>" class="nav-cta">Cart (<?= (int) $totals['count'] ?>)</a>
  </nav>
</header>

<section class="section">
  <div class="section-head">
    <h2>Your cart</h2>
    <p>Click &amp; Collect — pick up at the shop (online card pay comes with payments phase).</p>
  </div>

  <?php if (!$items): ?>
    <p class="muted">Cart is empty. <a href="<?= APP_BASE ?>/shop.php?tenant=<?= urlencode($tenantParam) ?>">Browse products</a></p>
  <?php else: ?>
    <form method="post">
      <input type="hidden" name="action" value="update">
      <table class="cart-table">
        <thead><tr><th></th><th>Product</th><th>Price</th><th>Qty</th><th>Total</th><th></th></tr></thead>
        <tbody>
          <?php foreach ($items as $i): ?>
            <tr>
              <td>
                <?php if ($i['image_url']): ?>
                  <img class="cart-thumb" src="<?= htmlspecialchars($i['image_url']) ?>" alt="">
                <?php endif; ?>
              </td>
              <td><?= htmlspecialchars($i['name']) ?></td>
              <td>$<?= number_format((float) $i['price'], 2) ?></td>
              <td><input type="number" name="qty[<?= (int) $i['id'] ?>]" min="0" max="<?= (int) $i['stock'] ?>" value="<?= (int) $i['qty'] ?>" style="width:4rem"></td>
              <td>$<?= number_format((float) $i['line_total'], 2) ?></td>
              <td>
                <button class="btn small ghost dark" form="rm-<?= (int) $i['id'] ?>" type="submit">Remove</button>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      <div class="cart-foot">
        <strong>Subtotal $<?= number_format($totals['subtotal'], 2) ?></strong>
        <div>
          <button class="btn ghost dark" type="submit">Update cart</button>
          <a class="btn" href="<?= APP_BASE ?>/checkout.php?tenant=<?= urlencode($tenantParam) ?>">Checkout</a>
        </div>
      </div>
    </form>
    <?php foreach ($items as $i): ?>
      <form id="rm-<?= (int) $i['id'] ?>" method="post" style="display:none">
        <input type="hidden" name="action" value="remove">
        <input type="hidden" name="product_id" value="<?= (int) $i['id'] ?>">
      </form>
    <?php endforeach; ?>
  <?php endif; ?>
</section>
<footer class="site-footer sn-footer-only">
  <?php require_once __DIR__ . '/lib/sn_credit.php'; sn_credit_render(); ?>
</footer>
</body>
</html>
