<?php
require_once __DIR__ . '/includes/config.php';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $cart = $_SESSION['cart'] ?? [];
    if (empty($cart)) {
        $_SESSION['error'] = 'Your cart is empty.';
        header('Location: /cart.php');
        exit;
    }

    $email     = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    $phone     = trim($_POST['phone'] ?? '');
    $firstName = trim($_POST['first_name'] ?? '');
    $lastName  = trim($_POST['last_name'] ?? '');
    $address   = trim($_POST['address'] ?? '');
    $city      = trim($_POST['city'] ?? '');
    $state     = trim($_POST['state'] ?? '');
    $zip       = trim($_POST['zip'] ?? '');

    if (!$email || !$phone || !$firstName || !$lastName || !$address || !$city || !$state || !$zip) {
        $_SESSION['error'] = 'Please fill in all required fields.';
        header('Location: /checkout.php');
        exit;
    }

    // Build email body
    $subtotal = 0;
    $itemLines = '';
    foreach ($cart as $item) {
        $itemTotal = $item['price'] * $item['quantity'];
        $subtotal += $itemTotal;
        $itemLines .= "- {$item['name']}: Qty {$item['quantity']} x $" . number_format($item['price'], 2) . " = $" . number_format($itemTotal, 2) . "\n";
    }

    $body = "New Order Request\n\n";
    $body .= "Customer: {$firstName} {$lastName}\n";
    $body .= "Email: {$email}\n";
    $body .= "Phone: {$phone}\n\n";
    $body .= "Shipping Address:\n{$address}\n{$city}, {$state} {$zip}\n\n";
    $body .= "Items:\n{$itemLines}\n";
    $body .= "Subtotal: $" . number_format($subtotal, 2) . "\n";

    // Send via PHP mail (PHPMailer can be added for SMTP)
    $headers = "From: " . SITE_EMAIL . "\r\nReply-To: {$email}\r\n";
    @mail(SITE_EMAIL, SITE_NAME . ' - New Order Request', $body, $headers);

    $_SESSION['cart'] = [];
    $_SESSION['success'] = 'Request sent successfully! A member of our team will get back to you shortly.';
    header('Location: /checkout-success.php');
    exit;
}

$cart = $_SESSION['cart'] ?? [];
$subtotal = 0;
foreach ($cart as $item) {
    $subtotal += $item['price'] * $item['quantity'];
}

$pageTitle = 'Secure Checkout | ' . SITE_NAME;
$metaDescription = 'Complete your ' . SITE_NAME . ' order.';
require_once __DIR__ . '/includes/header.php';
?>

<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
    <div class="grid grid-cols-1 lg:grid-cols-12 gap-12">
        <div class="lg:col-span-7">
            <h2 class="text-3xl font-black text-white uppercase tracking-tighter mb-8 border-b-2 border-brand-orange inline-block pb-2">Secure Checkout</h2>
            <form action="/checkout.php" method="POST" class="space-y-8 bg-gray-900 border border-gray-800 p-8 rounded-2xl shadow-xl">
                <div>
                    <h3 class="text-xl font-bold text-white mb-4">1. Contact Info</h3>
                    <div class="space-y-4">
                        <input type="email" name="email" placeholder="Email Address" required class="w-full bg-black border border-gray-700 text-white rounded-lg px-4 py-3 focus:outline-none focus:border-brand-orange transition-colors">
                        <input type="tel" name="phone" placeholder="Phone Number" required class="w-full bg-black border border-gray-700 text-white rounded-lg px-4 py-3 focus:outline-none focus:border-brand-orange transition-colors">
                    </div>
                </div>
                <div class="pt-6 border-t border-gray-800">
                    <h3 class="text-xl font-bold text-white mb-4">2. Shipping Address</h3>
                    <div class="grid grid-cols-2 gap-4">
                        <input type="text" name="first_name" placeholder="First Name" required class="w-full bg-black border border-gray-700 text-white rounded-lg px-4 py-3 focus:outline-none focus:border-brand-orange transition-colors">
                        <input type="text" name="last_name" placeholder="Last Name" required class="w-full bg-black border border-gray-700 text-white rounded-lg px-4 py-3 focus:outline-none focus:border-brand-orange transition-colors">
                        <input type="text" name="address" placeholder="Street Address" required class="col-span-2 w-full bg-black border border-gray-700 text-white rounded-lg px-4 py-3 focus:outline-none focus:border-brand-orange transition-colors">
                        <input type="text" name="city" placeholder="City" required class="w-full bg-black border border-gray-700 text-white rounded-lg px-4 py-3 focus:outline-none focus:border-brand-orange transition-colors">
                        <div class="grid grid-cols-2 gap-4">
                            <input type="text" name="state" placeholder="State/Prov" required class="w-full bg-black border border-gray-700 text-white rounded-lg px-4 py-3 focus:outline-none focus:border-brand-orange transition-colors">
                            <input type="text" name="zip" placeholder="Zip Code" required class="w-full bg-black border border-gray-700 text-white rounded-lg px-4 py-3 focus:outline-none focus:border-brand-orange transition-colors">
                        </div>
                    </div>
                </div>
                <button type="submit" class="w-full bg-brand-orange text-white font-black text-lg py-4 px-6 rounded-xl uppercase tracking-widest hover:bg-[#ff5511] transition-colors border border-brand-orange/30">
                    Request Order Confirmation
                </button>
            </form>
        </div>

        <div class="lg:col-span-5">
            <div class="bg-black border border-gray-800 rounded-2xl p-8 sticky top-24 shadow-2xl">
                <h2 class="text-2xl font-black text-white uppercase tracking-wider border-b border-gray-700 pb-4 mb-6">In Your Cart</h2>
                <ul class="divide-y divide-gray-800 mb-6">
                    <?php foreach ($cart as $item): ?>
                    <li class="py-4 flex gap-4">
                        <div class="h-16 w-16 bg-gray-900 rounded border border-gray-700 flex items-center justify-center overflow-hidden flex-shrink-0">
                            <?php if ($item['image']): ?><img src="<?= e($item['image']) ?>" class="h-full object-contain"><?php endif; ?>
                        </div>
                        <div class="flex-1">
                            <h4 class="text-white font-bold text-sm truncate pr-2"><?= e($item['name']) ?></h4>
                            <p class="text-gray-500 text-xs mt-1">Qty: <?= $item['quantity'] ?></p>
                        </div>
                        <p class="text-brand-orange font-bold">$<?= number_format($item['price'], 2) ?></p>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <div class="space-y-3 text-sm font-semibold text-gray-400">
                    <div class="flex justify-between"><p>Subtotal</p><p class="text-white">$<?= number_format($subtotal, 2) ?></p></div>
                    <div class="flex justify-between"><p>Shipping</p><p class="text-white">Free (Over $99)</p></div>
                    <div class="flex justify-between border-t border-gray-800 pt-3 mt-3 text-lg font-bold text-white uppercase"><p>Total</p><p class="text-brand-orange">$<?= number_format($subtotal, 2) ?></p></div>
                </div>
            </div>
        </div>
    </div>
</div>

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