<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\Cart; use App\Core\Database; use App\Core\OrderService; use App\Core\ShippingEngine;
$cart=Cart::summary(); if(!$cart['items']){set_flash('error','Your cart is empty.');redirect('public/cart.php');}
$user=current_user();$districts=Database::safeFetchAll('SELECT * FROM districts WHERE status="active" ORDER BY name');$areas=Database::safeFetchAll('SELECT * FROM areas WHERE status="active" ORDER BY name');$defaultQuote=ShippingEngine::quote((float)$cart['subtotal']);$errors=[];
if($_SERVER['REQUEST_METHOD']==='POST'){
 if(!verify_csrf())$errors[]='Invalid security token.';else try{$customer=$user?:['id'=>null,'name'=>$_POST['customer_name']??'','email'=>$_POST['customer_email']??'','phone'=>$_POST['customer_phone']??''];$oid=OrderService::create($customer,$cart,$_POST);Cart::clear();$gateway=(string)($_POST['payment_method']??'cod');if(in_array($gateway,['sslcommerz','bkash','nagad','partial'],true))redirect('payment/'.$gateway.'.php?order_id='.$oid);redirect('public/thank-you.php?order_id='.$oid);}catch(Throwable $e){$errors[]=$e->getMessage();}
}
$pageTitle='Checkout | '.BRAND_NAME;include ROOT_PATH.'/app/Layouts/frontend_header.php';
?>
<section class="container py-5"><h1 class="section-title mb-4">Checkout</h1><?php foreach($errors as $error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endforeach; ?><form method="post" class="row g-4"><?= csrf_field() ?><div class="col-lg-8"><div class="card border-0 shadow-sm"><div class="card-body"><h5>Customer & Delivery</h5><div class="row g-3"><div class="col-md-6"><label class="form-label">Name</label><input name="customer_name" class="form-control" value="<?= e($user['name']??$_POST['customer_name']??'') ?>" required></div><div class="col-md-6"><label class="form-label">Phone</label><input name="customer_phone" class="form-control" value="<?= e($user['phone']??$_POST['customer_phone']??'') ?>" required></div><div class="col-md-6"><label class="form-label">Email</label><input name="customer_email" type="email" class="form-control" value="<?= e($user['email']??$_POST['customer_email']??'') ?>"></div><div class="col-md-6"><label class="form-label">Payment</label><select name="payment_method" class="form-select"><option value="cod">Cash on Delivery</option><?php if($user): ?><option value="wallet">Purchase Wallet</option><?php endif; ?><?php if(PAYMENT_SANDBOX): ?><option value="sslcommerz">SSLCommerz (sandbox/pending)</option><option value="bkash">bKash (sandbox/pending)</option><option value="nagad">Nagad (sandbox/pending)</option><?php endif; ?></select></div><div class="col-md-6"><label class="form-label">District</label><select id="checkoutDistrict" name="district_id" class="form-select"><option value="">Select district</option><?php foreach($districts as $d): ?><option value="<?= (int)$d['id'] ?>"><?= e($d['name']) ?></option><?php endforeach; ?></select></div><div class="col-md-6"><label class="form-label">Area</label><select id="checkoutArea" name="area_id" class="form-select"><option value="">Select area</option><?php foreach($areas as $a): ?><option value="<?= (int)$a['id'] ?>" data-district="<?= (int)$a['district_id'] ?>"><?= e($a['name']) ?></option><?php endforeach; ?></select></div><div class="col-12"><label class="form-label">Address</label><textarea name="delivery_address" class="form-control" rows="3" required><?= e($_POST['delivery_address']??'') ?></textarea></div><div class="col-md-6"><label class="form-label">Coupon code</label><input name="coupon_code" class="form-control" value="<?= e($_POST['coupon_code']??'') ?>" placeholder="Optional"></div><div class="col-12"><label class="form-label">Order note</label><textarea name="order_note" class="form-control"><?= e($_POST['order_note']??'') ?></textarea></div></div></div></div></div><div class="col-lg-4"><div class="card border-0 shadow-sm"><div class="card-body"><h5>Summary</h5><?php foreach($cart['items'] as $item): ?><p class="d-flex justify-content-between small"><span><?= e($item['product']['name']) ?> × <?= (int)$item['qty'] ?></span><span><?= money($item['line_total']) ?></span></p><?php endforeach; ?><hr><p class="d-flex justify-content-between"><span>Subtotal</span><strong><?= money($cart['subtotal']) ?></strong></p><p class="d-flex justify-content-between"><span>Delivery</span><strong id="shippingAmount"><?= money($defaultQuote['shipping_charge']) ?></strong></p><hr><p class="d-flex justify-content-between fs-5"><span>Total</span><strong id="checkoutTotal"><?= money($defaultQuote['total']) ?></strong></p><button class="btn btn-primary w-100">Place Order</button></div></div></div></form></section>
<script>document.addEventListener('DOMContentLoaded',function(){const d=document.getElementById('checkoutDistrict'),a=document.getElementById('checkoutArea');function filter(){[...a.options].forEach((o,i)=>{if(i)o.hidden=d.value&&o.dataset.district!==d.value;});if(a.selectedOptions[0]?.hidden)a.value='';quote();}function quote(){fetch('<?= url('api/shipping-quote.php') ?>?subtotal=<?= (float)$cart['subtotal'] ?>&district_id='+encodeURIComponent(d.value)+'&area_id='+encodeURIComponent(a.value)).then(r=>r.json()).then(x=>{if(x.ok){document.getElementById('shippingAmount').textContent=x.formatted_shipping;document.getElementById('checkoutTotal').textContent=x.formatted_total;}});}d.addEventListener('change',filter);a.addEventListener('change',quote);filter();});</script>
<?php include ROOT_PATH.'/app/Layouts/frontend_footer.php'; ?>
