<?php
declare(strict_types=1);
session_start();
if (!isset($_SESSION['cart_by_user'])) $_SESSION['cart_by_user'] = [];
$userId = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
$items = isset($_SESSION['cart_by_user'][$userId]) ? array_values($_SESSION['cart_by_user'][$userId]) : [];

$dbHost = getenv('DB_HOST') ?: 'localhost';
$dbUser = getenv('DB_USER') ?: 'root';
$dbPass = getenv('DB_PASSWORD') ?: '';
$dbName = 'listbnb';

try {
    $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (Throwable $e) {
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Database connection failed.');window.location.href='cart.php';</script></body></html>";
    exit;
}

// Prefer database-backed cart for logged-in users; fallback to session
try {
    if ($userId > 0) {
        $pdo->exec('CREATE TABLE IF NOT EXISTS user_carts (user_id INT UNSIGNED NOT NULL, product_id INT UNSIGNED NOT NULL, qty INT UNSIGNED NOT NULL DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY uc_unique (user_id, product_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
        $stmt = $pdo->prepare('SELECT p.id, p.product_title, p.price, p.image1 FROM products p INNER JOIN user_carts uc ON uc.product_id=p.id WHERE uc.user_id=:u ORDER BY uc.created_at DESC');
        $stmt->execute([':u'=>$userId]);
        $itemsDb = $stmt->fetchAll();
        if ($itemsDb && is_array($itemsDb)) { $items = $itemsDb; }
    }
} catch (Throwable $e) {}

// If still empty on GET, redirect back to cart
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && empty($items)) {
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Cart is empty.');window.location.href='cart.php';</script></body></html>";
    exit;
}

try {
    $pdo->exec('CREATE TABLE IF NOT EXISTS orders (
        id INT AUTO_INCREMENT PRIMARY KEY,
        total DECIMAL(10,2) NOT NULL,
        status ENUM("pending","paid","cancelled") NOT NULL DEFAULT "pending",
        items_json TEXT,
        user_id INT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
    $pdo->exec('CREATE TABLE IF NOT EXISTS order_requests (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NULL,
        items_json TEXT,
        total DECIMAL(10,2) NOT NULL,
        shipping_method VARCHAR(50) NOT NULL,
        shipping_charge DECIMAL(10,2) NOT NULL,
        discount_code VARCHAR(100) NULL,
        discount_amount DECIMAL(10,2) NOT NULL DEFAULT 0,
        grand_total DECIMAL(10,2) NOT NULL,
        contact VARCHAR(190) NOT NULL,
        contact_marketing TINYINT(1) NOT NULL DEFAULT 0,
        area VARCHAR(120) NOT NULL,
        first_name VARCHAR(120) NOT NULL,
        last_name VARCHAR(120) NOT NULL,
        address VARCHAR(255) NOT NULL,
        apartment VARCHAR(120) NULL,
        city VARCHAR(120) NOT NULL,
        postal_code VARCHAR(40) NULL,
        phone VARCHAR(60) NOT NULL,
        billing_same TINYINT(1) NOT NULL DEFAULT 1,
        billing_area VARCHAR(120) NULL,
        billing_first_name VARCHAR(120) NULL,
        billing_last_name VARCHAR(120) NULL,
        billing_address VARCHAR(255) NULL,
        billing_apartment VARCHAR(120) NULL,
        billing_city VARCHAR(120) NULL,
        billing_postal_code VARCHAR(40) NULL,
        billing_phone VARCHAR(60) NULL,
        payment_method VARCHAR(50) NOT NULL,
        payment_image_path VARCHAR(255) NULL,
        status ENUM("pending","approved","rejected") NOT NULL DEFAULT "pending",
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}

$total = 0.0;
foreach ($items as $it) { $total += (float)($it['price'] ?? 0); }
$shipping = 199.0;
$discount = 0.0;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $dc = isset($_POST['discount_code']) ? (string)$_POST['discount_code'] : '';
  $da = isset($_POST['discount_amount']) ? (float)$_POST['discount_amount'] : 0.0;
  if ($dc !== '' && $da > 0) { $discount = max(0.0, min($da, $total)); }
}
$grand = max(0.0, $total + $shipping - $discount);
$userId = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : null;
$itemsJson = json_encode($items, JSON_UNESCAPED_SLASHES);
$orderId = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    function saveUpload($key){
        if (!isset($_FILES[$key]) || !is_uploaded_file($_FILES[$key]['tmp_name'])) return null;
        $name = preg_replace('/[^A-Za-z0-9._-]/','_', $_FILES[$key]['name']);
        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        if (!in_array($ext,['jpg','jpeg','png','gif','webp'])) return null;
        $dir = __DIR__ . '/uploads';
        if (!is_dir($dir)) @mkdir($dir, 0777, true);
        $target = $dir . '/' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
        if (move_uploaded_file($_FILES[$key]['tmp_name'], $target)) return 'uploads/' . basename($target);
        return null;
    }
    $contact = isset($_POST['contact']) ? (string)$_POST['contact'] : '';
    $contactMarketing = isset($_POST['contact_marketing']) ? 1 : 0;
    $area = isset($_POST['area']) ? (string)$_POST['area'] : '';
    $firstName = isset($_POST['first_name']) ? (string)$_POST['first_name'] : '';
    $lastName = isset($_POST['last_name']) ? (string)$_POST['last_name'] : '';
    $address = isset($_POST['address']) ? (string)$_POST['address'] : '';
    $apartment = isset($_POST['apartment']) ? (string)$_POST['apartment'] : '';
    $city = isset($_POST['city']) ? (string)$_POST['city'] : '';
    $postalCode = isset($_POST['postal_code']) ? (string)$_POST['postal_code'] : '';
    $phone = isset($_POST['phone']) ? (string)$_POST['phone'] : '';
    $shippingMethod = isset($_POST['shipping_method']) ? (string)$_POST['shipping_method'] : 'standard';
    $paymentMethod = isset($_POST['payment']) ? (string)$_POST['payment'] : 'cod';
    $billingSame = isset($_POST['billing_same']) && $_POST['billing_same'] === 'no' ? 0 : 1;
    $bArea = isset($_POST['billing_area']) ? (string)$_POST['billing_area'] : null;
    $bFirstName = isset($_POST['billing_first_name']) ? (string)$_POST['billing_first_name'] : null;
    $bLastName = isset($_POST['billing_last_name']) ? (string)$_POST['billing_last_name'] : null;
    $bAddress = isset($_POST['billing_address']) ? (string)$_POST['billing_address'] : null;
    $bApartment = isset($_POST['billing_apartment']) ? (string)$_POST['billing_apartment'] : null;
    $bCity = isset($_POST['billing_city']) ? (string)$_POST['billing_city'] : null;
    $bPostalCode = isset($_POST['billing_postal_code']) ? (string)$_POST['billing_postal_code'] : null;
    $bPhone = isset($_POST['billing_phone']) ? (string)$_POST['billing_phone'] : null;
    $dc = isset($_POST['discount_code']) ? (string)$_POST['discount_code'] : '';
    $da = isset($_POST['discount_amount']) ? (float)$_POST['discount_amount'] : 0.0;
    $payImg = null;
    if ($paymentMethod === 'cod') $payImg = saveUpload('cod_image');
    elseif ($paymentMethod === 'bank') $payImg = saveUpload('bank_image');
    elseif ($paymentMethod === 'easypaisa') $payImg = saveUpload('easypaisa_image');
    elseif ($paymentMethod === 'jazzcash') $payImg = saveUpload('jazzcash_image');
    try {
        $stmt = $pdo->prepare('INSERT INTO order_requests(
            user_id, items_json, total, shipping_method, shipping_charge, discount_code, discount_amount, grand_total,
            contact, contact_marketing, area, first_name, last_name, address, apartment, city, postal_code, phone,
            billing_same, billing_area, billing_first_name, billing_last_name, billing_address, billing_apartment, billing_city, billing_postal_code, billing_phone,
            payment_method, payment_image_path, status
        ) VALUES(
            :u, :j, :t, :sm, :sc, :dc, :da, :gt,
            :c, :cm, :ar, :fn, :ln, :ad, :ap, :ct, :pc, :ph,
            :bs, :bar, :bfn, :bln, :bad, :bap, :bct, :bpc, :bph,
            :pm, :pimg, :st
        )');
        $stmt->execute([
            ':u'=>$userId, ':j'=>$itemsJson, ':t'=>$total, ':sm'=>$shippingMethod, ':sc'=>$shipping, ':dc'=>$dc, ':da'=>$da, ':gt'=>$grand,
            ':c'=>$contact, ':cm'=>$contactMarketing, ':ar'=>$area, ':fn'=>$firstName, ':ln'=>$lastName, ':ad'=>$address, ':ap'=>$apartment, ':ct'=>$city, ':pc'=>$postalCode, ':ph'=>$phone,
            ':bs'=>$billingSame, ':bar'=>$bArea, ':bfn'=>$bFirstName, ':bln'=>$bLastName, ':bad'=>$bAddress, ':bap'=>$bApartment, ':bct'=>$bCity, ':bpc'=>$bPostalCode, ':bph'=>$bPhone,
            ':pm'=>$paymentMethod, ':pimg'=>$payImg, ':st'=>'pending'
        ]);
        $orderId = (int)$pdo->lastInsertId();
        if (isset($_SESSION['cart_by_user'][$userId])) { $_SESSION['cart_by_user'][$userId] = []; }
        try {
            $pdo->exec('CREATE TABLE IF NOT EXISTS user_carts (user_id INT UNSIGNED NOT NULL, product_id INT UNSIGNED NOT NULL, qty INT UNSIGNED NOT NULL DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY uc_unique (user_id, product_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
            $del = $pdo->prepare('DELETE FROM user_carts WHERE user_id = :u');
            $del->execute([':u' => (int)$userId]);
        } catch (Throwable $e) {}
    } catch (Throwable $e) {
        echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Failed to place order.');window.location.href='cart.php';</script></body></html>";
        exit;
    }
}
?>
<!doctype html>
<html class="no-js" lang="zxx">
<head>
   <meta charset="utf-8">
   <meta http-equiv="x-ua-compatible" content="ie=edge">
   <title>Checkout - ListBnb</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">

   <link rel="shortcut icon" type="image/x-icon" href="assets/img/logo/favicon.png">
   <link rel="stylesheet" href="assets/css/bootstrap.css">
   <link rel="stylesheet" href="assets/css/animate.css">
   <link rel="stylesheet" href="assets/css/swiper-bundle.css">
   <link rel="stylesheet" href="assets/css/slick.css">
   <link rel="stylesheet" href="assets/css/magnific-popup.css">
   <link rel="stylesheet" href="assets/css/font-awesome-pro.css">
   <link rel="stylesheet" href="assets/css/spacing.css">
   <link rel="stylesheet" href="assets/css/custom-animation.css">
   <link rel="stylesheet" href="assets/css/main.css">
   <style>
    :root {
      --primary: #ff9fc4; /* baby pink */
      --primary-light: #ffd6e7; /* light baby pink */
      --primary-dark: #e36fa1;
       --success: #10b981;
       --danger: #ef4444;
       --warning: #f59e0b;
       --dark: #1f2937;
       --light: #f9fafb;
       --lighter: #f3f4f6;
       --border: #e5e7eb;
       --text: #374151;
       --text-light: #6b7280;
       --radius: 10px;
       --shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
       --transition: all 0.2s ease;
     }
     
     body {
       background-color: #f8fafc;
       color: var(--text);
       font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
       line-height: 1.5;
     }
     
    .checkout-hero {
      background: linear-gradient(135deg, #eef1f5 0%, #ffbfd6 50%, var(--primary) 100%);
      padding: 1rem 0;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      border-bottom: 1px solid #e6e9ee;
      margin-bottom: 24px;
    }
    .checkout-hero a { color:#1f2937 !important; font-size:1.25rem !important; display:inline-flex; align-items:center; justify-content:center; width:36px; height:36px; border-radius:999px; background:#ffffffcc; border:1px solid #e6e9ee; }
    .checkout-hero a:hover{ background:#fff; }
     
    .checkout-title {
      color: #1f2937;
      font-size: 1.875rem;
      font-weight: 800;
      margin: 0;
      position: relative;
      display: inline-block;
    }
     
    .checkout-title:after {
      content: '';
      position: absolute;
      left: 0;
      bottom: -8px;
      width: 50px;
      height: 4px;
      background: var(--primary);
      border-radius: 2px;
    }
     
     .co-layout {
       display: grid;
       grid-template-columns: 1fr 400px;
       gap: 2rem;
       max-width: 1400px;
       margin: 0 auto;
       padding: 0 1rem;
     }
     
     @media (max-width: 992px) {
       .co-layout {
         grid-template-columns: 1fr;
         max-width: 800px;
       }
     }
     
    .panel {
      background: white;
      border-radius: var(--radius);
      box-shadow: var(--shadow);
      border: 1px solid #e6e9ee; /* soft gray border */
      overflow: hidden;
      margin-bottom: 1.5rem;
      transition: var(--transition);
    }
     
     .panel:hover {
       box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
     }
     
     .panel .box {
       padding: 1.5rem;
     }
     
     .panel h4 {
       font-size: 1.125rem;
       font-weight: 700;
       color: var(--dark);
       margin: 0 0 1.25rem;
       padding-bottom: 0.75rem;
       border-bottom: 1px solid var(--border);
       position: relative;
     }
     
     .panel h4:after {
       content: '';
       position: absolute;
       left: 0;
       bottom: -1px;
       width: 40px;
       height: 2px;
       background: var(--primary);
     }
     
     .field {
       margin-bottom: 1rem;
     }
     
     .field label {
       display: block;
       font-size: 0.875rem;
       font-weight: 500;
       color: var(--text);
       margin-bottom: 0.5rem;
     }
     
     .field input[type="text"],
     .field input[type="email"],
     .field input[type="tel"],
     .field input[type="number"],
     .field select,
     .field textarea {
       width: 100%;
       height: 44px;
       padding: 0.5rem 1rem;
       border: 1px solid var(--border);
       border-radius: var(--radius);
       font-size: 0.9375rem;
       transition: var(--transition);
       background-color: white;
     }
     
    .field input:focus,
    .field select:focus,
    .field textarea:focus {
      outline: none;
      border-color: #4f46e5;
      box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.15);
    }
     
     .field textarea {
       min-height: 100px;
       resize: vertical;
     }
     
     .grid-2 {
       display: grid;
       grid-template-columns: 1fr 1fr;
       gap: 1rem;
     }
     
     .grid-3 {
       display: grid;
       grid-template-columns: 2fr 1fr 1fr;
       gap: 1rem;
     }
     
     @media (max-width: 640px) {
       .grid-2,
       .grid-3 {
         grid-template-columns: 1fr;
       }
     }
     
     .check {
       display: flex;
       align-items: center;
       gap: 0.75rem;
       margin: 0.5rem 0;
       cursor: pointer;
       font-size: 0.9375rem;
       color: var(--text);
     }
     
    .check input[type="checkbox"],
    .check input[type="radio"] {
      width: 18px;
      height: 18px;
      accent-color: #4f46e5;
    }
     
     .radio {
       display: flex;
       align-items: center;
       gap: 0.75rem;
       padding: 1rem 1.25rem;
       border: 1px solid var(--border);
       border-radius: var(--radius);
       margin-bottom: 0.75rem;
       cursor: pointer;
       transition: var(--transition);
       position: relative;
     }
     
    .radio:hover {
      border-color: #4f46e5;
      background-color: #eef2ff;
    }
     
    .radio input[type="radio"] {
      width: 18px;
      height: 18px;
      accent-color: #4f46e5;
    }
     
    .summary {
      background: #f5f6f8; /* soft gray card */
      border: 1px solid #e6e9ee;
      border-radius: var(--radius);
      box-shadow: var(--shadow);
      padding: 1.5rem;
      position: sticky;
      top: 1.5rem;
    }
     
     .sum-item {
       display: grid;
       grid-template-columns: 60px 1fr auto;
       gap: 0.875rem;
       align-items: center;
       padding: 0.75rem 0;
       border-bottom: 1px solid var(--border);
     }
     
     .sum-item:last-child {
       border-bottom: none;
     }
     
     .sum-thumb {
       width: 60px;
       height: 60px;
       border-radius: 8px;
       object-fit: cover;
       border: 1px solid var(--border);
       background: white;
     }
     
     .sum-title {
       font-weight: 600;
       font-size: 0.9375rem;
       margin: 0 0 0.25rem;
       color: var(--dark);
     }
     
     .sum-meta {
       font-size: 0.8125rem;
       color: var(--text-light);
       margin: 0;
     }
     
     .sum-price {
       font-weight: 600;
       color: var(--dark);
     }
     
     .sum-line {
       display: flex;
       justify-content: space-between;
       margin: 0.5rem 0;
       font-size: 0.9375rem;
       color: var(--text);
     }
     
     .sum-total {
       display: flex;
       justify-content: space-between;
       align-items: center;
       margin-top: 1rem;
       padding-top: 1rem;
       border-top: 2px solid var(--border);
       font-weight: 800;
       font-size: 1.125rem;
       color: var(--dark);
     }
     
     .btn {
       display: inline-flex;
       align-items: center;
       justify-content: center;
       height: 48px;
       padding: 0 1.5rem;
       border-radius: var(--radius);
       font-weight: 600;
       font-size: 1rem;
       line-height: 1.5;
       text-align: center;
       white-space: nowrap;
       transition: var(--transition);
       cursor: pointer;
       border: 1px solid transparent;
       width: 100%;
     }
     
     .btn-primary {
       background-color: var(--primary);
       color: white;
       border-color: var(--primary);
     }
     
     .btn-primary:hover {
       background-color: var(--primary-dark);
       border-color: var(--primary-dark);
       transform: translateY(-2px);
       box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
     }
     
     .btn-outline {
       background-color: white;
       border: 1px solid var(--border);
       color: var(--text);
     }
     
     .btn-outline:hover {
       background-color: var(--lighter);
       border-color: var(--border);
       transform: translateY(-2px);
     }
     
     .btn[disabled] {
       opacity: 0.6;
       cursor: not-allowed;
       transform: none !important;
       box-shadow: none !important;
     }
     
     /* Payment method details */
     #cod_details,
     #bank_details,
     #easypaisa_details,
     #jazzcash_details {
       background: var(--lighter);
       border: 1px solid var(--border);
       border-radius: var(--radius);
       padding: 1rem;
       margin-top: 1rem;
       font-size: 0.875rem;
       line-height: 1.5;
     }
     
     #cod_details div,
     #bank_details div,
     #easypaisa_details div,
     #jazzcash_details div {
       margin-bottom: 0.5rem;
     }
     
     #cod_details div:last-child,
     #bank_details div:last-child,
     #easypaisa_details div:last-child,
     #jazzcash_details div:last-child {
       margin-bottom: 0;
     }
     
     /* Responsive adjustments */
     @media (max-width: 768px) {
       .checkout-hero {
         padding: 1.5rem 0;
       }
       
       .checkout-title {
         font-size: 1.5rem;
       }
       
       .panel .box {
         padding: 1.25rem;
       }
       
       .summary {
         position: static;
         margin-top: 2rem;
       }
     }
   </style>
<?php if ($_SERVER['REQUEST_METHOD'] !== 'POST'): ?>
</head>
<body>

   <main>
      <section class="checkout-hero">
        <div class="container" style="display: flex; align-items: center; gap: 15px;">
          <a href="cart.php" style="color: white; font-size: 1.5rem; text-decoration: none; display: flex; align-items: center;">
            <i class="fa fa-arrow-left"></i>
          </a>
          <h1 class="checkout-title" style="margin: 0;">Checkout</h1>
        </div>
      </section>
      <section class="pb-120 pt-10">
        <div class="container">
          <div class="co-layout">
            <div>
              <form action="checkout.php" method="post" id="checkout-form" enctype="multipart/form-data">
                <div class="panel">
                  <div class="box">
                    <h4>Contact</h4>
                    <div class="field"><input type="text" name="contact" placeholder="Email or mobile phone number" required></div>
                    <label class="check"><input type="checkbox" name="contact_marketing" checked> <span>Email me with news and offers</span></label>
                  </div>
                </div>
                <div class="panel mt-20">
                  <div class="box">
                    <h4>Delivery</h4>
                    <div class="field"><select name="area" required>
                      <option value="DHA">DHA (Defence)</option>
                      <option value="Gulberg">Gulberg</option>
                      <option value="Model Town">Model Town</option>
                      <option value="Johar Town">Johar Town</option>
                      <option value="Garden Town">Garden Town</option>
                      <option value="Faisal Town">Faisal Town</option>
                      <option value="Township">Township</option>
                      <option value="Wapda Town">Wapda Town</option>
                      <option value="Bahria Town">Bahria Town</option>
                      <option value="Cantt">Cantt</option>
                      <option value="Shadman">Shadman</option>
                      <option value="Allama Iqbal Town">Allama Iqbal Town</option>
                      <option value="Samanabad">Samanabad</option>
                      <option value="Gulshan-e-Ravi">Gulshan-e-Ravi</option>
                      <option value="Sabzazar">Sabzazar</option>
                      <option value="Mughalpura">Mughalpura</option>
                      <option value="Harbanspura">Harbanspura</option>
                      <option value="Cavalry Ground">Cavalry Ground</option>
                      <option value="Walton">Walton</option>
                      <option value="Nishat Colony">Nishat Colony</option>
                      <option value="Shahdara">Shahdara</option>
                      <option value="Ravi Road">Ravi Road</option>
                      <option value="Upper Mall">Upper Mall</option>
                      <option value="Canal View">Canal View</option>
                      <option value="Paragon City">Paragon City</option>
                      <option value="Askari">Askari</option>
                      <option value="Valencia Town">Valencia Town</option>
                      <option value="Lake City">Lake City</option>
                      <option value="Bahria Orchard">Bahria Orchard</option>
                      <option value="Airline Society">Airline Society</option>
                      <option value="State Life Society">State Life Society</option>
                      <option value="PCSIR">PCSIR</option>
                      <option value="Green Town">Green Town</option>
                      <option value="Ichhra">Ichhra</option>
                      <option value="Mozang">Mozang</option>
                      <option value="Badami Bagh">Badami Bagh</option>
                      <option value="Anarkali">Anarkali</option>
                      <option value="Kot Lakhpat">Kot Lakhpat</option>
                      <option value="Raiwind Road">Raiwind Road</option>
                      <option value="Multan Road">Multan Road</option>
                      <option value="Ferozepur Road">Ferozepur Road</option>
                      <option value="Other" selected>Other</option>
                    </select></div>
                    <div class="grid-2">
                      <div class="field"><input type="text" name="first_name" placeholder="First name" required></div>
                      <div class="field"><input type="text" name="last_name" placeholder="Last name" required></div>
                    </div>
                    <div class="field"><input type="text" name="address" placeholder="Address" required></div>
                    <div class="field"><input type="text" name="apartment" placeholder="Apartment, suite, etc. (optional)"></div>
                    <div class="grid-2">
                      <div class="field"><input type="text" name="city" placeholder="City" required></div>
                      <div class="field"><input type="text" name="postal_code" placeholder="Postal code (optional)"></div>
                    </div>
                    <div class="field"><input type="text" name="phone" placeholder="Phone" required></div>
                  </div>
                </div>
                <div class="panel mt-20">
                  <div class="box">
                    <h4>Shipping method</h4>
                    <label class="radio"><input type="radio" name="shipping_method" value="standard" checked> <span>Standard Shipping</span> <span style="margin-left:auto">Rs <?php echo number_format($shipping,2); ?></span></label>
                  </div>
                </div>
                <div class="panel mt-20">
                  <div class="box">
                    <h4>Payment</h4>
                    <div class="radio"><input type="radio" name="payment" value="cod" checked> <span>Cash on Delivery (COD)</span></div>
                    <div class="radio"><input type="radio" name="payment" value="bank"> <span>Bank Deposit</span></div>
                    <div class="radio"><input type="radio" name="payment" value="easypaisa"> <span>Easypaisa</span></div>
                    <div class="radio"><input type="radio" name="payment" value="jazzcash"> <span>JazzCash</span></div>
                    <div id="cod_details" style="display:none;margin-top:10px;background:#f7f7f8;border:1px solid #e5e7eb;border-radius:10px;padding:12px">
                      <div>Delivery charges: Rs 250</div>
                      <div class="field" style="margin-top:10px"><input type="file" name="cod_image" accept="image/*"></div>
                    </div>
                    <div id="bank_details" style="display:none;margin-top:10px;background:#f7f7f8;border:1px solid #e5e7eb;border-radius:10px;padding:12px">
                      <div>Bank: Meezan Bank</div>
                      <div>Account Title: FLOSSIE INTERNATIONAL</div>
                      <div>Account number: 0282 0113457447</div>
                      <div>IBAN: PK40 MEZN 0002 8201 1345 7447</div>
                      <div class="field" style="margin-top:10px"><input type="file" name="bank_image" accept="image/*"></div>
                    </div>
                    <div id="easypaisa_details" style="display:none;margin-top:10px;background:#f7f7f8;border:1px solid #e5e7eb;border-radius:10px;padding:12px">
                      <div>Account Name: FLOSSIE INTERNATIONAL</div>
                      <div>Account number: 03004231556</div>
                      <div class="field" style="margin-top:10px"><input type="file" name="easypaisa_image" accept="image/*"></div>
                    </div>
                    <div id="jazzcash_details" style="display:none;margin-top:10px;background:#f7f7f8;border:1px solid #e5e7eb;border-radius:10px;padding:12px">
                      <div>Account Name: FLOSSIE INTERNATIONAL</div>
                      <div>Account number: 03004231556</div>
                      <div class="field" style="margin-top:10px"><input type="file" name="jazzcash_image" accept="image/*"></div>
                    </div>
                  </div>
                </div>
                <div class="panel mt-20">
                  <div class="box">
                    <h4>Billing address</h4>
                    <div class="radio"><input type="radio" name="billing_same" value="yes" checked> <span>Same as shipping address</span></div>
                    <div class="radio"><input type="radio" name="billing_same" value="no"> <span>Use a different billing address</span></div>
                    <div id="billing_alt" style="display:none;margin-top:10px">
                      <div class="field"><select name="billing_area">
                        <option value="DHA">DHA (Defence)</option>
                        <option value="Gulberg">Gulberg</option>
                        <option value="Model Town">Model Town</option>
                        <option value="Johar Town">Johar Town</option>
                        <option value="Garden Town">Garden Town</option>
                        <option value="Faisal Town">Faisal Town</option>
                        <option value="Township">Township</option>
                        <option value="Wapda Town">Wapda Town</option>
                        <option value="Bahria Town">Bahria Town</option>
                        <option value="Cantt">Cantt</option>
                        <option value="Shadman">Shadman</option>
                        <option value="Allama Iqbal Town">Allama Iqbal Town</option>
                        <option value="Samanabad">Samanabad</option>
                        <option value="Gulshan-e-Ravi">Gulshan-e-Ravi</option>
                        <option value="Sabzazar">Sabzazar</option>
                        <option value="Mughalpura">Mughalpura</option>
                        <option value="Harbanspura">Harbanspura</option>
                        <option value="Cavalry Ground">Cavalry Ground</option>
                        <option value="Walton">Walton</option>
                        <option value="Nishat Colony">Nishat Colony</option>
                        <option value="Shahdara">Shahdara</option>
                        <option value="Ravi Road">Ravi Road</option>
                        <option value="Upper Mall">Upper Mall</option>
                        <option value="Canal View">Canal View</option>
                        <option value="Paragon City">Paragon City</option>
                        <option value="Askari">Askari</option>
                        <option value="Valencia Town">Valencia Town</option>
                        <option value="Lake City">Lake City</option>
                        <option value="Bahria Orchard">Bahria Orchard</option>
                        <option value="Airline Society">Airline Society</option>
                        <option value="State Life Society">State Life Society</option>
                        <option value="PCSIR">PCSIR</option>
                        <option value="Green Town">Green Town</option>
                        <option value="Ichhra">Ichhra</option>
                        <option value="Mozang">Mozang</option>
                        <option value="Badami Bagh">Badami Bagh</option>
                        <option value="Anarkali">Anarkali</option>
                        <option value="Kot Lakhpat">Kot Lakhpat</option>
                        <option value="Raiwind Road">Raiwind Road</option>
                        <option value="Multan Road">Multan Road</option>
                        <option value="Ferozepur Road">Ferozepur Road</option>
                        <option value="Other" selected>Other</option>
                      </select></div>
                      <div class="grid-2">
                        <div class="field"><input type="text" name="billing_first_name" placeholder="First name"></div>
                        <div class="field"><input type="text" name="billing_last_name" placeholder="Last name"></div>
                      </div>
                      <div class="field"><input type="text" name="billing_address" placeholder="Address"></div>
                      <div class="field"><input type="text" name="billing_apartment" placeholder="Apartment, suite, etc. (optional)"></div>
                      <div class="grid-2">
                        <div class="field"><input type="text" name="billing_city" placeholder="City"></div>
                        <div class="field"><input type="text" name="billing_postal_code" placeholder="Postal code (optional)"></div>
                      </div>
                      <div class="field"><input type="text" name="billing_phone" placeholder="Phone (optional)"></div>
                    </div>
                    <input type="hidden" name="discount_code" id="discount_code_input">
                    <input type="hidden" name="discount_amount" id="discount_amount_input" value="0">
                    <button class="btn" type="submit">Pay now</button>
                  </div>
                </div>
              </form>
            </div>
            <aside>
              <div class="summary">
                <?php foreach ($items as $it): ?>
                  <div class="sum-item">
                    <img class="sum-thumb" src="<?php echo htmlspecialchars((string)($it['image1'] ?? 'assets/img/listing/listing-1-1.png'), ENT_QUOTES); ?>" alt="thumb">
                    <div>
                      <div class="sum-title"><?php echo htmlspecialchars((string)$it['product_title'], ENT_QUOTES); ?></div>
                      <?php if (!empty($it['size'])): ?><div class="sum-meta">Size: <?php echo htmlspecialchars((string)$it['size'], ENT_QUOTES); ?></div><?php endif; ?>
                    </div>
                    <div>Rs <?php echo number_format((float)($it['price'] ?? 0), 2); ?></div>
                  </div>
                <?php endforeach; ?>
                <div class="sum-code">
                  <!-- <input type="text" id="discount_code" placeholder="Discount code">
                  <button class="btn btn-outline" id="apply_discount" type="button">Apply</button> -->
                </div>
                <div class="sum-line"><span>Subtotal</span><span>Rs <?php echo number_format($total,2); ?></span></div>
                <div class="sum-line"><span>Shipping</span><span>Rs <?php echo number_format($shipping,2); ?></span></div>
                <div class="sum-total"><span>Total</span><span>PKR Rs <span id="grand_total"><?php echo number_format($grand,2); ?></span></span></div>
                <div style="margin-top:12px;display:flex;gap:10px;justify-content:flex-end">
                  <a class="btn btn-outline" href="cart.php">Back to Cart</a>
                </div>
              </div>
            </aside>
          </div>
        </div>
      </section>
   </main>

   <script src="assets/js/vendor/jquery.js"></script>
   <script src="assets/js/bootstrap-bundle.js"></script>
   <script src="assets/js/slick.js"></script>
   <script src="assets/js/main.js"></script>
   <script>
       (function(){
         var code = document.getElementById('discount_code');
         var apply = document.getElementById('apply_discount');
         var grandEl = document.getElementById('grand_total');
         var dcInput = document.getElementById('discount_code_input');
         var daInput = document.getElementById('discount_amount_input');
         var subtotal = <?php echo json_encode($total); ?>;
         var shipping = <?php echo json_encode($shipping); ?>;
         function setGrand(v){ grandEl.textContent = v.toFixed(2); }
         setGrand(subtotal + shipping);
         apply && apply.addEventListener('click', function(){
           var c = (code.value || '').trim();
           var amt = 0;
           if (c.toUpperCase() === 'DISCOUNT10') { amt = Math.min(subtotal * 0.10, 200); }
           dcInput.value = c;
           daInput.value = amt.toFixed(2);
           setGrand(Math.max(0, subtotal + shipping - amt));
           apply.disabled = true;
         });

         var billingAlt = document.getElementById('billing_alt');
         var billingRadios = document.querySelectorAll('input[name="billing_same"]');
         function updateBilling(){
           var selected = document.querySelector('input[name="billing_same"]:checked');
           billingAlt.style.display = selected && selected.value === 'no' ? 'block' : 'none';
         }
         billingRadios.forEach(function(r){ r.addEventListener('change', updateBilling); });
         updateBilling();

         var bankDetails = document.getElementById('bank_details');
         var codDetails = document.getElementById('cod_details');
         var easypaisaDetails = document.getElementById('easypaisa_details');
         var jazzcashDetails = document.getElementById('jazzcash_details');
         var paymentRadios = document.querySelectorAll('input[name="payment"]');
         function updatePayment(){
           var selected = document.querySelector('input[name="payment"]:checked');
           var val = selected ? selected.value : '';
           bankDetails.style.display = val === 'bank' ? 'block' : 'none';
           codDetails.style.display = val === 'cod' ? 'block' : 'none';
           easypaisaDetails.style.display = val === 'easypaisa' ? 'block' : 'none';
           jazzcashDetails.style.display = val === 'jazzcash' ? 'block' : 'none';
         }
         paymentRadios.forEach(function(r){ r.addEventListener('change', updatePayment); });
         updatePayment();
       })();
     </script>
</body>
</html>
<?php else: ?>
</head>
<body>
  <script>
    alert('Your order request was sent successfully');
    window.location.href='order_request.php?id=<?php echo (int)$orderId; ?>';
  </script>
</body>
</html>
<?php endif; ?>
