<?php
require_once __DIR__ . '/functions.php';
$page_title = 'Checkout';
$db = db();

// Handle Buy Now — add product to cart before displaying checkout
if (isset($_GET['buy_now'])) {
    $buyPid = (int)$_GET['buy_now'];
    $buyVid = !empty($_GET['variant_id']) ? (int)$_GET['variant_id'] : null;
    $cartId = getCartId();
    $existing = $db->prepare("SELECT id FROM cart_items WHERE cart_id = ? AND product_id = ? AND (variant_id = ? OR (variant_id IS NULL AND ? IS NULL))");
    $existing->execute([$cartId, $buyPid, $buyVid, $buyVid]);
    if (!$existing->fetch()) {
        $p = $db->prepare("SELECT price FROM products WHERE id = ? AND is_active = 1");
        $p->execute([$buyPid]);
        $prod = $p->fetch();
        $unitPrice = $prod ? (float)$prod['price'] : 0;
        if ($buyVid) {
            $v = $db->prepare("SELECT price_modifier FROM product_variants WHERE id = ? AND is_active = 1");
            $v->execute([$buyVid]);
            $vr = $v->fetch();
            if ($vr) $unitPrice = (float)$vr['price_modifier'];
        }
        $db->prepare("INSERT INTO cart_items (cart_id, product_id, variant_id, quantity, unit_price) VALUES (?, ?, ?, 1, ?)")
            ->execute([$cartId, $buyPid, $buyVid, $unitPrice]);
    }
}

$items = getCartItems();
if (count($items) === 0) {
    header('Location: cart.php');
    exit;
}

$subtotal = getCartTotal();
$coupon = getAppliedCoupon();
$user = null;
$shippingState = null;
if (isLoggedIn()) {
    $user = getCurrentUser();
    $shippingState = $user['state'] ?? null;
}
$totals = calculateTotals($subtotal, $coupon, $items, $shippingState);

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

<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <h1 class="text-2xl font-bold text-gray-800 mb-6">Checkout</h1>

    <?php if (!isLoggedIn()): ?>
    <div class="bg-blue-50 border border-blue-200 text-blue-700 px-4 py-3 rounded-lg mb-6 flex items-center gap-2">
        <i class="fas fa-info-circle"></i> Please <a href="login.php?redirect=checkout.php" class="underline font-medium">login</a> or <a href="register.php" class="underline font-medium">register</a> to place your order.
    </div>
    <?php endif; ?>
    <?php if (empty(RAZORPAY_KEY_ID)): ?>
    <div class="bg-yellow-50 border border-yellow-200 text-yellow-700 px-4 py-3 rounded-lg mb-6 flex items-center gap-2">
        <i class="fas fa-exclamation-triangle"></i> Razorpay not configured. Only COD is available.
    </div>
    <?php endif; ?>

    <form method="POST" id="checkout-form" class="grid grid-cols-1 lg:grid-cols-3 gap-8" onsubmit="return placeOrder(event)">
        <div class="lg:col-span-2 space-y-6">
            <!-- Shipping Info -->
            <div class="bg-white rounded-xl border border-gray-200 p-6">
                <h2 class="font-semibold text-gray-800 mb-4">Shipping Address</h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Full Name *</label>
                        <input type="text" name="shipping_name" value="<?= h($user['name'] ?? '') ?>" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Phone *</label>
                        <input type="text" name="shipping_phone" value="<?= h($user['phone'] ?? '') ?>" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500">
                    </div>
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Address *</label>
                        <textarea name="shipping_address" rows="2" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500"><?= h($user['address'] ?? '') ?></textarea>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">City *</label>
                        <input type="text" name="shipping_city" value="<?= h($user['city'] ?? '') ?>" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">State *</label>
                        <input type="text" name="shipping_state" value="<?= h($user['state'] ?? '') ?>" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Pincode *</label>
                        <input type="text" name="shipping_pincode" value="<?= h($user['pincode'] ?? '') ?>" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Country</label>
                        <input type="text" name="shipping_country" value="India" class="w-full border border-gray-300 rounded-lg px-3 py-2 bg-gray-50 focus:outline-none focus:ring-1 focus:ring-primary-500">
                    </div>
                </div>
            </div>

            <!-- Payment Method -->
            <div class="bg-white rounded-xl border border-gray-200 p-6">
                <h2 class="font-semibold text-gray-800 mb-4">Payment Method</h2>
                <div class="space-y-2">
                    <label class="flex items-center gap-3 p-3 border border-gray-200 rounded-lg cursor-pointer hover:border-primary-500">
                        <input type="radio" name="payment_method" value="cod" checked onchange="toggleRazorpay(false)">
                        <span><i class="fas fa-money-bill-wave text-green-600 mr-2"></i> Cash on Delivery</span>
                    </label>
                    <label class="flex items-center gap-3 p-3 border border-gray-200 rounded-lg cursor-pointer hover:border-primary-500">
                        <input type="radio" name="payment_method" value="razorpay" onchange="toggleRazorpay(true)">
                        <span><i class="fas fa-credit-card text-primary-600 mr-2"></i> Pay Online (Razorpay)</span>
                    </label>
                </div>
            </div>

            <!-- Order Notes -->
            <div class="bg-white rounded-xl border border-gray-200 p-6">
                <h2 class="font-semibold text-gray-800 mb-2">Order Notes (Optional)</h2>
                <textarea name="notes" rows="2" placeholder="Any special instructions?" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary-500"></textarea>
            </div>
        </div>

        <!-- Order Summary -->
        <div class="bg-white rounded-xl border border-gray-200 p-6 h-fit sticky top-24">
            <h2 class="font-semibold text-gray-800 mb-4">Order Summary</h2>
            <div class="space-y-3 mb-4">
                <?php foreach ($items as $item): ?>
                <div class="flex items-start gap-3">
                    <div class="w-14 h-14 bg-gray-50 rounded-lg flex items-center justify-center overflow-hidden shrink-0">
                        <?php $ci = $item['variant_image'] ? BASE_PATH . '/' . h($item['variant_image']) : ($item['image'] ? h($item['image']) : ''); ?>
                        <?php if ($ci): ?>
                        <img src="<?= $ci ?>" alt="" class="w-full h-full object-cover">
                        <?php else: ?>
                        <i class="fas fa-box text-gray-300"></i>
                        <?php endif; ?>
                    </div>
                    <div class="flex-1 min-w-0">
                        <p class="text-sm font-medium text-gray-800 truncate"><?= h($item['name']) ?></p>
                        <p class="text-xs text-gray-500">Qty: <?= $item['quantity'] ?></p>
                        <?php if ($item['variant_value']): ?>
                        <p class="text-xs text-gray-400"><?= h($item['variant_type']) ?>: <?= h($item['variant_value']) ?></p>
                        <?php endif; ?>
                        <button type="button" onclick="removeItem(<?= $item['id'] ?>)" class="text-xs text-red-500 hover:text-red-700 mt-1 flex items-center gap-1"><i class="fas fa-trash-alt"></i> Remove</button>
                    </div>
                    <p class="text-sm font-medium shrink-0"><?= formatPrice($item['unit_price'] * $item['quantity']) ?></p>
                </div>
                <?php endforeach; ?>
            </div>
            <hr>
            <div class="space-y-2 text-sm mt-4">
                <div class="flex justify-between text-gray-600">
                    <span>Subtotal</span>
                    <span><?= formatPrice($totals['subtotal']) ?></span>
                </div>
                <?php if ($totals['discount'] > 0): ?>
                <div class="flex justify-between text-green-600">
                    <span>Discount</span>
                    <span>-<?= formatPrice($totals['discount']) ?></span>
                </div>
                <?php endif; ?>
                <div class="flex justify-between text-gray-600">
                    <span><?= $totals['tax_label'] ?></span>
                    <span><?= formatPrice($totals['tax']) ?></span>
                </div>
                <div class="flex justify-between text-gray-600">
                    <span><?= $totals['shipping_label'] ?></span>
                    <span><?= $totals['shipping'] > 0 ? formatPrice($totals['shipping']) : 'Free' ?></span>
                </div>
                <hr>
                <div class="flex justify-between font-bold text-gray-800 text-base">
                    <span>Total</span>
                    <span><?= formatPrice($totals['total']) ?></span>
                </div>
            </div>
            <input type="hidden" name="subtotal" value="<?= $totals['subtotal'] ?>">
            <input type="hidden" name="tax_amount" value="<?= $totals['tax'] ?>">
            <input type="hidden" name="shipping_amount" value="<?= $totals['shipping'] ?>">
            <input type="hidden" name="discount_amount" value="<?= $totals['discount'] ?>">
            <input type="hidden" name="total" value="<?= $totals['total'] ?>">
            <button type="button" id="place-order-btn" onclick="placeOrder()" class="w-full bg-primary-600 text-white py-3 rounded-lg font-semibold hover:bg-primary-700 transition mt-6">
                Place Order
            </button>
        </div>
    </form>
</div>

<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
function toggleRazorpay(show) {
    document.querySelectorAll('input[name="payment_method"]').forEach(r => {
        if (show) r.value === 'razorpay' ? r.checked = true : null;
        else r.value === 'cod' ? r.checked = true : null;
    });
}

async function placeOrder() {
    const btn = document.getElementById('place-order-btn');
    btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Processing...';

    const form = document.getElementById('checkout-form');
    const method = form.querySelector('input[name="payment_method"]:checked').value;
    const data = new URLSearchParams(new FormData(form));

    if (method === 'cod') {
        data.append('razorpay_payment_id', '');
        data.append('razorpay_order_id', '');
        try {
            const r = await fetch('<?= BASE_PATH ?>/api/order.php', { method: 'POST', body: data });
            const d = await r.json();
            if (d.success) window.location.href = d.redirect;
            else { alert(d.message); btn.disabled = false; btn.innerHTML = 'Place Order'; }
        } catch(e) {
            alert('Error placing order.'); btn.disabled = false; btn.innerHTML = 'Place Order';
        }
        return;
    }

    // Razorpay
    try {
        const r = await fetch('<?= BASE_PATH ?>/api/razorpay-order.php');
        const order = await r.json();
        if (!order.success) { alert(order.message); btn.disabled = false; btn.innerHTML = 'Place Order'; return; }

        const options = {
            key: order.razorpay_key_id,
            amount: order.amount,
            currency: order.currency,
            name: '<?= APP_NAME ?>',
            description: 'Order Payment',
            order_id: order.razorpay_order_id,
            prefill: { name: order.user_name, email: order.user_email },
            handler: async function(payment) {
                data.append('razorpay_payment_id', payment.razorpay_payment_id);
                data.append('razorpay_order_id', payment.razorpay_order_id);
                try {
                    const r = await fetch('<?= BASE_PATH ?>/api/order.php', { method: 'POST', body: data });
                    const d = await r.json();
                    if (d.success) window.location.href = d.redirect;
                    else { alert(d.message); btn.disabled = false; btn.innerHTML = 'Place Order'; }
                } catch(e) {
                    alert('Error placing order.'); btn.disabled = false; btn.innerHTML = 'Place Order';
                }
            },
            modal: { ondismiss: function() { btn.disabled = false; btn.innerHTML = 'Place Order'; } }
        };
        const rzp = new Razorpay(options);
        rzp.open();
    } catch(e) {
        alert('Could not initiate payment.'); btn.disabled = false; btn.innerHTML = 'Place Order';
    }
}

async function removeItem(itemId) {
    if (!confirm('Remove this item from checkout?')) return;
    try {
        await fetch('<?= BASE_PATH ?>/api/cart.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'action=update&item_id=' + itemId + '&quantity=0'
        });
        window.location.reload();
    } catch(e) {
        alert('Error removing item.');
    }
}
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
