<?php
require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/cart.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';
require_once __DIR__ . '/../app/helpers/email.php';
require_once __DIR__ . '/../app/helpers/abandoned-cart.php';

$pageTitle = 'Checkout | LOVE-U Essentials';
$pageDescription = 'Complete your LOVE-U Essentials order securely.';

$currentCustomer = function_exists('customer') ? customer() : null;

$cart = get_cart();
$productIds = [];

foreach ($cart as $cartKey => $cartItem) {
    if (!empty($cartItem['product_id'])) {
        $productIds[] = (int) $cartItem['product_id'];
    }
}

$productIds = array_values(array_unique($productIds));

$cartItems = [];

$subtotal = 0;
$shippingFee = 0;
$discountAmount = 0;
$total = 0;

$error = '';
$couponMessage = '';
$orderSuccess = false;
$orderNumber = '';

$appliedCoupon = $_SESSION['applied_coupon'] ?? null;

$old = $_SESSION['checkout_old'] ?? [];

if (is_post()) {
    $old = array_merge($old, $_POST);
}

$selectedBillingCountry = $old['billing_country'] ?? 'United Kingdom';
$selectedShippingCountry = $old['shipping_country'] ?? 'United Kingdom';

$shippingRateName = '';
$shippingMessage = '';

if ($productIds) {
    $placeholders = implode(',', array_fill(0, count($productIds), '?'));

    $stmt = $pdo->prepare("
        SELECT p.*,
            (
                SELECT image_path
                FROM product_images
                WHERE product_id = p.id
                ORDER BY is_primary DESC, sort_order ASC, id ASC
                LIMIT 1
            ) AS primary_image
        FROM products p
        WHERE p.id IN ($placeholders)
          AND p.status = 'active'
    ");

    $stmt->execute($productIds);
    $products = $stmt->fetchAll();

    foreach ($cart as $cartKey => $cartItem) {
        $productId = (int) ($cartItem['product_id'] ?? 0);
        $variationId = !empty($cartItem['variation_id']) ? (int) $cartItem['variation_id'] : null;

        $product = null;

        foreach ($products as $productRow) {
            if ((int) $productRow['id'] === $productId) {
                $product = $productRow;
                break;
            }
        }

        if (!$product) {
            continue;
        }

        $variation = null;

        if ($variationId) {
            $stmtVariation = $pdo->prepare("
            SELECT *
            FROM product_variations
            WHERE id = ?
              AND product_id = ?
              AND status = 'active'
            LIMIT 1
        ");
            $stmtVariation->execute([$variationId, $productId]);
            $variation = $stmtVariation->fetch();
        }

        $quantity = (int) ($cartItem['quantity'] ?? 1);
        $basePrice = !empty($product['sale_price']) ? (float) $product['sale_price'] : (float) $product['regular_price'];
        $unitPrice = $basePrice + (float) ($variation['price_adjustment'] ?? 0);
        $lineTotal = $unitPrice * $quantity;

        $displayImage = $product['primary_image'] ?? '';

        if (!empty($variation['image_path'])) {
            $displayImage = $variation['image_path'];
        }

        $subtotal += $lineTotal;

        $cartItems[] = [
            'cart_key' => $cartKey,
            'product' => $product,
            'variation' => $variation,
            'display_image' => $displayImage,
            'quantity' => $quantity,
            'unit_price' => $unitPrice,
            'line_total' => $lineTotal,
        ];
    }
}
if ($cartItems && $subtotal > 0) {
    $abandonedCartItems = [];

    foreach ($cartItems as $item) {
        $variation = $item['variation'] ?? null;

        $abandonedCartItems[] = [
            'product_id' => $item['product']['id'],
            'variation_id' => $variation['id'] ?? null,
            'product_name' => $item['product']['product_name'],
            'variation_name' => $variation
                ? $variation['variation_name'] . ': ' . $variation['variation_value']
                : null,
            'quantity' => $item['quantity'],
            'unit_price' => $item['unit_price'],
        ];
    }

    $checkoutEmailForCart = trim($_POST['email'] ?? ($currentCustomer['email'] ?? ''));

    upsert_abandoned_cart(
        $currentCustomer['id'] ?? null,
        $checkoutEmailForCart,
        $subtotal,
        $abandonedCartItems
    );
}

if (is_post() && !verify_csrf()) {
    $error = 'Invalid request. Please refresh and try again.';
}

if (!$error && is_post() && ($_POST['checkout_action'] ?? '') === 'apply_coupon') {
    $_SESSION['checkout_old'] = $old;

    $couponCode = strtoupper(trim($_POST['coupon_code'] ?? ''));

    if ($couponCode === '') {
        $error = 'Please enter a coupon code.';
    } elseif (!$cartItems) {
        $error = 'Your cart is empty.';
    } else {
        $stmt = $pdo->prepare("
            SELECT *
            FROM coupons
            WHERE coupon_code = ?
              AND status = 'active'
            LIMIT 1
        ");
        $stmt->execute([$couponCode]);
        $coupon = $stmt->fetch();

        if (!$coupon) {
            $error = 'Invalid or inactive coupon code.';
        } elseif (!empty($coupon['starts_at']) && strtotime($coupon['starts_at']) > time()) {
            $error = 'This coupon is not active yet.';
        } elseif (!empty($coupon['expires_at']) && strtotime($coupon['expires_at']) < time()) {
            $error = 'This coupon has expired.';
        } elseif (!empty($coupon['usage_limit']) && (int) $coupon['used_count'] >= (int) $coupon['usage_limit']) {
            $error = 'This coupon usage limit has been reached.';
        } elseif ($subtotal < (float) $coupon['min_order_amount']) {
            $error = 'Minimum order amount for this coupon is ' . format_price($coupon['min_order_amount']) . '.';
        } else {
            $_SESSION['applied_coupon'] = [
                'id' => $coupon['id'],
                'coupon_code' => $coupon['coupon_code'],
                'coupon_type' => $coupon['coupon_type'],
                'coupon_value' => $coupon['coupon_value'],
                'max_discount_amount' => $coupon['max_discount_amount'],
            ];

            redirect(BASE_URL . '/public/checkout.php?coupon=applied');
        }
    }
}

if (!$error && is_post() && ($_POST['checkout_action'] ?? '') === 'remove_coupon') {
    $_SESSION['checkout_old'] = $old;
    unset($_SESSION['applied_coupon']);

    redirect(BASE_URL . '/public/checkout.php?coupon=removed');
}

if (isset($_GET['remove_coupon'])) {
    unset($_SESSION['applied_coupon']);
    redirect(BASE_URL . '/public/checkout.php?coupon=removed');
}

$appliedCoupon = $_SESSION['applied_coupon'] ?? null;

if ($appliedCoupon && $subtotal > 0) {
    if ($appliedCoupon['coupon_type'] === 'percentage') {
        $discountAmount = $subtotal * ((float) $appliedCoupon['coupon_value'] / 100);

        if (!empty($appliedCoupon['max_discount_amount']) && $discountAmount > (float) $appliedCoupon['max_discount_amount']) {
            $discountAmount = (float) $appliedCoupon['max_discount_amount'];
        }
    } else {
        $discountAmount = (float) $appliedCoupon['coupon_value'];
    }

    if ($discountAmount > $subtotal) {
        $discountAmount = $subtotal;
    }
}

if ($subtotal > 0) {
    $stmt = $pdo->prepare("
        SELECT sr.*, sz.zone_name, sz.country, sz.region, sz.message
        FROM shipping_rates sr
        INNER JOIN shipping_zones sz ON sr.zone_id = sz.id
        WHERE sz.status = 'active'
          AND sr.status = 'active'
          AND sz.country = ?
          AND sr.min_order_amount <= ?
          AND (sr.max_order_amount IS NULL OR sr.max_order_amount = 0 OR sr.max_order_amount >= ?)
        ORDER BY sr.min_order_amount DESC, sr.id DESC
        LIMIT 1
    ");

    $stmt->execute([
        $selectedShippingCountry,
        $subtotal,
        $subtotal
    ]);

    $shippingRate = $stmt->fetch();

    if ($shippingRate) {
        $shippingRateName = $shippingRate['rate_name'];
        $shippingMessage = $shippingRate['message'] ?? '';

        if (!empty($shippingRate['free_shipping_threshold']) && $subtotal >= (float) $shippingRate['free_shipping_threshold']) {
            $shippingFee = 0;
        } else {
            $shippingFee = (float) $shippingRate['shipping_fee'];
        }
    } else {
        $shippingRateName = 'Shipping';
        $shippingMessage = 'Shipping rate will be confirmed manually.';
        $shippingFee = 0;
    }
}

$total = $subtotal + $shippingFee - $discountAmount;

if (isset($_GET['coupon']) && $_GET['coupon'] === 'applied') {
    $couponMessage = 'Coupon applied successfully.';
}

if (isset($_GET['coupon']) && $_GET['coupon'] === 'removed') {
    $couponMessage = 'Coupon removed successfully.';
}

if (!$error && is_post() && ($_POST['checkout_action'] ?? '') === 'place_order') {
    if (!$cartItems) {
        $error = 'Your cart is empty.';
    } else {
        $firstName = trim($_POST['first_name'] ?? '');
        $lastName = trim($_POST['last_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');

        $billingAddress1 = trim($_POST['billing_address_1'] ?? '');
        $billingAddress2 = trim($_POST['billing_address_2'] ?? '');
        $billingCity = trim($_POST['billing_city'] ?? '');
        $billingRegion = trim($_POST['billing_region'] ?? '');
        $billingPostcode = trim($_POST['billing_postcode'] ?? '');
        $billingCountry = trim($_POST['billing_country'] ?? '');

        $shippingAddress1 = trim($_POST['shipping_address_1'] ?? '');
        $shippingAddress2 = trim($_POST['shipping_address_2'] ?? '');
        $shippingCity = trim($_POST['shipping_city'] ?? '');
        $shippingRegion = trim($_POST['shipping_region'] ?? '');
        $shippingPostcode = trim($_POST['shipping_postcode'] ?? '');
        $shippingCountry = trim($_POST['shipping_country'] ?? '');

        $selectedBillingCountry = $billingCountry;
        $selectedShippingCountry = $shippingCountry;

        $orderNotes = trim($_POST['order_notes'] ?? '');

        $isGift = isset($_POST['is_gift']) ? 1 : 0;
        $giftRecipientName = trim($_POST['gift_recipient_name'] ?? '');
        $giftRecipientEmail = trim($_POST['gift_recipient_email'] ?? '');
        $giftRecipientPhone = trim($_POST['gift_recipient_phone'] ?? '');
        $giftMessage = trim($_POST['gift_message'] ?? '');

        if ($firstName === '' || $email === '' || $phone === '') {
            $error = 'Please enter your name, email, and phone number.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid email address.';
        } elseif ($billingAddress1 === '' || $billingCity === '' || $billingCountry === '') {
            $error = 'Please complete your billing address.';
        } elseif ($shippingAddress1 === '' || $shippingCity === '' || $shippingCountry === '') {
            $error = 'Please complete your shipping address.';
        } elseif ($isGift && $giftRecipientName === '') {
            $error = 'Please enter the gift recipient name.';
        } else {
            try {
                $stmt = $pdo->prepare("
                    SELECT sr.*, sz.zone_name, sz.country, sz.region, sz.message
                    FROM shipping_rates sr
                    INNER JOIN shipping_zones sz ON sr.zone_id = sz.id
                    WHERE sz.status = 'active'
                      AND sr.status = 'active'
                      AND sz.country = ?
                      AND sr.min_order_amount <= ?
                      AND (sr.max_order_amount IS NULL OR sr.max_order_amount = 0 OR sr.max_order_amount >= ?)
                    ORDER BY sr.min_order_amount DESC, sr.id DESC
                    LIMIT 1
                ");

                $stmt->execute([
                    $shippingCountry,
                    $subtotal,
                    $subtotal
                ]);

                $shippingRate = $stmt->fetch();

                if ($shippingRate) {
                    $shippingRateName = $shippingRate['rate_name'];

                    if (!empty($shippingRate['free_shipping_threshold']) && $subtotal >= (float) $shippingRate['free_shipping_threshold']) {
                        $shippingFee = 0;
                    } else {
                        $shippingFee = (float) $shippingRate['shipping_fee'];
                    }
                } else {
                    $shippingRateName = 'Shipping';
                    $shippingFee = 0;
                }

                $total = $subtotal + $shippingFee - $discountAmount;

                $pdo->beginTransaction();

                foreach ($cartItems as $item) {
                    $product = $item['product'];
                    $variation = $item['variation'] ?? null;
                    $requestedQty = (int) $item['quantity'];

                    if ($variation) {
                        $stmtStockCheck = $pdo->prepare("
            SELECT stock_quantity, status, variation_value
            FROM product_variations
            WHERE id = ?
              AND product_id = ?
            LIMIT 1
        ");
                        $stmtStockCheck->execute([
                            $variation['id'],
                            $product['id']
                        ]);
                        $latestVariation = $stmtStockCheck->fetch();

                        if (
                            !$latestVariation ||
                            $latestVariation['status'] !== 'active' ||
                            (int) $latestVariation['stock_quantity'] <= 0
                        ) {
                            throw new Exception($product['product_name'] . ' - ' . ($variation['variation_value'] ?? 'Selected option') . ' is now out of stock.');
                        }

                        if ($requestedQty > (int) $latestVariation['stock_quantity']) {
                            throw new Exception(
                                'Only ' . (int) $latestVariation['stock_quantity'] .
                                    ' item(s) left for ' . $product['product_name'] .
                                    ' - ' . $latestVariation['variation_value'] . '.'
                            );
                        }
                    } else {
                        $stmtStockCheck = $pdo->prepare("
            SELECT stock_quantity, stock_status
            FROM products
            WHERE id = ?
            LIMIT 1
        ");
                        $stmtStockCheck->execute([$product['id']]);
                        $latestProduct = $stmtStockCheck->fetch();

                        if (
                            !$latestProduct ||
                            $latestProduct['stock_status'] === 'out_of_stock' ||
                            (int) $latestProduct['stock_quantity'] <= 0
                        ) {
                            throw new Exception($product['product_name'] . ' is now out of stock.');
                        }

                        if ($requestedQty > (int) $latestProduct['stock_quantity']) {
                            throw new Exception(
                                'Only ' . (int) $latestProduct['stock_quantity'] .
                                    ' item(s) left for ' . $product['product_name'] . '.'
                            );
                        }
                    }
                }

                $orderNumber = 'LUE-' . date('Ymd') . '-' . strtoupper(bin2hex(random_bytes(3)));

                $billingAddress = implode("\n", array_filter([
                    $firstName . ' ' . $lastName,
                    $phone,
                    $billingAddress1,
                    $billingAddress2,
                    $billingCity,
                    $billingRegion,
                    $billingPostcode,
                    $billingCountry,
                ]));

                $shippingAddress = implode("\n", array_filter([
                    $firstName . ' ' . $lastName,
                    $phone,
                    $shippingAddress1,
                    $shippingAddress2,
                    $shippingCity,
                    $shippingRegion,
                    $shippingPostcode,
                    $shippingCountry,
                ]));

                $stmt = $pdo->prepare("
                    INSERT INTO orders (
                        order_number,
                        customer_id,
                        customer_email,
                        customer_phone,
                        billing_address,
                        shipping_address,
                        subtotal,
                        discount_amount,
                        shipping_fee,
                        tax_amount,
                        total_amount,
                        currency_code,
                        coupon_code,
                        order_notes,
                        is_gift,
                        payment_status,
                        order_status,
                        shipping_status
                    ) VALUES (
                        ?, ?, ?, ?, ?, ?, ?, ?, ?, 0.00, ?, 'GBP', ?, ?, ?,
                        'pending', 'pending', 'not_shipped'
                    )
                ");

                $stmt->execute([
                    $orderNumber,
                    $currentCustomer['id'] ?? null,
                    $email,
                    $phone,
                    $billingAddress,
                    $shippingAddress,
                    $subtotal,
                    $discountAmount,
                    $shippingFee,
                    $total,
                    $appliedCoupon['coupon_code'] ?? null,
                    $orderNotes,
                    $isGift
                ]);

                $orderId = (int) $pdo->lastInsertId();

                $stmtItem = $pdo->prepare("
    INSERT INTO order_items (
        order_id,
        product_id,
        variation_id,
        product_name,
        variation_name,
        sku,
        quantity,
        unit_price,
        total_price
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
");

                $stmtProductStock = $pdo->prepare("
    UPDATE products
    SET stock_quantity = GREATEST(stock_quantity - ?, 0)
    WHERE id = ?
");

                $stmtVariationStock = $pdo->prepare("
    UPDATE product_variations
    SET stock_quantity = GREATEST(stock_quantity - ?, 0)
    WHERE id = ?
");

                foreach ($cartItems as $item) {
                    $product = $item['product'];

                    $variation = $item['variation'] ?? null;

                    $variationName = null;
                    $finalSku = $product['sku'];

                    if ($variation) {
                        $variationName = $variation['variation_name'] . ': ' . $variation['variation_value'];

                        if (!empty($variation['sku'])) {
                            $finalSku = $variation['sku'];
                        }
                    }

                    $stmtItem->execute([
                        $orderId,
                        $product['id'],
                        $variation['id'] ?? null,
                        $product['product_name'],
                        $variationName,
                        $finalSku,
                        $item['quantity'],
                        $item['unit_price'],
                        $item['line_total'],
                    ]);
                    if (!empty($variation)) {
                        $stmtVariationStock->execute([
                            $item['quantity'],
                            $variation['id']
                        ]);
                    } else {
                        $stmtProductStock->execute([
                            $item['quantity'],
                            $product['id']
                        ]);
                    }
                }

                if ($isGift) {
                    $stmtGift = $pdo->prepare("
                        INSERT INTO gift_orders (
                            order_id,
                            recipient_name,
                            recipient_email,
                            recipient_phone,
                            gift_message,
                            hide_price,
                            gift_wrap
                        ) VALUES (?, ?, ?, ?, ?, 1, 0)
                    ");

                    $stmtGift->execute([
                        $orderId,
                        $giftRecipientName,
                        $giftRecipientEmail !== '' ? $giftRecipientEmail : null,
                        $giftRecipientPhone !== '' ? $giftRecipientPhone : null,
                        $giftMessage !== '' ? $giftMessage : null
                    ]);
                }

                $stmtPayment = $pdo->prepare("
                    INSERT INTO payments (
                        order_id,
                        payment_gateway,
                        transaction_id,
                        payment_reference,
                        amount,
                        currency_code,
                        status,
                        gateway_response
                    ) VALUES (?, 'manual', NULL, NULL, ?, 'GBP', 'pending', NULL)
                ");

                $stmtPayment->execute([$orderId, $total]);

                if ($appliedCoupon) {
                    $stmtCoupon = $pdo->prepare("
                        UPDATE coupons
                        SET used_count = used_count + 1
                        WHERE id = ?
                    ");
                    $stmtCoupon->execute([$appliedCoupon['id']]);
                }
                $siteName = function_exists('get_setting') ? get_setting('site_name', APP_NAME) : APP_NAME;

                $customerNameForEmail = trim(($firstName ?? '') . ' ' . ($lastName ?? ''));

                if ($customerNameForEmail === '') {
                    $customerNameForEmail = 'Customer';
                }

                queue_template_email(
                    'order_confirmation',
                    $email,
                    [
                        'site_name' => $siteName,
                        'customer_name' => $customerNameForEmail,
                        'order_number' => $orderNumber,
                        'order_total' => format_price($total, DEFAULT_CURRENCY),
                        'payment_status' => 'Pending',
                        'points' => '0'
                    ],
                    $currentCustomer['id'] ?? null,
                    $orderId
                );
                mark_abandoned_cart_recovered(null, $email);

                $pdo->commit();

                clear_cart();
                unset($_SESSION['applied_coupon']);
                unset($_SESSION['checkout_old']);

                $orderSuccess = true;
            } catch (Exception $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }

                $error = 'Order could not be placed: ' . $e->getMessage();
            }
        }
    }
}

function selected_country($current, $value)
{
    return $current === $value ? 'selected' : '';
}

require_once __DIR__ . '/includes/header.php';
?>

<section class="shop-hero">
    <div class="container">
        <div class="eyebrow">Secure Checkout</div>
        <h1>Checkout</h1>
        <p>Complete your details and place your LOVE-U Essentials order.</p>
    </div>
</section>

<section class="section">
    <div class="container">
        <?php if ($orderSuccess): ?>
            <div class="success-box">
                <h1>Order placed successfully</h1>
                <p>Your order number is <strong><?= e($orderNumber); ?></strong>.</p>
                <p>Payment status is currently pending. Payment gateway integration will be connected next.</p>
                <a href="<?= e(BASE_URL); ?>/public/shop.php" class="btn">Continue Shopping</a>
            </div>
        <?php elseif (!$cartItems): ?>
            <div class="empty-state">
                <h2>Your cart is empty</h2>
                <p>Add products to your cart before checkout.</p>
                <a href="<?= e(BASE_URL); ?>/public/shop.php" class="btn">Shop Now</a>
            </div>
        <?php else: ?>

            <?php if ($error || $couponMessage): ?>
                <div
                    class="checkout-toast <?= $error ? 'checkout-toast-error' : 'checkout-toast-success'; ?>"
                    id="checkoutToast">
                    <div>
                        <strong><?= $error ? 'Checkout Notice' : 'Coupon Updated'; ?></strong>
                        <p><?= e($error ?: $couponMessage); ?></p>
                    </div>

                    <button type="button" onclick="closeCheckoutToast()">×</button>
                </div>
            <?php endif; ?>

            <form method="POST">
                <?= csrf_field(); ?>

                <div class="checkout-layout">
                    <div class="checkout-form">
                        <h2>Contact Details</h2>

                        <div class="checkout-grid">
                            <div class="checkout-field">
                                <label>First Name *</label>
                                <input type="text" name="first_name" value="<?= e($old['first_name'] ?? $currentCustomer['first_name'] ?? ''); ?>" required>
                            </div>

                            <div class="checkout-field">
                                <label>Last Name</label>
                                <input type="text" name="last_name" value="<?= e($old['last_name'] ?? $currentCustomer['last_name'] ?? ''); ?>">
                            </div>

                            <div class="checkout-field">
                                <label>Email *</label>
                                <input type="email" name="email" value="<?= e($old['email'] ?? $currentCustomer['email'] ?? ''); ?>" required>
                            </div>

                            <div class="checkout-field">
                                <label>Phone *</label>
                                <input type="text" name="phone" value="<?= e($old['phone'] ?? ''); ?>" required>
                            </div>
                        </div>

                        <div class="lue-checkout-section-head">
                            <div>
                                <h2>Billing Address</h2>
                                <p>Use your billing details for invoices and order records.</p>
                            </div>
                        </div>

                        <div class="checkout-field">
                            <label>Address Line 1 *</label>
                            <input type="text" name="billing_address_1" id="billingAddress1" value="<?= e($old['billing_address_1'] ?? ''); ?>" required>
                        </div>

                        <div class="checkout-field">
                            <label>Address Line 2</label>
                            <input type="text" name="billing_address_2" id="billingAddress2" value="<?= e($old['billing_address_2'] ?? ''); ?>">
                        </div>

                        <div class="checkout-grid">
                            <div class="checkout-field">
                                <label>City *</label>
                                <input type="text" name="billing_city" id="billingCity" value="<?= e($old['billing_city'] ?? ''); ?>" required>
                            </div>

                            <div class="checkout-field">
                                <label>Region / State</label>
                                <input type="text" name="billing_region" id="billingRegion" value="<?= e($old['billing_region'] ?? ''); ?>">
                            </div>

                            <div class="checkout-field">
                                <label>Postal Code</label>
                                <input type="text" name="billing_postcode" id="billingPostcode" value="<?= e($old['billing_postcode'] ?? ''); ?>">
                            </div>

                            <div class="checkout-field">
                                <label>Country *</label>
                                <select name="billing_country" id="billingCountry" required>
                                    <option value="United Kingdom" <?= selected_country($selectedBillingCountry, 'United Kingdom'); ?>>United Kingdom</option>
                                    <option value="Grenada" <?= selected_country($selectedBillingCountry, 'Grenada'); ?>>Grenada</option>
                                    <option value="Sri Lanka" <?= selected_country($selectedBillingCountry, 'Sri Lanka'); ?>>Sri Lanka</option>
                                    <option value="Other" <?= selected_country($selectedBillingCountry, 'Other'); ?>>Other</option>
                                </select>
                            </div>
                        </div>

                        <div class="lue-checkout-section-head lue-checkout-section-head-row">
                            <div>
                                <h2>Shipping Address</h2>
                                <p>Where should we send your LOVE-U Essentials order?</p>
                            </div>

                            <label class="lue-same-address-toggle">
                                <input type="checkbox" id="sameAsBillingAddress">
                                <span></span>
                                Same as billing address
                            </label>
                        </div>

                        <div class="checkout-field">
                            <label>Address Line 1 *</label>
                            <input type="text" name="shipping_address_1" id="shippingAddress1" value="<?= e($old['shipping_address_1'] ?? ''); ?>" required>
                        </div>

                        <div class="checkout-field">
                            <label>Address Line 2</label>
                            <input type="text" name="shipping_address_2" id="shippingAddress2" value="<?= e($old['shipping_address_2'] ?? ''); ?>">
                        </div>

                        <div class="checkout-grid">
                            <div class="checkout-field">
                                <label>City *</label>
                                <input type="text" name="shipping_city" id="shippingCity" value="<?= e($old['shipping_city'] ?? ''); ?>" required>
                            </div>

                            <div class="checkout-field">
                                <label>Region / State</label>
                                <input type="text" name="shipping_region" id="shippingRegion" value="<?= e($old['shipping_region'] ?? ''); ?>">
                            </div>

                            <div class="checkout-field">
                                <label>Postal Code</label>
                                <input type="text" name="shipping_postcode" id="shippingPostcode" value="<?= e($old['shipping_postcode'] ?? ''); ?>">
                            </div>

                            <div class="checkout-field">
                                <label>Country *</label>
                                <select name="shipping_country" id="shippingCountrySelect" required>
                                    <option value="United Kingdom" <?= selected_country($selectedShippingCountry, 'United Kingdom'); ?>>United Kingdom</option>
                                    <option value="Grenada" <?= selected_country($selectedShippingCountry, 'Grenada'); ?>>Grenada</option>
                                    <option value="Sri Lanka" <?= selected_country($selectedShippingCountry, 'Sri Lanka'); ?>>Sri Lanka</option>
                                    <option value="Other" <?= selected_country($selectedShippingCountry, 'Other'); ?>>Other</option>
                                </select>
                                <small>Shipping total updates after submitting the order. Admin shipping rates are used.</small>
                            </div>
                        </div>

                        <h2>Gift Option</h2>

                        <div class="checkout-field">
                            <label style="display:flex; gap:10px; align-items:center; font-weight:700;">
                                <input type="checkbox" name="is_gift" value="1" <?= isset($old['is_gift']) ? 'checked' : ''; ?>>
                                Send this order as a gift
                            </label>
                        </div>

                        <div class="checkout-grid">
                            <div class="checkout-field">
                                <label>Gift Recipient Name</label>
                                <input type="text" name="gift_recipient_name" value="<?= e($old['gift_recipient_name'] ?? ''); ?>">
                            </div>

                            <div class="checkout-field">
                                <label>Gift Recipient Email</label>
                                <input type="email" name="gift_recipient_email" value="<?= e($old['gift_recipient_email'] ?? ''); ?>">
                            </div>

                            <div class="checkout-field">
                                <label>Gift Recipient Phone</label>
                                <input type="text" name="gift_recipient_phone" value="<?= e($old['gift_recipient_phone'] ?? ''); ?>">
                            </div>
                        </div>

                        <div class="checkout-field">
                            <label>Gift Message</label>
                            <textarea name="gift_message"><?= e($old['gift_message'] ?? ''); ?></textarea>
                        </div>

                        <h2>Order Notes</h2>

                        <div class="checkout-field">
                            <label>Notes</label>
                            <textarea name="order_notes" placeholder="Any delivery notes or special instructions?"><?= e($old['order_notes'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <aside class="checkout-summary">
                        <h2>Order Summary</h2>

                        <?php foreach ($cartItems as $item): ?>
                            <?php $product = $item['product']; ?>

                            <div class="checkout-product">
                                <div class="checkout-product-image">
                                    <?php if (!empty($item['display_image'])): ?>
                                        <img src="<?= e(BASE_URL . '/' . $item['display_image']); ?>" alt="<?= e($product['product_name']); ?>">
                                    <?php else: ?>
                                        <div class="product-placeholder"><?= e($product['product_name']); ?></div>
                                    <?php endif; ?>
                                </div>

                                <div>
                                    <h3><?= e($product['product_name']); ?></h3>
                                    <?php if (!empty($item['variation'])): ?>
                                        <p>
                                            <?= e($item['variation']['variation_name']); ?>:
                                            <strong><?= e($item['variation']['variation_value']); ?></strong>
                                        </p>
                                    <?php endif; ?>

                                    <p>Qty <?= e($item['quantity']); ?> × <?= e(format_price($item['unit_price'], $product['currency_code'])); ?></p>
                                </div>

                                <strong><?= e(format_price($item['line_total'], $product['currency_code'])); ?></strong>
                            </div>
                        <?php endforeach; ?>

                        <div style="margin:18px 0; padding:16px; background:#fff; border:1px solid #e2d8cc; border-radius:16px;">
                            <h3 style="margin:0 0 12px; font-size:16px;">Coupon Code</h3>

                            <?php if ($appliedCoupon): ?>
                                <p style="margin:0 0 12px; color:#555;">
                                    Applied: <strong><?= e($appliedCoupon['coupon_code']); ?></strong>
                                </p>

                                <button
                                    type="submit"
                                    name="checkout_action"
                                    value="remove_coupon"
                                    class="btn btn-light"
                                    style="width:100%;">
                                    Remove Coupon
                                </button>
                            <?php else: ?>
                                <div class="checkout-field" style="margin-bottom:12px;">
                                    <input
                                        type="text"
                                        name="coupon_code"
                                        value="<?= e($old['coupon_code'] ?? ''); ?>"
                                        placeholder="Optional coupon code">
                                </div>

                                <button
                                    type="submit"
                                    name="checkout_action"
                                    value="apply_coupon"
                                    class="btn btn-light"
                                    style="width:100%;">
                                    Apply Coupon
                                </button>
                            <?php endif; ?>

                            <p class="cart-note" style="margin-top:10px;">
                                Coupon code is optional. You can place the order without one.
                            </p>
                        </div>

                        <div class="checkout-total-row">
                            <span>Subtotal</span>
                            <strong><?= e(format_price($subtotal)); ?></strong>
                        </div>

                        <div class="checkout-total-row">
                            <span>
                                Shipping
                                <?php if ($shippingRateName): ?>
                                    <br><small><?= e($shippingRateName); ?></small>
                                <?php endif; ?>
                            </span>
                            <strong><?= $shippingFee > 0 ? e(format_price($shippingFee)) : 'Free'; ?></strong>
                        </div>

                        <?php if ($shippingMessage): ?>
                            <p class="cart-note"><?= e($shippingMessage); ?></p>
                        <?php endif; ?>

                        <?php if ($discountAmount > 0): ?>
                            <div class="checkout-total-row">
                                <span>Discount<?= $appliedCoupon ? ' (' . e($appliedCoupon['coupon_code']) . ')' : ''; ?></span>
                                <strong>-<?= e(format_price($discountAmount)); ?></strong>
                            </div>
                        <?php endif; ?>

                        <div class="checkout-grand-total">
                            <span>Total</span>
                            <strong><?= e(format_price($total)); ?></strong>
                        </div>

                        <button
                            type="submit"
                            name="checkout_action"
                            value="place_order"
                            class="btn">
                            Place Order
                        </button>

                        <p class="cart-note">
                            Current checkout saves the order as pending payment. Stripe / PayPal will be connected after this flow is confirmed.
                        </p>
                    </aside>
                </div>
            </form>
        <?php endif; ?>
    </div>
</section>

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