<?php
declare(strict_types=1);

require_once __DIR__ . '/lib/tenant.php';
require_once __DIR__ . '/lib/media.php';
require_once __DIR__ . '/lib/products.php';
require_once __DIR__ . '/lib/users.php';
require_once __DIR__ . '/lib/payments.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();
$paySettings = payment_settings($tenantId);
$methods = payment_available_methods($tenantId, 'retail');
$currency = strtoupper((string) ($paySettings['default_currency'] ?? 'USD'));

$items = cart_items($tenantId);
$totals = cart_totals($items);
$ps = db()->prepare('SELECT business_name, phone, address FROM page_settings WHERE tenant_id = ?');
$ps->execute([$tenantId]);
$page = $ps->fetch() ?: [];
$business = shop_company_name($page, $tenant);

$error = '';
$orderId = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (!$items) {
            throw new RuntimeException('Cart is empty.');
        }
        if (!$methods) {
            throw new RuntimeException('No payment methods enabled. Ask the shop to configure Payments in admin.');
        }
        $name = trim((string) ($_POST['customer_name'] ?? ''));
        $phone = trim((string) ($_POST['customer_phone'] ?? ''));
        $email = trim((string) ($_POST['customer_email'] ?? ''));
        $notes = trim((string) ($_POST['notes'] ?? ''));
        $method = trim((string) ($_POST['payment_method'] ?? 'manual'));
        $allowed = array_column($methods, 'id');
        if (!in_array($method, $allowed, true)) {
            throw new RuntimeException('Choose a valid payment method.');
        }
        if ($name === '') {
            throw new RuntimeException('Name is required.');
        }
        $user = user_upsert($tenantId, $name, $phone ?: null, $email ?: null);

        db()->beginTransaction();
        $orderStatus = $method === 'manual' ? 'pending_pickup' : 'awaiting_payment';
        $payStatus = $method === 'manual' ? 'pay_at_shop' : 'pending';
        db()->prepare(
            'INSERT INTO shop_orders (tenant_id, user_id, customer_name, customer_phone, customer_email, status, fulfillment, subtotal, total, notes, payment_status, payment_provider)
             VALUES (?,?,?,?,?,?,?,?,?,?,?,?)'
        )->execute([
            $tenantId,
            (int) $user['id'],
            $name,
            user_normalize_phone($phone),
            user_normalize_email($email),
            $orderStatus,
            'pickup',
            $totals['subtotal'],
            $totals['total'],
            $notes ?: null,
            $payStatus,
            $method,
        ]);
        $orderId = (int) db()->lastInsertId();
        $ins = db()->prepare(
            'INSERT INTO shop_order_items (order_id, product_id, product_name, unit_price, qty, line_total)
             VALUES (?,?,?,?,?,?)'
        );
        $stockUpd = db()->prepare('UPDATE products SET stock = stock - ? WHERE id = ? AND tenant_id = ? AND stock >= ?');
        foreach ($items as $i) {
            $qty = (int) $i['qty'];
            $stockUpd->execute([$qty, (int) $i['id'], $tenantId, $qty]);
            if ($stockUpd->rowCount() < 1) {
                throw new RuntimeException('Not enough stock for ' . $i['name']);
            }
            $ins->execute([
                $orderId,
                (int) $i['id'],
                $i['name'],
                (float) $i['price'],
                $qty,
                (float) $i['line_total'],
            ]);
        }

        $gw = payment_gateway($tenantId, $method);
        $baseReturn = '' . ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . APP_BASE . '/payments/return.php?tenant=' . urlencode($tenantParam);

        if ($method === 'manual') {
            $result = $gw->createCheckout([
                'amount' => (float) $totals['total'],
                'currency' => $currency,
                'description' => 'Order #' . $orderId . ' · ' . $business,
                'customer_email' => $email ?: null,
                'success_url' => $baseReturn,
                'cancel_url' => $baseReturn . '&cancel=1',
                'metadata' => ['reference_id' => (string) $orderId],
            ]);
            payment_create_record(
                $tenantId,
                $method,
                'retail_order',
                'shop_order',
                $orderId,
                (float) $totals['total'],
                $currency,
                $result
            );
            db()->commit();
            cart_clear();
            header('Location: ' . APP_BASE . '/checkout.php?tenant=' . urlencode($tenantParam) . '&done=' . $orderId);
            exit;
        }

        // Insert pending payment first so return URLs can carry payment_id.
        $paymentId = payment_create_record(
            $tenantId,
            $method,
            'retail_order',
            'shop_order',
            $orderId,
            (float) $totals['total'],
            $currency,
            ['status' => 'pending', 'external_id' => null, 'checkout_url' => null]
        );
        $successUrl = $baseReturn . '&payment_id=' . $paymentId;
        $cancelUrl = $successUrl . '&cancel=1';
        if ($method === 'stripe') {
            $successUrl .= '&session_id={CHECKOUT_SESSION_ID}';
        }
        $result = $gw->createCheckout([
            'amount' => (float) $totals['total'],
            'currency' => $currency,
            'description' => 'Order #' . $orderId . ' · ' . $business,
            'customer_email' => $email ?: null,
            'success_url' => $successUrl,
            'cancel_url' => $cancelUrl,
            'metadata' => [
                'reference_type' => 'shop_order',
                'reference_id' => (string) $orderId,
                'tenant_id' => (string) $tenantId,
                'payment_id' => (string) $paymentId,
            ],
        ]);
        db()->prepare(
            'UPDATE payments SET external_id = ?, checkout_url = ?, status = ?, meta_json = ? WHERE id = ? AND tenant_id = ?'
        )->execute([
            $result['external_id'] ?? null,
            $result['checkout_url'] ?? null,
            $result['status'] ?? 'pending',
            isset($result['raw']) ? json_encode($result['raw'], JSON_UNESCAPED_SLASHES) : null,
            $paymentId,
            $tenantId,
        ]);

        if (empty($result['checkout_url'])) {
            throw new RuntimeException('Payment provider did not return a checkout URL. Check API keys.');
        }
        db()->commit();
        cart_clear();
        header('Location: ' . (string) $result['checkout_url']);
        exit;
    } catch (Throwable $e) {
        if (db()->inTransaction()) {
            db()->rollBack();
        }
        $error = $e->getMessage();
        $items = cart_items($tenantId);
        $totals = cart_totals($items);
        $methods = payment_available_methods($tenantId, 'retail');
    }
}

$doneId = (int) ($_GET['done'] ?? 0);
$paid = isset($_GET['paid']);
$payCancel = isset($_GET['pay_cancel']);
$payPending = isset($_GET['pay_pending']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Checkout · <?= 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</a>
  </nav>
</header>

<section class="section">
  <?php if ($doneId): ?>
    <div class="section-head">
      <h2>Order #<?= $doneId ?> placed</h2>
      <?php if ($paid): ?>
        <p>Payment received. We’ll have it ready for Click &amp; Collect.</p>
      <?php elseif ($payCancel): ?>
        <p>Payment was cancelled. Your order may still be awaiting payment — contact the shop if needed.</p>
      <?php elseif ($payPending): ?>
        <p>Payment is still processing. You’ll get confirmation when it clears.</p>
      <?php else: ?>
        <p>We’ll have it ready for Click &amp; Collect. Pay at pickup unless you already paid online.</p>
      <?php endif; ?>
    </div>
    <p><a class="btn" href="<?= APP_BASE ?>/shop.php?tenant=<?= urlencode($tenantParam) ?>">Back to shop</a></p>
  <?php else: ?>
    <div class="section-head">
      <h2>Checkout</h2>
      <p>Pickup at <?= htmlspecialchars((string) ($page['address'] ?? $business)) ?><?= !empty($page['phone']) ? ' · ' . htmlspecialchars((string) $page['phone']) : '' ?></p>
    </div>
    <?php if ($error): ?><div class="book-flash err"><?= htmlspecialchars($error) ?></div><?php endif; ?>
    <?php if (!$items): ?>
      <p class="muted">Nothing to check out. <a href="<?= APP_BASE ?>/shop.php?tenant=<?= urlencode($tenantParam) ?>">Shop</a></p>
    <?php else: ?>
      <div class="checkout-grid">
        <form method="post" class="book-form">
          <label>Name</label>
          <input type="text" name="customer_name" required>
          <label>Phone</label>
          <input type="text" name="customer_phone" required>
          <label>Email</label>
          <input type="email" name="customer_email">
          <label>Notes (optional)</label>
          <textarea name="notes" placeholder="Pickup with my Saturday cut…"></textarea>
          <fieldset class="pay-methods">
            <legend>Payment</legend>
            <?php foreach ($methods as $i => $m): ?>
              <label class="pay-option">
                <input type="radio" name="payment_method" value="<?= htmlspecialchars($m['id']) ?>" <?= $i === 0 ? 'checked' : '' ?>>
                <span>
                  <strong><?= htmlspecialchars($m['label']) ?></strong>
                  <small><?= htmlspecialchars($m['hint']) ?></small>
                </span>
              </label>
            <?php endforeach; ?>
          </fieldset>
          <button class="btn" type="submit">Continue · $<?= number_format($totals['total'], 2) ?></button>
        </form>
        <div class="checkout-summary">
          <h3>Order summary</h3>
          <ul>
            <?php foreach ($items as $i): ?>
              <li><?= (int) $i['qty'] ?> × <?= htmlspecialchars($i['name']) ?> — $<?= number_format((float) $i['line_total'], 2) ?></li>
            <?php endforeach; ?>
          </ul>
          <strong>Total $<?= number_format($totals['total'], 2) ?></strong>
        </div>
      </div>
    <?php endif; ?>
  <?php endif; ?>
</section>
<footer class="site-footer sn-footer-only">
  <?php require_once __DIR__ . '/lib/sn_credit.php'; sn_credit_render(); ?>
</footer>
</body>
</html>
