<?php
require_once __DIR__ . '/config/database.php';
$settings = getAllSettings($pdo);
$error    = '';
$items    = $_SESSION['checkout_items'] ?? [];

// ── Place Order ──────────────────────────────────────────────
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;
    $couponId  = (int)($_POST['coupon_id']       ?? 0);
    $discount  = (float)($_POST['discount_amount']?? 0);
    $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 {
        $subtotal = 0;
        foreach($items as $it) $subtotal += $it['price']*$it['quantity'];
        $deliveryCharge = $insideDhaka
            ? (float)($settings['inside_dhaka_charge']??60)
            : (float)($settings['outside_dhaka_charge']??120);
        $grandTotal = max(0, $subtotal - $discount + $deliveryCharge);

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

        if (!$stockErr) {
            $pdo->beginTransaction();
            try {
                $uid = 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([$uid,$name,$phone,$address,$insideDhaka,$grandTotal,$deliveryCharge]);
                $oid = $pdo->lastInsertId();

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

                // Increment coupon usage
                if ($couponId) {
                    $pdo->prepare("UPDATE coupons SET used_count=used_count+1 WHERE id=?")->execute([$couponId]);
                }

                $pdo->commit();
                unset($_SESSION['checkout_items'], $_SESSION['applied_coupon']);
                redirect(BASE_URL.'/thankyou.php?order_id='.$oid);
            } catch(Exception $e){
                $pdo->rollBack();
                $error='<div class="alert alert-error">অর্ডার প্রক্রিয়াকরণে সমস্যা হয়েছে।</div>';
            }
        }
    }
}

$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 $it) $subtotal += $it['price']*$it['quantity'];
$delivery = $outsideDhakaCharge;
$total    = $subtotal + $delivery;

include __DIR__ . '/includes/header.php';
?>
<style>
.checkout-grid{display:grid;grid-template-columns:1fr;gap:20px}
@media(min-width:860px){.checkout-grid{grid-template-columns:1fr 360px}}
.coupon-box{background:linear-gradient(135deg,rgba(26,42,79,.04),rgba(212,175,55,.06));border:1.5px dashed var(--gold);border-radius:var(--r);padding:16px;margin-bottom:16px}
.coupon-box h4{font-size:.95rem;font-weight:700;color:var(--navy);margin-bottom:10px}
.coupon-input-row{display:flex;gap:8px;}
.coupon-input{flex:1;padding:10px 13px;border:1.5px solid var(--g200);border-radius:var(--r);font-family:var(--font);font-size:.9rem;text-transform:uppercase;letter-spacing:1px}
.coupon-input:focus{outline:none;border-color:var(--gold)}
.coupon-apply-btn{padding:10px 18px;background:var(--navy);color:var(--gold);border:none;border-radius:var(--r);font-family:var(--font);font-weight:700;font-size:.88rem;cursor:pointer;white-space:nowrap;transition:var(--tr)}
.coupon-apply-btn:hover{background:var(--gold);color:var(--navy)}
.coupon-applied{display:flex;align-items:center;justify-content:space-between;background:rgba(56,161,105,.1);border:1px solid rgba(56,161,105,.25);border-radius:var(--r);padding:10px 14px;font-size:.88rem}
.coupon-applied .code-tag{font-family:monospace;font-weight:700;color:#276749;font-size:.95rem;letter-spacing:1px}
.coupon-remove{background:none;border:none;color:var(--danger);cursor:pointer;font-size:1rem;padding:2px 5px}
.discount-row{color:var(--success)!important;font-weight:600}
</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:11px 26px;margin-top:14px;">শপিং করুন</a>
    </div>
    <?php else: ?>
    <form method="POST" id="orderForm">
        <div class="checkout-grid">

            <!-- LEFT -->
            <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'])?>" class="order-item-img" alt="">
                        <?php else: ?>
                            <div class="order-item-img" style="display:flex;align-items:center;justify-content:center;color:var(--g400);"><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)">−</button>
                                <span class="qty-num" id="qty-<?=$idx?>"><?=(int)$item['quantity']?></span>
                                <button type="button" class="qty-btn" onclick="changeItemQty(<?=$idx?>,1)">+</button>
                                <span style="color:var(--g400);font-size:.8rem;">× ৳<?=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:16px;">
                    <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">
                        <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 style="position:sticky;top:72px;height:fit-content;">
                <div class="checkout-card">
                    <h2><i class="fas fa-receipt"></i> অর্ডার সারসংক্ষেপ</h2>

                    <!-- Coupon Section -->
                    <div class="coupon-box">
                        <h4><i class="fas fa-ticket-alt" style="color:var(--gold);"></i> কুপন কোড</h4>
                        <div id="couponInput">
                            <div class="coupon-input-row">
                                <input type="text" id="couponCode" class="coupon-input" placeholder="কুপন কোড লিখুন..." maxlength="30">
                                <button type="button" class="coupon-apply-btn" onclick="applyCoupon()">প্রয়োগ করুন</button>
                            </div>
                            <div id="couponMsg" style="font-size:.82rem;margin-top:8px;"></div>
                        </div>
                        <div id="couponApplied" style="display:none;">
                            <div class="coupon-applied">
                                <span>🎉 <span class="code-tag" id="appliedCode"></span> প্রয়োগ হয়েছে!</span>
                                <button type="button" class="coupon-remove" onclick="removeCoupon()" title="সরান"><i class="fas fa-times-circle"></i></button>
                            </div>
                        </div>
                    </div>

                    <!-- Hidden coupon fields -->
                    <input type="hidden" name="coupon_id"       id="hiddenCouponId"  value="0">
                    <input type="hidden" name="discount_amount" id="hiddenDiscount"   value="0">
                    <input type="hidden" name="total_amount"    id="hiddenTotal"      value="<?=$total?>">
                    <input type="hidden" name="delivery_charge" id="hiddenDelivery"   value="<?=$delivery?>">

                    <!-- Summary rows -->
                    <div class="summary-row"><span>পণ্যের মূল্য</span><span id="subtotalDisplay">৳<?=number_format($subtotal,2)?></span></div>
                    <div class="summary-row" id="discountRow" style="display:none;">
                        <span style="color:var(--success);">ডিসকাউন্ট</span>
                        <span id="discountDisplay" style="color:var(--success);">−৳0.00</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 style="background:rgba(212,175,55,.1);border-radius:var(--r);padding:11px;margin:12px 0;font-size:.85rem;color:var(--g600);">
                        <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>
const INSIDE_CHARGE  = <?= $insideDhakaCharge ?>;
const OUTSIDE_CHARGE = <?= $outsideDhakaCharge ?>;
const BASE_URL_JS    = '<?= BASE_URL ?>';

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

let appliedDiscount = 0;
let appliedCouponId = 0;

function changeItemQty(idx, delta) {
    if (!itemData[idx]) return;
    let q = itemData[idx].qty + delta;
    if (q < 1) q = 1;
    itemData[idx].qty = q;
    document.getElementById('qty-'+idx).textContent = q;
    document.getElementById('itotal-'+idx).textContent = '৳'+(itemData[idx].price*q).toFixed(2);
    fetch(BASE_URL_JS+'/checkout-update.php',{
        method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'idx='+idx+'&qty='+q
    });
    recalcTotal();
}

function removeItem(idx) {
    if(!confirm('এই পণ্যটি সরাবেন?')) return;
    document.getElementById('item-'+idx)?.remove();
    delete itemData[idx];
    fetch(BASE_URL_JS+'/checkout-update.php',{
        method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'idx='+idx+'&qty=0'
    });
    recalcTotal();
    if(Object.keys(itemData).length===0){
        document.getElementById('checkoutItems').innerHTML='<div class="empty-cart" style="padding:32px 0;text-align:center;"><i class="fas fa-shopping-bag" style="font-size:2.5rem;color:var(--g400);display:block;margin-bottom:10px;"></i><p>তালিকা খালি।</p></div>';
    }
}

function recalcTotal() {
    let sub=0;
    Object.values(itemData).forEach(d=>sub+=d.price*d.qty);
    const inside = document.getElementById('insideDhaka');
    const del = (inside&&inside.checked)?INSIDE_CHARGE:OUTSIDE_CHARGE;
    const discount = appliedDiscount;
    const grand = Math.max(0, sub - discount + del);

    document.getElementById('subtotalDisplay').textContent='৳'+sub.toFixed(2);
    document.getElementById('deliveryDisplay').textContent='৳'+del.toFixed(2);
    document.getElementById('totalDisplay').textContent='৳'+grand.toFixed(2);
    document.getElementById('hiddenTotal').value=grand.toFixed(2);
    document.getElementById('hiddenDelivery').value=del.toFixed(2);

    // Show/hide discount row
    const dRow=document.getElementById('discountRow');
    if(discount>0){
        dRow.style.display='flex';
        document.getElementById('discountDisplay').textContent='−৳'+discount.toFixed(2);
    } else {
        dRow.style.display='none';
    }
    // Update coupon applied subtotal for coupon revalidation
    return sub;
}

function applyCoupon() {
    const code = document.getElementById('couponCode').value.trim().toUpperCase();
    const msgEl = document.getElementById('couponMsg');
    if(!code){msgEl.innerHTML='<span style="color:var(--danger);">কুপন কোড লিখুন।</span>';return;}

    const sub = recalcTotal();
    msgEl.innerHTML='<span style="color:var(--g400);">যাচাই করা হচ্ছে...</span>';

    fetch(BASE_URL_JS+'/coupon-check.php',{
        method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'code='+encodeURIComponent(code)+'&subtotal='+sub
    })
    .then(r=>r.json())
    .then(data=>{
        if(data.success){
            appliedDiscount = data.discount;
            appliedCouponId = data.coupon_id;
            document.getElementById('hiddenCouponId').value = data.coupon_id;
            document.getElementById('hiddenDiscount').value = data.discount;
            document.getElementById('appliedCode').textContent = code;
            document.getElementById('couponInput').style.display='none';
            document.getElementById('couponApplied').style.display='block';
            msgEl.innerHTML='';
            recalcTotal();
        } else {
            msgEl.innerHTML='<span style="color:var(--danger);"><i class="fas fa-times-circle"></i> '+data.msg+'</span>';
        }
    })
    .catch(()=>{msgEl.innerHTML='<span style="color:var(--danger);">সংযোগ সমস্যা।</span>';});
}

function removeCoupon() {
    appliedDiscount=0; appliedCouponId=0;
    document.getElementById('hiddenCouponId').value=0;
    document.getElementById('hiddenDiscount').value=0;
    document.getElementById('couponCode').value='';
    document.getElementById('couponMsg').innerHTML='';
    document.getElementById('couponInput').style.display='block';
    document.getElementById('couponApplied').style.display='none';
    recalcTotal();
}

// Enter key on coupon input
document.getElementById('couponCode')?.addEventListener('keydown',function(e){
    if(e.key==='Enter'){e.preventDefault();applyCoupon();}
});

recalcTotal();
</script>
<?php include __DIR__ . '/includes/footer.php'; ?>
