<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_login('/WATCHING/pages/checkout.php');
include __DIR__ . '/../includes/header.php';

$cart = $_SESSION['cart'] ?? [];

if (isset($_GET['buy_now'])) {
  $pid = (int)$_GET['buy_now'];
  $cart = [$pid => 1];
}

function genOrderNumber() {
  return 'ORD-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid()), 0, 6));
}

$submitted = ($_SERVER['REQUEST_METHOD'] === 'POST');
$success = false; $error = null;
$total = 0; $items = [];
if (!empty($cart)) {
  $ids = implode(',', array_map('intval', array_keys($cart)));
  $res = db()->query("SELECT id, title, price, stock FROM products WHERE id IN ($ids)");
  while ($row = $res->fetch_assoc()) {
    $qty = $cart[$row['id']];
    $row['qty'] = $qty;
    $row['line_total'] = $qty * $row['price'];
    $total += $row['line_total'];
    $items[] = $row;
  }
}

if ($submitted && $items) {
  // Check stock availability before placing order
  foreach ($items as $it) {
    if ((int)$it['stock'] < (int)$it['qty']) {
      $error = 'Insufficient stock for: ' . htmlspecialchars($it['title']);
      $submitted = false;
      break;
    }
  }

  if ($submitted) {
    $payment_method = $_POST['payment_method'] === 'ONLINE' ? 'ONLINE' : 'COD';
    $order_number = genOrderNumber();

    $stmt = db()->prepare("
      INSERT INTO orders (
        order_number, payment_method, status, total,
        billing_first_name, billing_last_name, billing_company,
        billing_country, billing_address1, billing_address2,
        billing_city, billing_district, billing_zip,
        billing_phone, billing_email, ship_different,
        shipping_address1, shipping_address2, shipping_city, shipping_district, shipping_zip,
        order_notes
      ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
    ");

    // Explicit variables for bind_param (pass-by-reference friendly)
    $status = 'PENDING';
    $billing_first_name = $_POST['billing_first_name'] ?? '';
    $billing_last_name = $_POST['billing_last_name'] ?? '';
    $billing_company = $_POST['billing_company'] ?? '';
    $billing_country = $_POST['billing_country'] ?? '';
    $billing_address1 = $_POST['billing_address1'] ?? '';
    $billing_address2 = $_POST['billing_address2'] ?? '';
    $billing_city = $_POST['billing_city'] ?? '';
    $billing_district = $_POST['billing_district'] ?? '';
    $billing_zip = $_POST['billing_zip'] ?? '';
    $billing_phone = $_POST['billing_phone'] ?? '';
    $billing_email = $_POST['billing_email'] ?? '';
    $ship_different = isset($_POST['ship_different']) ? 1 : 0;
    $shipping_address1 = $_POST['shipping_address1'] ?? '';
    $shipping_address2 = $_POST['shipping_address2'] ?? '';
    $shipping_city = $_POST['shipping_city'] ?? '';
    $shipping_district = $_POST['shipping_district'] ?? '';
    $shipping_zip = $_POST['shipping_zip'] ?? '';
    $order_notes = $_POST['order_notes'] ?? '';

    // Types: sss d + 11 s + i + 6 s = 22 params
    $stmt->bind_param(
      "sssdsssssssssssissssss",
      $order_number, $payment_method, $status, $total,
      $billing_first_name, $billing_last_name, $billing_company,
      $billing_country, $billing_address1, $billing_address2,
      $billing_city, $billing_district, $billing_zip,
      $billing_phone, $billing_email, $ship_different,
      $shipping_address1, $shipping_address2, $shipping_city, $shipping_district, $shipping_zip,
      $order_notes
    );

    if ($stmt->execute()) {
      $order_id = $stmt->insert_id;
      $stmt->close();
  
      $itemStmt = db()->prepare("INSERT INTO order_items (order_id, product_id, qty, price) VALUES (?,?,?,?)");
      foreach ($items as $it) {
        $itemStmt->bind_param("iiid", $order_id, $it['id'], $it['qty'], $it['price']);
        $itemStmt->execute();
      }
      $itemStmt->close();
  
      // Decrement stock for ordered items
      $decStmt = db()->prepare("UPDATE products SET stock = stock - ? WHERE id = ?");
      foreach ($items as $it) {
        $decStmt->bind_param("ii", $it['qty'], $it['id']);
        $decStmt->execute();
      }
      $decStmt->close();
  
      if ($payment_method === 'ONLINE') {
        db()->query("UPDATE orders SET status='CONFIRMED' WHERE id=" . (int)$order_id);
      }
  
      $_SESSION['cart'] = [];
      $success = true;
    } else {
      $error = 'Failed to place order. Please try again.';
    }
  }
}
?>
<div class="container glass-card" style="padding: 16px;">
  <div class="section-title">
    <h2>Checkout</h2>
    <p>Billing details</p>
  </div>
  <?php if (!$items): ?>
    <div class="alert error">No items to checkout.</div>
  <?php elseif ($success): ?>
    <div class="alert success">Order placed successfully! You will receive confirmation soon.</div>
  <?php else: ?>
    <form method="post">
      <div class="form-grid">
        <div>
          <label>First name *</label>
          <input class="input" name="billing_first_name" required>
        </div>
        <div>
          <label>Last name *</label>
          <input class="input" name="billing_last_name" required>
        </div>
        <div class="full">
          <label>Company name (optional)</label>
          <input class="input" name="billing_company">
        </div>
        <div class="full">
          <label>Country / Region *</label>
          <select class="select" name="billing_country" required>
            <option>Bangladesh</option>
          </select>
        </div>
        <div class="full">
          <label>Street address *</label>
          <input class="input" name="billing_address1" placeholder="House number and street name" required>
        </div>
        <div class="full">
          <label>Apartment, suite, unit, etc. (optional)</label>
          <input class="input" name="billing_address2">
        </div>
        <div>
          <label>Town / City *</label>
          <input class="input" name="billing_city" required>
        </div>
        <div>
          <label>District *</label>
          <input class="input" name="billing_district" required>
        </div>
        <div>
          <label>Postcode / ZIP (optional)</label>
          <input class="input" name="billing_zip">
        </div>
        <div>
          <label>Phone *</label>
          <input class="input" name="billing_phone" required>
        </div>
        <div class="full">
          <label>Email address *</label>
          <input type="email" class="input" name="billing_email" required>
        </div>
        <div class="full">
          <label><input type="checkbox" name="ship_different" id="shipDiff"> Ship to a different address?</label>
        </div>
        <div class="full ship-fields" style="display:none;">
          <label>Shipping address</label>
          <input class="input" name="shipping_address1" placeholder="House number and street name">
          <input class="input" name="shipping_address2" placeholder="Apartment, suite, unit, etc.">
          <input class="input" name="shipping_city" placeholder="Town / City">
          <input class="input" name="shipping_district" placeholder="District">
          <input class="input" name="shipping_zip" placeholder="Postcode / ZIP">
        </div>
        <div class="full">
          <label>Order notes (optional)</label>
          <textarea class="textarea" name="order_notes"></textarea>
        </div>
        <div class="full">
          <label>Payment methods</label>
          <div style="display:grid;gap:8px;">
            <label><input type="radio" name="payment_method" value="COD" checked> Cash on delivery — Pay with cash upon delivery.</label>
            <label><input type="radio" name="payment_method" value="ONLINE"> Pay Online (Credit/Debit Card/MobileBanking/NetBanking/bKash)</label>
          </div>
        </div>
      </div>
      <div style="text-align:right;margin-top:12px;">
        <button class="btn" type="submit">Confirm Order</button>
      </div>
    </form>
    <script>
      const shipDiff = document.getElementById('shipDiff');
      const shipFields = document.querySelector('.ship-fields');
      shipDiff.addEventListener('change', () => {
        shipFields.style.display = shipDiff.checked ? 'grid' : 'none';
      });
    </script>
  <?php endif; ?>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>