<?php
require_once __DIR__ . '/config/database.php';
$settings = getAllSettings($pdo);

$error = '';
$items = $_SESSION['checkout_items'] ?? [];

// Handle order submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['place_order'])) {
    $name      = trim($_POST['customer_name'] ?? '');
    $phone     = trim($_POST['customer_phone'] ?? '');
    $address   = trim($_POST['customer_address'] ?? '');
    $insideDhaka = isset($_POST['inside_dhaka']) ? 1 : 0;
    $total     = (float)($_POST['total_amount'] ?? 0);
    $delivery  = (float)($_POST['delivery_charge'] ?? 0);

    // Re-read items from session (don't trust POST totals for security, recalculate)
    $items = $_SESSION['checkout_items'] ?? [];

    if (!$name || !$phone || !$address) {
        $error = '<div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> অনুগ্রহ করে সমস্ত তথ্য পূরণ করুন।</div>';
    } elseif (empty($items)) {
        $error = '<div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> কোনো পণ্য নেই।</div>';
    } else {
        // Recalculate server-side
        $subtotal = 0;
        foreach ($items as $item) $subtotal += $item['price'] * $item['quantity'];
        $deliveryCharge = $insideDhaka
            ? (float)($settings['inside_dhaka_charge'] ?? 60)
            : (float)($settings['outside_dhaka_charge'] ?? 120);
        $grandTotal = $subtotal + $deliveryCharge;

        $stockError = false;
        foreach ($items as $item) {
            $ps = $pdo->prepare("SELECT stock, name FROM products WHERE id = ?");
            $ps->execute([$item['product_id']]);
            $p = $ps->fetch();
            if (!$p || $p['stock'] < $item['quantity']) {
                $error = '<div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> "' . e($item['product_name']) . '" পণ্যের পর্যাপ্ত স্টক নেই।</div>';
                $stockError = true;
                break;
            }
        }

        if (!$stockError) {
            $pdo->beginTransaction();
            try {
                $userId = isLoggedIn() ? $_SESSION['user_id'] : null;
                $ins = $pdo->prepare("INSERT INTO orders (user_id, customer_name, customer_phone, customer_address, inside_dhaka, total_amount, delivery_charge, status) VALUES (?,?,?,?,?,?,?,'pending')");
                $ins->execute([$userId, $name, $phone, $address, $insideDhaka, $grandTotal, $deliveryCharge]);
                $orderId = $pdo->lastInsertId();

                foreach ($items as $item) {
                    $insItem = $pdo->prepare("INSERT INTO order_items (order_id, product_id, variation_info, quantity, price) VALUES (?,?,?,?,?)");
                    $insItem->execute([$orderId, $item['product_id'], $item['variation_info'], $item['quantity'], $item['price']]);
                    $pdo->prepare("UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?")->execute([$item['quantity'], $item['product_id'], $item['quantity']]);
                }

                $pdo->commit();
                unset($_SESSION['checkout_items']);
                redirect(BASE_URL . '/thankyou.php?order_id=' . $orderId);
            } catch (Exception $e) {
                $pdo->rollBack();
                $error = '<div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> অর্ডার প্রক্রিয়াকরণে সমস্যা হয়েছে। আবার চেষ্টা করুন।</div>';
            }
        }
    }
}

// Reload items after possible session changes
$items = $_SESSION['checkout_items'] ?? [];
$insideDhakaCharge  = (float)($settings['inside_dhaka_charge'] ?? 60);
$outsideDhakaCharge = (float)($settings['outside_dhaka_charge'] ?? 120);
$dhakaCheckboxEnabled = ($settings['dhaka_checkbox_enabled'] ?? '1') == '1';

$subtotal = 0;
foreach ($items as $item) $subtotal += $item['price'] * $item['quantity'];
$delivery = $outsideDhakaCharge;
$total    = $subtotal + $delivery;

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

<style>
/* ===== CHECKOUT MOBILE IMPROVEMENTS ===== */
.checkout-grid { display:grid; grid-template-columns:1fr 360px; gap:24px; align-items:start; }
@media(max-width:860px){
    .checkout-grid { grid-template-columns:1fr; }
    .order-summary-sticky { position:static !important; }
}
.order-item { display:flex; gap:12px; padding:14px 0; border-bottom:1px solid var(--gray-100); align-items:flex-start; }
.order-item:last-child { border-bottom:none; }
.order-item-img { width:64px; height:64px; object-fit:cover; border-radius:8px; background:var(--gray-100); flex-shrink:0; }
.qty-controls { display:flex; align-items:center; gap:8px; margin-top:8px; }
.qty-btn { width:32px; height:32px; border:1.5px solid var(--gray-200); background:white; border-radius:6px; font-size:1.1rem; cursor:pointer; display:flex; align-items:center; justify-content:center; font-weight:700; color:var(--navy); transition:all .2s; user-select:none; }
.qty-btn:hover { background:var(--navy); color:white; border-color:var(--navy); }
.qty-num { min-width:36px; text-align:center; font-weight:700; font-size:1rem; color:var(--navy); }
.remove-item { background:none; border:none; color:var(--danger); cursor:pointer; padding:4px 6px; border-radius:4px; transition:all .2s; }
.remove-item:hover { background:rgba(229,62,62,.1); }
</style>

<div class="checkout-page">
    <div class="container">
        <h1 class="page-title">চেকআউট</h1>
        <p class="page-subtitle">আপনার পণ্য পর্যালোচনা করুন এবং অর্ডার সম্পন্ন করুন</p>

        <?= $error ?>

        <?php if (empty($items)): ?>
            <div class="empty-cart">
                <i class="fas fa-shopping-bag"></i>
                <p>আপনার চেকআউট তালিকা খালি।</p>
                <a href="<?= BASE_URL ?>/index.php" class="btn-primary" style="display:inline-block;width:auto;padding:12px 28px;margin-top:16px;">শপিং করুন</a>
            </div>
        <?php else: ?>
        <form method="POST" id="orderForm">
            <div class="checkout-grid">
                <!-- LEFT COLUMN -->
                <div>
                    <!-- Items -->
                    <div class="checkout-card">
                        <h2><i class="fas fa-shopping-bag"></i> আপনার পণ্য</h2>
                        <div id="checkoutItems">
                            <?php foreach ($items as $idx => $item): ?>
                            <div class="order-item" id="item-<?= $idx ?>" data-idx="<?= $idx ?>" data-price="<?= (float)$item['price'] ?>">
                                <?php if (!empty($item['product_image'])): ?>
                                    <img src="<?= UPLOADS_URL . e($item['product_image']) ?>" alt="" class="order-item-img">
                                <?php else: ?>
                                    <div class="order-item-img" style="display:flex;align-items:center;justify-content:center;color:var(--gray-400);font-size:1.4rem;"><i class="fas fa-image"></i></div>
                                <?php endif; ?>

                                <div class="order-item-info" style="flex:1;">
                                    <div class="order-item-name"><?= e($item['product_name']) ?></div>
                                    <?php if (!empty($item['variation_info'])): ?>
                                        <div class="order-item-var"><i class="fas fa-tag"></i> <?= e($item['variation_info']) ?></div>
                                    <?php endif; ?>
                                    <div class="qty-controls">
                                        <button type="button" class="qty-btn" onclick="changeItemQty(<?= $idx ?>, -1)" aria-label="কমান">−</button>
                                        <span class="qty-num" id="qty-<?= $idx ?>"><?= (int)$item['quantity'] ?></span>
                                        <button type="button" class="qty-btn" onclick="changeItemQty(<?= $idx ?>, 1)" aria-label="বাড়ান">+</button>
                                        <span style="color:var(--gray-400);font-size:0.82rem;margin-left:4px;">× ৳<?= number_format($item['price'], 2) ?></span>
                                    </div>
                                </div>

                                <div style="display:flex;flex-direction:column;align-items:flex-end;gap:8px;flex-shrink:0;">
                                    <div class="item-total" id="itotal-<?= $idx ?>">৳<?= number_format($item['price'] * $item['quantity'], 2) ?></div>
                                    <button type="button" class="remove-item" onclick="removeItem(<?= $idx ?>)" title="সরান">
                                        <i class="fas fa-trash-alt"></i>
                                    </button>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Delivery Form -->
                    <div class="checkout-card" style="margin-top:20px;">
                        <h2><i class="fas fa-map-marker-alt"></i> ডেলিভারি তথ্য</h2>
                        <div class="form-group">
                            <label class="form-label">পূর্ণ নাম *</label>
                            <input type="text" class="form-control" name="customer_name"
                                   placeholder="আপনার পুরো নাম লিখুন"
                                   value="<?= isLoggedIn() ? e($_SESSION['user_name'] ?? '') : '' ?>" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">মোবাইল নম্বর *</label>
                            <input type="tel" class="form-control" name="customer_phone"
                                   placeholder="০১XXXXXXXXX"
                                   value="<?= isLoggedIn() ? e($_SESSION['user_phone'] ?? '') : '' ?>" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">পূর্ণ ঠিকানা *</label>
                            <textarea class="form-control" name="customer_address" rows="3"
                                      placeholder="বাসা নম্বর, রাস্তা, এলাকা, জেলা" required><?= isLoggedIn() ? e($_SESSION['user_address'] ?? '') : '' ?></textarea>
                        </div>

                        <?php if ($dhakaCheckboxEnabled): ?>
                        <label class="dhaka-checkbox" style="cursor:pointer;">
                            <input type="checkbox" name="inside_dhaka" id="insideDhaka" value="1" onchange="recalcTotal()">
                            <span>✅ ঢাকার ভিতরে ডেলিভারি (৳<?= $insideDhakaCharge ?>)</span>
                        </label>
                        <?php else: ?>
                        <input type="hidden" name="inside_dhaka" value="0">
                        <?php endif; ?>
                    </div>
                </div>

                <!-- RIGHT: Summary -->
                <div class="order-summary-sticky" style="position:sticky;top:80px;">
                    <div class="checkout-card">
                        <h2><i class="fas fa-receipt"></i> অর্ডার সারসংক্ষেপ</h2>
                        <div class="order-summary">
                            <div class="summary-row">
                                <span>পণ্যের মূল্য</span>
                                <span id="subtotalDisplay">৳<?= number_format($subtotal, 2) ?></span>
                            </div>
                            <div class="summary-row">
                                <span>ডেলিভারি চার্জ</span>
                                <span id="deliveryDisplay">৳<?= number_format($delivery, 2) ?></span>
                            </div>
                            <div class="summary-row total">
                                <span>মোট পরিমাণ</span>
                                <span id="totalDisplay">৳<?= number_format($total, 2) ?></span>
                            </div>
                        </div>

                        <input type="hidden" name="total_amount"    id="hiddenTotal"    value="<?= $total ?>">
                        <input type="hidden" name="delivery_charge" id="hiddenDelivery" value="<?= $delivery ?>">

                        <div style="background:rgba(212,175,55,.1);border-radius:8px;padding:12px;margin:14px 0;font-size:0.87rem;color:var(--gray-600);">
                            <i class="fas fa-info-circle" style="color:var(--gold);"></i>
                            পেমেন্ট: ক্যাশ অন ডেলিভারি
                        </div>

                        <button type="submit" name="place_order" class="btn-order">
                            <i class="fas fa-check-circle"></i> অর্ডার করুন
                        </button>
                    </div>
                </div>
            </div>
        </form>
        <?php endif; ?>
    </div>
</div>

<script>
// ====== CHECKOUT QUANTITIES ======
const INSIDE_CHARGE  = <?= $insideDhakaCharge ?>;
const OUTSIDE_CHARGE = <?= $outsideDhakaCharge ?>;

// Live item quantities (JS mirror of session)
const itemData = {
    <?php foreach ($items as $idx => $item): ?>
    <?= $idx ?>: { qty: <?= (int)$item['quantity'] ?>, price: <?= (float)$item['price'] ?> },
    <?php endforeach; ?>
};

function changeItemQty(idx, delta) {
    if (!itemData[idx]) return;
    let newQty = itemData[idx].qty + delta;
    if (newQty < 1) newQty = 1;

    itemData[idx].qty = newQty;

    // Update display
    const qtyEl = document.getElementById('qty-' + idx);
    if (qtyEl) qtyEl.textContent = newQty;

    // Update item total
    const itotalEl = document.getElementById('itotal-' + idx);
    if (itotalEl) itotalEl.textContent = '৳' + (itemData[idx].price * newQty).toFixed(2);

    // Send to server
    fetch('<?= BASE_URL ?>/checkout-update.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'idx=' + idx + '&qty=' + newQty
    });

    recalcTotal();
}

function removeItem(idx) {
    if (!confirm('এই পণ্যটি সরাবেন?')) return;

    const el = document.getElementById('item-' + idx);
    if (el) el.remove();
    delete itemData[idx];

    // Send to server
    fetch('<?= BASE_URL ?>/checkout-update.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'idx=' + idx + '&qty=0'
    });

    recalcTotal();

    // Show empty state if no items
    if (Object.keys(itemData).length === 0) {
        document.getElementById('checkoutItems').innerHTML =
            '<div class="empty-cart" style="padding:40px 0;text-align:center;">' +
            '<i class="fas fa-shopping-bag" style="font-size:3rem;color:var(--gray-400);"></i>' +
            '<p style="margin:16px 0;">কোনো পণ্য নেই।</p>' +
            '<a href="<?= BASE_URL ?>/index.php" class="btn-primary" style="display:inline-block;width:auto;padding:10px 24px;">শপিং করুন</a></div>';
        // Update cart count badge
        const badge = document.querySelector('.cart-count');
        if (badge) badge.style.display = 'none';
    } else {
        // Update header cart count
        let total = 0;
        Object.values(itemData).forEach(d => total += d.qty);
        const badge = document.querySelector('.cart-count');
        if (badge) { badge.textContent = total; badge.style.display = 'flex'; }
    }
}

function recalcTotal() {
    let subtotal = 0;
    Object.values(itemData).forEach(d => subtotal += d.price * d.qty);

    const dhakaEl = document.getElementById('insideDhaka');
    const isInside = dhakaEl && dhakaEl.checked;
    const delivery = isInside ? INSIDE_CHARGE : OUTSIDE_CHARGE;
    const grand    = subtotal + delivery;

    document.getElementById('subtotalDisplay').textContent = '৳' + subtotal.toFixed(2);
    document.getElementById('deliveryDisplay').textContent = '৳' + delivery.toFixed(2);
    document.getElementById('totalDisplay').textContent    = '৳' + grand.toFixed(2);
    document.getElementById('hiddenTotal').value           = grand.toFixed(2);
    document.getElementById('hiddenDelivery').value        = delivery.toFixed(2);
}
</script>

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