<?php
require_once 'includes/bootstrap.php';
require_once 'includes/product-card.php';
$subtotal = cart_total($conn);
$zones = delivery_zones();
$selected_province = isset($_POST['province']) ? $_POST['province'] : 'mosul_right';
$delivery_fee = delivery_fee_for($selected_province);
if($_SERVER['REQUEST_METHOD']=='POST'){
  if($subtotal <= 0) redirect('cart.php?lang='.$lang);
  $name=mysqli_real_escape_string($conn,$_POST['name']);
  $phone=mysqli_real_escape_string($conn,$_POST['phone']);
  $province_key=mysqli_real_escape_string($conn,$_POST['province']);
  $province_label=mysqli_real_escape_string($conn,delivery_label($_POST['province'],$lang));
  $addr=mysqli_real_escape_string($conn,$_POST['address']);
  $map=mysqli_real_escape_string($conn,isset($_POST['map_link'])?$_POST['map_link']:'');
  $note=mysqli_real_escape_string($conn,$_POST['note']);
  $uid=isset($_SESSION['user_id'])?(int)$_SESSION['user_id']:0;
  $delivery_fee=delivery_fee_for($_POST['province']);
  $total=$subtotal+$delivery_fee;
  mysqli_query($conn,"INSERT INTO orders(user_id,customer_name,phone,city,province,address,map_link,subtotal,total,delivery_fee,note) VALUES($uid,'$name','$phone','$province_key','$province_label','$addr','$map',$subtotal,$total,$delivery_fee,'$note')");
  $oid=mysqli_insert_id($conn);
  if(isset($_SESSION['cart'])){
    foreach($_SESSION['cart'] as $pid=>$qty){
      $pid=(int)$pid; $qty=(int)$qty;
      $q=mysqli_query($conn,"SELECT * FROM products WHERE id=$pid");
      if($q && mysqli_num_rows($q)){
        $p=mysqli_fetch_assoc($q); $pn=mysqli_real_escape_string($conn,$p['name_en']); $price=product_final_price($p);
        mysqli_query($conn,"INSERT INTO order_items(order_id,product_id,product_name,qty,price) VALUES($oid,$pid,'$pn',$qty,$price)");
      }
    }
  }
  unset($_SESSION['cart']);
  redirect('thank-you.php?id='.$oid.'&lang='.$lang);
}
include 'includes/header.php';
?>
<main class="container checkout-page section">
  <form class="checkout-layout" method="post" id="checkoutForm">
    <div class="checkout-card">
      <h2><?php echo e(t('customer_info')); ?></h2>
      <input name="name" placeholder="<?php echo e(t('full_name')); ?>" required>
      <input name="phone" placeholder="<?php echo e(t('phone')); ?>" required>
      <select name="province" id="provinceSelect" required>
        <?php foreach($zones as $key=>$z): ?>
          <option value="<?php echo e($key); ?>" data-fee="<?php echo (float)$z['fee']; ?>" <?php echo $key==$selected_province?'selected':''; ?>><?php echo e(delivery_label($key,$lang)); ?> - <?php echo money_iqd($z['fee']); ?></option>
        <?php endforeach; ?>
      </select>
      <textarea name="address" placeholder="<?php echo e(t('address')); ?>" required></textarea>
      <input name="map_link" placeholder="<?php echo e(t('map_link')); ?> - https://maps.google.com/..." style="direction:ltr">
      <textarea name="note" placeholder="<?php echo e(t('note')); ?>"></textarea>
    </div>
    <aside class="checkout-summary">
      <h3><?php echo e(t('checkout')); ?></h3>
      <div class="summary-row"><span><?php echo e(t('subtotal')); ?></span><strong id="subtotalVal" data-value="<?php echo (float)$subtotal; ?>"><?php echo money_iqd($subtotal); ?></strong></div>
      <div class="summary-row"><span><?php echo e(t('delivery_fee')); ?></span><strong id="deliveryVal"><?php echo money_iqd($delivery_fee); ?></strong></div>
      <div class="summary-row grand"><span><?php echo e(t('grand_total')); ?></span><strong id="grandVal"><?php echo money_iqd($subtotal+$delivery_fee); ?></strong></div>
      <button class="primary-btn" <?php echo $subtotal<=0?'disabled':''; ?>><?php echo e(t('confirm_order')); ?></button>
      <?php if($subtotal<=0): ?><a href="cart.php?lang=<?php echo e($lang); ?>"><?php echo e(t('empty_cart')); ?></a><?php endif; ?>
    </aside>
  </form>
</main>
<script>
(function(){
  var select=document.getElementById('provinceSelect'), subtotal=document.getElementById('subtotalVal'), delivery=document.getElementById('deliveryVal'), grand=document.getElementById('grandVal');
  function fmt(n){ return Math.round(n).toLocaleString()+' <?php echo e(t('iqd')); ?>'; }
  function update(){ var fee=parseFloat(select.options[select.selectedIndex].getAttribute('data-fee')||0); var sub=parseFloat(subtotal.getAttribute('data-value')||0); delivery.textContent=fmt(fee); grand.textContent=fmt(sub+fee); }
  if(select) select.addEventListener('change',update);
})();
</script>
<?php include 'includes/footer.php'; ?>
