<?php
require_once __DIR__ . '/../config.php';
requireCustomer();
$items = cartItems();
if (!$items) redirect(SITE_URL . '/pages/cart.php');

$cust = currentCustomer();
$db   = getDB();
$custData = $db->prepare("SELECT * FROM customers WHERE id=?")->execute([$cust['id']]) ? $db->query("SELECT * FROM customers WHERE id={$cust['id']}")->fetch() : [];

$error = ''; $success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name   = trim($_POST['name']   ?? '');
    $phone  = trim($_POST['phone']  ?? '');
    $email  = trim($_POST['email']  ?? '');
    $addr   = trim($_POST['address']?? '');
    $city   = trim($_POST['city']   ?? '');
    $state  = trim($_POST['state']  ?? '');
    $pin    = trim($_POST['pincode']?? '');
    $pay    = $_POST['payment_method'] ?? 'cod';
    $notes  = trim($_POST['notes']  ?? '');

    if (!$name || !$phone || !$addr || !$city || !$state || !$pin) {
        $error = 'Please fill all required delivery fields.';
    } else {
        $subtotal = cartTotal();
        $shipping = $subtotal >= 5000 ? 0 : 299;
        $total    = $subtotal + $shipping;
        $order_no = 'BM-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid()),0,5));

        $db->prepare("INSERT INTO orders (order_no,customer_id,name,phone,email,address,city,state,pincode,subtotal,shipping,total,payment_method,notes) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
           ->execute([$order_no,$cust['id'],$name,$phone,$email,$addr,$city,$state,$pin,$subtotal,$shipping,$total,$pay,$notes]);
        $order_id = $db->lastInsertId();

        foreach ($items as $item) {
            $db->prepare("INSERT INTO order_items (order_id,product_id,product_name,product_image,price,qty,subtotal) VALUES (?,?,?,?,?,?,?)")
               ->execute([$order_id,$item['id'],$item['name'],$item['image'],$item['price'],$item['qty'],$item['price']*$item['qty']]);
        }
        cartClear();
        redirect(SITE_URL . '/pages/order_success.php?order=' . urlencode($order_no));
    }
}

$total    = cartTotal();
$shipping = $total >= 5000 ? 0 : 299;
$states   = ['Andhra Pradesh','Bihar','Delhi','Gujarat','Jharkhand','Karnataka','Madhya Pradesh','Maharashtra','Odisha','Punjab','Rajasthan','Tamil Nadu','Telangana','Uttar Pradesh','Uttarakhand','West Bengal','Other'];

$page_title = 'Checkout | Balimeen Private Limited';
include __DIR__ . '/../includes/header.php';
?>
<div class="page-hero" style="padding:40px 0;">
  <div class="container">
    <h1 style="font-size:1.8rem;">Checkout</h1>
    <div class="breadcrumb"><a href="<?= SITE_URL ?>">Home</a> → <a href="cart.php">Cart</a> → Checkout</div>
  </div>
</div>

<section class="section-pad-sm" style="background:var(--bg-light);">
  <div class="container">
    <?php if ($error): ?><div class="alert alert-error" style="margin-bottom:20px;"><?= h($error) ?></div><?php endif; ?>
    <form method="POST">
    <div class="checkout-grid">
      <!-- Left -->
      <div>
        <!-- Delivery -->
        <div class="checkout-section">
          <h3><span class="step-num">1</span> Delivery Details</h3>
          <div class="form-row">
            <div class="form-group"><label>Full Name *</label><input type="text" name="name" value="<?= h($_POST['name'] ?? $custData['name'] ?? '') ?>" required placeholder="Receiver's name"></div>
            <div class="form-group"><label>Phone Number *</label><input type="tel" name="phone" value="<?= h($_POST['phone'] ?? $custData['phone'] ?? '') ?>" required placeholder="+91 XXXXX XXXXX"></div>
          </div>
          <div class="form-group"><label>Email</label><input type="email" name="email" value="<?= h($_POST['email'] ?? $cust['email'] ?? '') ?>" placeholder="For order confirmation"></div>
          <div class="form-group"><label>Delivery Address *</label><textarea name="address" required rows="2" placeholder="House/Flat No, Street, Area, Landmark"><?= h($_POST['address'] ?? $custData['address'] ?? '') ?></textarea></div>
          <div class="form-row">
            <div class="form-group"><label>City *</label><input type="text" name="city" value="<?= h($_POST['city'] ?? $custData['city'] ?? '') ?>" required placeholder="City"></div>
            <div class="form-group"><label>State *</label>
              <select name="state" required>
                <option value="">Select State</option>
                <?php foreach ($states as $s): ?><option value="<?= h($s) ?>" <?= (($_POST['state']??$custData['state']??'')===$s)?'selected':'' ?>><?= h($s) ?></option><?php endforeach; ?>
              </select>
            </div>
          </div>
          <div class="form-row">
            <div class="form-group"><label>PIN Code *</label><input type="text" name="pincode" value="<?= h($_POST['pincode'] ?? $custData['pincode'] ?? '') ?>" required maxlength="6" placeholder="6-digit PIN"></div>
            <div class="form-group"><label>Order Notes (optional)</label><input type="text" name="notes" value="<?= h($_POST['notes']??'') ?>" placeholder="Special instructions"></div>
          </div>
        </div>

        <!-- Payment -->
        <div class="checkout-section">
          <h3><span class="step-num">2</span> Payment Method</h3>
          <div class="payment-options">
            <label class="payment-option"><input type="radio" name="payment_method" value="cod" checked><div class="pay-icon">💵</div><div><div class="pay-title">Cash on Delivery</div><div class="pay-sub">Pay when your order arrives</div></div></label>
            <label class="payment-option"><input type="radio" name="payment_method" value="bank_transfer"><div class="pay-icon">🏦</div><div><div class="pay-title">Bank Transfer / NEFT</div><div class="pay-sub">Transfer to our account – order confirmed after payment</div></div></label>
            <label class="payment-option"><input type="radio" name="payment_method" value="upi"><div class="pay-icon">📱</div><div><div class="pay-title">UPI Payment</div><div class="pay-sub">GPay, PhonePe, Paytm & more</div></div></label>
          </div>
        </div>
      </div>

      <!-- Order Summary -->
      <div class="order-summary-card">
        <h3 style="font-family:'Outfit',sans-serif;font-weight:700;color:var(--blue-dark);margin-bottom:16px;font-size:1rem;">Order Summary</h3>
        <?php foreach ($items as $item): ?>
        <div class="order-item-row">
          <img src="<?= SITE_URL ?>/assets/images/<?= h($item['image']) ?>" class="order-item-img" alt="">
          <div class="order-item-info"><div class="name"><?= h($item['name']) ?></div><div class="qty">Qty: <?= $item['qty'] ?></div></div>
          <div class="order-item-price"><?= rupee($item['price'] * $item['qty']) ?></div>
        </div>
        <?php endforeach; ?>
        <div class="summary-row" style="padding:10px 0;border-bottom:1px solid #f1f5f9;font-size:.88rem;">
          <span>Subtotal</span><span><?= rupee($total) ?></span>
        </div>
        <div class="summary-row" style="padding:8px 0;border-bottom:1px solid #f1f5f9;font-size:.88rem;">
          <span>Shipping</span><span><?= $shipping==0?'<span style="color:#10b981;font-weight:700;">FREE</span>':rupee($shipping) ?></span>
        </div>
        <div class="summary-row total" style="padding:12px 0;border-bottom:none;font-size:1.05rem;font-weight:800;">
          <span>Total</span><span style="color:var(--blue-main);"><?= rupee($total+$shipping) ?></span>
        </div>
        <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;margin-top:16px;font-size:1rem;padding:14px;">
          🛍️ Place Order
        </button>
        <p style="font-size:.76rem;color:#94a3b8;text-align:center;margin-top:10px;">Your order is safe with us. 100% secure checkout.</p>
      </div>
    </div>
    </form>
  </div>
</section>

<?php include __DIR__ . '/../includes/footer.php'; ?>
