<?php

namespace Core\App\Controllers;

use Core\App\Models\ProductModel;
use Core\System\ThemeManager;

/**
 * Standalone order form for landing pages.
 * Mirrors the public product checkout as closely as possible.
 */
class LandingOrderFormController
{
    public function form(int $productId): void
    {
        $product = (new ProductModel())->getById($productId);
        if (!$product) {
            http_response_code(404);
            echo '<p style="font-family:sans-serif;padding:20px;">Product not found</p>';
            exit;
        }

        $currency = ThemeManager::getSetting('currency', 'DA');
        $price = (float)($product['price'] ?? 0);
        $salePrice = (float)($product['sale_price'] ?? 0);
        $now = date('Y-m-d H:i:s');
        $finalPrice = $price;
        $hasDiscount = false;

        $discountType  = $product['discount_type'] ?? null;
        $discountValue = (float)($product['discount_value'] ?? 0);
        $discountStart = $product['discount_start'] ?? null;
        $discountEnd   = $product['discount_end'] ?? null;

        if (
            $discountType &&
            $discountValue > 0 &&
            $discountStart &&
            $discountEnd &&
            $now >= $discountStart &&
            $now <= $discountEnd
        ) {
            if ($discountType === 'fixed') {
                $finalPrice = max(0, $price - $discountValue);
                $hasDiscount = true;
            } elseif ($discountType === 'percent') {
                $finalPrice = max(0, $price - ($price * ($discountValue / 100)));
                $hasDiscount = true;
            }
        }

        if (!$hasDiscount && $salePrice > 0 && $salePrice < $price) {
            $finalPrice = $salePrice;
            $hasDiscount = true;
        }

        $variants = [];
        if (isset($product['variants'])) {
            if (is_string($product['variants'])) {
                $variants = json_decode($product['variants'], true) ?: [];
            } elseif (is_array($product['variants'])) {
                $variants = $product['variants'];
            }
        }

        $sizes = (isset($variants['sizes']) && is_array($variants['sizes'])) ? $variants['sizes'] : [];
        $colors = (isset($variants['colors']) && is_array($variants['colors'])) ? $variants['colors'] : [];
        $pName = htmlspecialchars($product['title'] ?? '', ENT_QUOTES, 'UTF-8');

        $theme = ($_GET['theme'] ?? 'dark') === 'light' ? 'light' : 'dark';
        $accent = preg_replace('/[^0-9a-fA-F]/', '', $_GET['color'] ?? 'f59e0b');
        if (strlen($accent) < 3) {
            $accent = 'f59e0b';
        }
        $accentHex = '#' . $accent;

        // Parse ?hide=city,wilaya,address  (comma-separated field names)
        // Supported tokens: city | commune | wilaya | state | address | qty | quantity | shipping
        $hideRaw    = strtolower((string)($_GET['hide'] ?? ''));
        $hideTokens = array_filter(array_map('trim', explode(',', $hideRaw)));
        $hideCity     = !empty(array_intersect($hideTokens, ['city', 'commune', 'bledia', 'municipality']));
        $hideWilaya   = !empty(array_intersect($hideTokens, ['wilaya', 'state', 'province']));
        $hideAddress  = !empty(array_intersect($hideTokens, ['address', 'addr']));
        $hideQty      = !empty(array_intersect($hideTokens, ['qty', 'quantity']));
        $hideShipping = !empty(array_intersect($hideTokens, ['shipping', 'delivery_type']));
        // If city hidden but wilaya required, we still need state for shipping calculation
        // If wilaya is hidden too, city must also be hidden
        if ($hideWilaya) {
            $hideCity = true;
        }

        if ($theme === 'light') {
            [$bg, $card, $inp, $brd, $txt, $mut, $lbl] = ['#fff', '#f8fafc', '#fff', '#d1d5db', '#111827', '#6b7280', '#374151'];
        } else {
            [$bg, $card, $inp, $brd, $txt, $mut, $lbl] = ['#1a1f2e', '#242938', '#2d3347', '#3d4461', '#f1f5f9', '#94a3b8', '#cbd5e1'];
        }

        header('Content-Type: text/html; charset=utf-8');
        header('X-Frame-Options: SAMEORIGIN');
        ?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Cairo',system-ui,sans-serif;background:<?=$bg?>;color:<?=$txt?>;padding:16px}
.w{max-width:560px;margin:0 auto}
h2.ttl{font-size:1.5rem;font-weight:800;text-align:center;margin-bottom:4px}
p.sub{font-size:.85rem;color:<?=$mut?>;text-align:center;margin-bottom:18px}
.grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px}
@media(max-width:500px){.grid{grid-template-columns:1fr}}
.full{grid-column:1/-1}
label.lbl{display:block;font-size:.76rem;font-weight:700;color:<?=$lbl?>;margin-bottom:4px}
label.lbl .r{color:<?=$accentHex?>}
.inp{width:100%;padding:11px 13px;background:<?=$inp?>;border:1.5px solid <?=$brd?>;border-radius:10px;color:<?=$txt?>;font-family:'Cairo',sans-serif;font-size:.88rem;outline:none;transition:border-color .15s;-webkit-appearance:none;appearance:none}
.inp:focus{border-color:<?=$accentHex?>}
.inp::placeholder{color:<?=$mut?>}
select.inp{cursor:pointer}
select.inp option{background:<?=$inp?>;color:<?=$txt?>}
.phone-row{display:flex;gap:8px}
.pfx{display:flex;align-items:center;gap:5px;padding:0 11px;background:<?=$inp?>;border:1.5px solid <?=$brd?>;border-radius:10px;font-size:.85rem;font-weight:700;color:<?=$txt?>;white-space:nowrap;flex-shrink:0}
.phone-row .inp{flex:1;min-width:0}
.qty{display:flex;align-items:center;justify-content:center;gap:10px;margin:8px 0 14px}
.qty button{width:40px;height:40px;border:none;border-radius:10px;background:<?=$accentHex?>;color:#fff;font-size:22px;font-weight:700;cursor:pointer}
.qty input{width:76px;text-align:center;background:<?=$inp?>;border:1.5px solid <?=$brd?>;border-radius:10px;color:<?=$txt?>;font-weight:800;font-size:1rem;padding:9px}
.summary{background:<?=$card?>;border:1px solid <?=$brd?>;border-radius:12px;padding:14px 16px;margin:4px 0 14px}
.row{display:flex;justify-content:space-between;align-items:center;padding:5px 0;font-size:.88rem;gap:12px}
.row .k{color:<?=$mut?>;font-weight:600}
.row .v{color:<?=$txt?>;font-weight:700}
.row.tot{border-top:1px solid <?=$brd?>;margin-top:6px;padding-top:10px}
.row.tot .v{color:<?=$accentHex?>;font-size:1.05rem}
.old-price{text-decoration:line-through;opacity:.65;font-size:.84rem;margin-inline-start:6px}
.btn{width:100%;padding:13px;background:<?=$accentHex?>;border:none;border-radius:12px;color:#fff;font-family:'Cairo',sans-serif;font-size:.95rem;font-weight:800;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;transition:filter .15s,transform .1s}
.btn:hover{filter:brightness(1.1)}
.btn:active{transform:scale(.98)}
.btn:disabled{opacity:.55;cursor:not-allowed}
.msg{padding:11px 14px;border-radius:10px;font-size:.86rem;text-align:center;margin-top:10px;display:none}
.msg.ok{background:rgba(16,185,129,.15);color:#10b981;border:1px solid rgba(16,185,129,.3)}
.msg.er{background:rgba(239,68,68,.15);color:#ef4444;border:1px solid rgba(239,68,68,.3)}
</style>
</head>
<body>
<div class="w" id="lp-order-root">
<h2 class="ttl">املأ بياناتك للطلب</h2>
<p class="sub">سنتصل بك خلال دقائق لتأكيد طلبك وشحنه فوراً.</p>

<form id="F" novalidate>
    <?= \Core\System\Csrf::field(); ?>
    <input type="hidden" name="product_id" value="<?=(int)$product['id']?>">
    <input type="hidden" name="quantity" id="h-qty" value="1">
    <input type="hidden" name="total_amount" id="h-tot" value="<?= (int)$finalPrice ?>">
    <input type="hidden" name="shipping_price" id="h-ship" value="0">
    <input type="hidden" name="state_code" id="h-sc" value="">
    <input type="hidden" name="state_name" id="h-sn" value="">
    <input type="hidden" name="city_id" id="h-ci" value="">
    <input type="hidden" name="city_name" id="h-cn" value="">
    <input type="hidden" name="shipping_type" id="h-st" value="home">
    <input type="hidden" name="variant_size" id="h-vs" value="">
    <input type="hidden" name="variant_color" id="h-vc" value="">
    <input type="hidden" name="variant_color_code" id="h-vcc" value="">

    <div class="grid">
        <div>
            <label class="lbl">الاسم واللقب <span class="r">*</span></label>
            <input type="text" name="full_name" class="inp" placeholder="أدخل اسمك الكامل" required>
        </div>

        <div>
            <label class="lbl">رقم الهاتف <span class="r">*</span></label>
            <div class="phone-row">
                <span class="pfx">🇩🇿 +213</span>
                <input type="tel" name="phone" class="inp" placeholder="0551 23 45 67" required>
            </div>
        </div>

        <?php if (!empty($sizes)): ?>
        <div>
            <label class="lbl">المقاس <span class="r">*</span></label>
            <select id="sel-size" class="inp" required>
                <option value="">اختر المقاس</option>
                <?php foreach ($sizes as $size): $val = trim((string)($size['value'] ?? '')); if ($val === '') continue; ?>
                    <option value="<?= htmlspecialchars($val, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($val, ENT_QUOTES, 'UTF-8') ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>

        <?php if (!empty($colors)): ?>
        <div>
            <label class="lbl">اللون <span class="r">*</span></label>
            <select id="sel-color" class="inp" required>
                <option value="">اختر اللون</option>
                <?php foreach ($colors as $color):
                    $name = trim((string)($color['name'] ?? ''));
                    $code = trim((string)($color['code'] ?? ''));
                    if ($name === '' && $code === '') continue;
                    $label = $name !== '' ? $name : $code;
                ?>
                    <option value="<?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?>" data-color-name="<?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?>" data-color-code="<?= htmlspecialchars($code, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>

        <?php if (!$hideWilaya): ?>
        <div>
            <label class="lbl">الولاية <span class="r">*</span></label>
            <select id="sel-w" class="inp" <?= $hideWilaya ? '' : 'required' ?>>
                <option value="">اختر ولايتك</option>
            </select>
        </div>
        <?php endif; ?>

        <?php if (!$hideCity): ?>
        <div>
            <label class="lbl">البلدية <?= $hideWilaya ? '' : '<span class="r">*</span>' ?></label>
            <select id="sel-c" class="inp" disabled <?= ($hideWilaya || $hideCity) ? '' : 'required' ?>>
                <option value="">اختر البلدية</option>
            </select>
        </div>
        <?php endif; ?>

        <?php if (!$hideShipping): ?>
        <div>
            <label class="lbl">نوع التوصيل <span class="r">*</span></label>
            <select id="sel-st" class="inp" required>
                <option value="home">توصيل منزلي</option>
                <option value="desk">استلام من المكتب</option>
            </select>
        </div>
        <?php endif; ?>

        <?php if (!$hideAddress): ?>
        <div class="full">
            <label class="lbl">العنوان التفصيلي</label>
            <input type="text" name="address_extra" class="inp" placeholder="الحي، الشارع، الرقم... (اختياري)">
        </div>
        <?php endif; ?>
    </div>

    <?php if (!$hideQty): ?>
    <div class="qty">
        <button type="button" id="qty-plus">+</button>
        <input type="text" id="qty-val" value="1" readonly>
        <button type="button" id="qty-minus">−</button>
    </div>
    <?php endif; ?>

    <div class="summary">
        <div class="row">
            <span class="k">المنتج</span>
            <span class="v" style="font-size:.82rem;max-width:55%;text-align:left"><?=$pName?></span>
        </div>
        <div class="row">
            <span class="k">سعر القطعة</span>
            <span class="v">
                <span id="s-pu"><?= number_format((float)$finalPrice, 0, '.', ',') ?> <?= htmlspecialchars($currency, ENT_QUOTES, 'UTF-8') ?></span>
                <?php if ($hasDiscount): ?>
                    <span class="old-price"><?= number_format((float)$price, 0, '.', ',') ?> <?= htmlspecialchars($currency, ENT_QUOTES, 'UTF-8') ?></span>
                <?php endif; ?>
            </span>
        </div>
        <div class="row">
            <span class="k">سعر المنتجات</span>
            <span class="v" id="s-p"><?= number_format((float)$finalPrice, 0, '.', ',') ?> <?= htmlspecialchars($currency, ENT_QUOTES, 'UTF-8') ?></span>
        </div>
        <div class="row">
            <span class="k">التوصيل</span>
            <span class="v" id="s-sh" style="color:<?=$mut?>">اختر الولاية أولاً</span>
        </div>
        <div class="row tot">
            <span class="k" style="font-size:.95rem;">المجموع</span>
            <span class="v" id="s-tt"><?= number_format((float)$finalPrice, 0, '.', ',') ?> <?= htmlspecialchars($currency, ENT_QUOTES, 'UTF-8') ?></span>
        </div>
    </div>

    <div id="msg" class="msg"></div>

    <button type="submit" class="btn" id="btn">
        ✅ <span id="bl">تأكيد الطلب — <?= number_format((float)$finalPrice, 0, '.', ',') ?> <?= htmlspecialchars($currency, ENT_QUOTES, 'UTF-8') ?></span>
    </button>
</form>
</div>

<script>
const PRICE = <?= json_encode((float)$finalPrice) ?>;
const CURRENCY = <?= json_encode($currency) ?>;
const HIDE_CITY     = <?= $hideCity     ? 'true' : 'false' ?>;
const HIDE_WILAYA   = <?= $hideWilaya   ? 'true' : 'false' ?>;
const HIDE_SHIPPING = <?= $hideShipping ? 'true' : 'false' ?>;
const HIDE_QTY      = <?= $hideQty      ? 'true' : 'false' ?>;
let shipCost = 0;

const $ = id => document.getElementById(id);
function fmt(n){ return Number(n || 0).toLocaleString('ar-DZ') + ' ' + CURRENCY; }
function qty(){ return Math.max(1, parseInt(($('qty-val')?.value || '1'), 10) || 1); }

function updateSummary(){
    const q = qty();
    const productsTotal = PRICE * q;
    const total = productsTotal + shipCost;
    $('h-qty').value = q;
    $('h-tot').value = total;
    $('h-ship').value = shipCost;
    $('s-p').textContent = fmt(productsTotal);
    $('s-tt').textContent = fmt(total);
    $('bl').textContent = 'تأكيد الطلب — ' + fmt(total);
}

function showMsg(cls, txt){
    const el = $('msg');
    el.className = 'msg ' + cls;
    el.textContent = txt;
    el.style.display = 'block';
    el.scrollIntoView({behavior:'smooth', block:'nearest'});
}

fetch('/api/dz/states', {credentials:'same-origin'})
    .then(r => r.json())
    .then(states => {
        const sel = $('sel-w');
        (states || []).forEach(s => {
            const code = String(s.code).padStart(2, '0');
            const label = `${code} ${s.name} - ${s.ar_name || ''}`.trim();
            const o = document.createElement('option');
            o.value = code;
            o.textContent = label;
            o.dataset.name = s.name || '';
            sel.appendChild(o);
        });
    })
    .catch(() => {});

async function fetchShipping(){
    const stateCode = $('sel-w').value;
    const cityId = $('sel-c').value;
    const shippingType = $('sel-st').value || 'home';
    $('h-st').value = shippingType;

    if (!stateCode) {
        shipCost = 0;
        $('s-sh').textContent = 'اختر الولاية أولاً';
        updateSummary();
        return;
    }

    if (!cityId) {
        shipCost = 0;
        $('s-sh').textContent = 'اختر البلدية أولاً';
        updateSummary();
        return;
    }

    try {
        const r = await fetch(
            '/api/shipping/price/' + encodeURIComponent(stateCode) + '/' + encodeURIComponent(cityId) + '?shipping_type=' + encodeURIComponent(shippingType),
            {credentials:'same-origin'}
        );
        const data = await r.json();
        const shippingText = data && data.display_text ? String(data.display_text) : '';
        shipCost = (data && data.price !== null && data.price !== undefined && data.price !== '') ? (parseInt(data.price, 10) || 0) : 0;
        $('s-sh').textContent = shippingText || (shipCost === 0 ? '<?= __('shipping.free','Free') ?>' : fmt(shipCost));
    } catch (e) {
        shipCost = 0;
        $('s-sh').textContent = '<?= __('shipping.free','Free') ?>';
    }
    updateSummary();
}

$('sel-w').addEventListener('change', async function(){
    const code = this.value;
    const opt = this.options[this.selectedIndex];
    $('h-sc').value = code;
    $('h-sn').value = opt?.dataset.name || '';
    $('h-ci').value = '';
    $('h-cn').value = '';

    const selC = $('sel-c');
    selC.innerHTML = '<option value="">جارٍ التحميل...</option>';
    selC.disabled = true;

    if (!code) {
        shipCost = 0;
        $('s-sh').textContent = 'اختر الولاية أولاً';
        updateSummary();
        return;
    }

    try {
        const r = await fetch('/api/dz/cities/' + encodeURIComponent(code), {credentials:'same-origin'});
        const cities = await r.json();
        selC.innerHTML = '<option value="">اختر البلدية</option>';
        (cities || []).forEach(c => {
            const o = document.createElement('option');
            o.value = c.id;
            o.textContent = c.name;
            o.dataset.name = c.name;
            selC.appendChild(o);
        });
        selC.disabled = false;
    } catch (e) {
        selC.innerHTML = '<option value="">تعذّر التحميل</option>';
    }
    fetchShipping();
});

$('sel-c').addEventListener('change', function(){
    const opt = this.options[this.selectedIndex];
    $('h-ci').value = this.value || '';
    $('h-cn').value = opt?.dataset.name || opt?.textContent || '';
    fetchShipping();
});

$('sel-st').addEventListener('change', fetchShipping);
$('qty-plus').addEventListener('click', function(){ $('qty-val').value = String(qty() + 1); updateSummary(); });
$('qty-minus').addEventListener('click', function(){ if (qty() > 1) { $('qty-val').value = String(qty() - 1); updateSummary(); } });

if ($('sel-size')) {
    $('sel-size').addEventListener('change', function(){ $('h-vs').value = this.value || ''; });
}
if ($('sel-color')) {
    $('sel-color').addEventListener('change', function(){
        const opt = this.options[this.selectedIndex];
        $('h-vc').value = opt?.dataset.colorName || this.value || '';
        $('h-vcc').value = opt?.dataset.colorCode || '';
    });
}

updateSummary();

$('F').addEventListener('submit', async function(e){
    e.preventDefault();

    const fullName = this.querySelector('[name="full_name"]').value.trim();
    const rawPhone = this.querySelector('[name="phone"]').value.trim();
    const sc = $('h-sc').value;
    const ci = $('h-ci').value;

    if (!fullName) { showMsg('er','يرجى إدخال الاسم واللقب.'); return; }
    if (!rawPhone) { showMsg('er','يرجى إدخال رقم الهاتف.'); return; }
    if (!HIDE_WILAYA && !sc) { showMsg('er','يرجى اختيار الولاية.'); return; }
    if (!HIDE_CITY   && !ci) { showMsg('er','يرجى اختيار البلدية.'); return; }
    if ($('sel-size') && !$('h-vs').value) { showMsg('er','يرجى اختيار المقاس.'); return; }
    if ($('sel-color') && !$('h-vc').value && !$('h-vcc').value) { showMsg('er','يرجى اختيار اللون.'); return; }

    let phone = rawPhone.replace(/\D/g, '');
    if (phone.startsWith('0')) phone = '213' + phone.slice(1);
    if (!phone.startsWith('213')) phone = '213' + phone;
    this.querySelector('[name="phone"]').value = phone;

    const btn = $('btn');
    btn.disabled = true;
    $('msg').style.display = 'none';

    try {
        const fd = new FormData(this);
        const res = await fetch('/submit-order', {
            method: 'POST',
            body: fd,
            credentials: 'same-origin'
        });

        const text = await res.text();
        let data = null;
        try { data = JSON.parse(text); } catch (_) {}

        if (res.ok && (!data || data.status !== 'error')) {
            showMsg('ok','✅ تم استلام طلبك بنجاح! سنتصل بك قريباً لتأكيد الطلب وشحنه.');
            this.reset();
            $('sel-c').disabled = true;
            $('sel-c').innerHTML = '<option value="">اختر البلدية</option>';
            ['h-sc','h-sn','h-ci','h-cn','h-ship','h-vs','h-vc','h-vcc'].forEach(id => { if ($(id)) $(id).value = ''; });
            $('h-st').value = 'home';
            $('sel-st').value = 'home';
            $('qty-val').value = '1';
            shipCost = 0;
            $('s-sh').textContent = 'اختر الولاية أولاً';
            updateSummary();
        } else {
            const reason = data && data.reason ? String(data.reason) : '';
            let msg = '❌ حدث خطأ. تأكد من البيانات وحاول مرة أخرى.';
            if (reason === 'missing_size') msg = '❌ يرجى اختيار المقاس أولاً.';
            else if (reason === 'missing_color') msg = '❌ يرجى اختيار اللون أولاً.';
            else if (reason === 'out_of_stock') msg = '❌ عذراً، هذا المنتج غير متوفر حالياً بالكمية المطلوبة.';
            else if (reason === 'phone_banned') msg = '❌ لا يمكن إتمام الطلب بهذا الرقم.';
            else if (text && /CSRF Token Mismatch/i.test(text)) msg = '❌ انتهت صلاحية الجلسة. أعد تحميل الصفحة وحاول مرة أخرى.';
            showMsg('er', msg);
        }
    } catch (err) {
        showMsg('er','❌ تعذّر الاتصال. تحقق من اتصالك وحاول مرة أخرى.');
    } finally {
        btn.disabled = false;
    }
});
</script>
</body>
</html>
<?php
        exit;
    }
}
