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

function t_h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function t_json($d){ header('Content-Type: application/json; charset=utf-8'); echo json_encode($d, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; }

$products=[];
if($res=$conn->query("SELECT id, name, price, status, has_variants, variants_same_price FROM products WHERE status=1 ORDER BY name ASC")){
    while($row=$res->fetch_assoc()) $products[]=$row;
    $res->close();
}
$variants=[];
if($res=$conn->query("SELECT id, product_id, variant_name, price, stock_qty, status FROM product_variants WHERE status=1 ORDER BY product_id ASC, sort_order ASC, id ASC")){
    while($row=$res->fetch_assoc()) $variants[]=$row;
    $res->close();
}
$provinces=[];
if($res=$conn->query("SELECT id,name FROM provinces WHERE status=1 ORDER BY name ASC")){
    while($row=$res->fetch_assoc()) $provinces[]=$row;
    $res->close();
}

$productMap = [];
foreach($products as $product){
    $productMap[(int)$product['id']] = $product;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = (string)$_POST['action'];
    if ($action === 'save') {
        $id = (int)($_POST['id'] ?? 0);
        $title = trim((string)($_POST['title'] ?? ''));
        $promoType = (string)($_POST['promo_type'] ?? 'special_price_product');
        $productId = (int)($_POST['product_id'] ?? 0);
        $variantId = (int)($_POST['variant_id'] ?? 0);
        $minSubtotal = max(0, (float)($_POST['min_subtotal'] ?? 0));
        $specialPrice = max(0, (float)($_POST['special_price'] ?? 0));
        $provinceId = (int)($_POST['province_id'] ?? 0);
        $status = (int)($_POST['status'] ?? 1) === 1 ? 1 : 0;
        $priority = (int)($_POST['priority'] ?? 0);
        $notes = trim((string)($_POST['notes'] ?? ''));

        if ($title === '') t_json(['ok'=>false,'msg'=>'عنوان القاعدة مطلوب.']);
        if ($promoType === 'special_price_product' && $productId <= 0) t_json(['ok'=>false,'msg'=>'اختيار المنتج مطلوب.']);

        $originalPrice = 0.0;
        if ($promoType === 'special_price_product') {
            if ($variantId > 0) {
                foreach ($variants as $variant) {
                    if ((int)$variant['id'] === $variantId) {
                        $originalPrice = (float)($variant['price'] ?? 0);
                        break;
                    }
                }
            }
            if ($originalPrice <= 0 && isset($productMap[$productId])) {
                $originalPrice = (float)($productMap[$productId]['price'] ?? 0);
            }
            if ($specialPrice <= 0) t_json(['ok'=>false,'msg'=>'السعر الخاص مطلوب ويجب أن يكون أكبر من صفر.']);
            if ($originalPrice > 0 && $specialPrice >= $originalPrice) {
                t_json(['ok'=>false,'msg'=>'السعر الخاص لازم يكون أقل من السعر الأصلي.']);
            }
        }

        if ($promoType === 'free_delivery') {
            $productId = 0;
            $variantId = 0;
            $specialPrice = 0;
        }

        if ($id > 0) {
            $stmt = $conn->prepare("UPDATE threshold_promotions SET title=?, promo_type=?, product_id=?, variant_id=?, min_subtotal=?, special_price=?, province_id=?, status=?, priority=?, notes=?, updated_at=NOW() WHERE id=?");
            $stmt->bind_param('ssiiddiiisi', $title, $promoType, $productId, $variantId, $minSubtotal, $specialPrice, $provinceId, $status, $priority, $notes, $id);
        } else {
            $stmt = $conn->prepare("INSERT INTO threshold_promotions (title, promo_type, product_id, variant_id, min_subtotal, special_price, province_id, status, priority, notes, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
            $stmt->bind_param('ssiiddiiis', $title, $promoType, $productId, $variantId, $minSubtotal, $specialPrice, $provinceId, $status, $priority, $notes);
        }
        $ok = $stmt && $stmt->execute();
        $msg = $ok ? 'تم حفظ قاعدة عرض الحد الأدنى بنجاح.' : ('تعذر الحفظ: ' . ($stmt ? $stmt->error : $conn->error));
        if($stmt) $stmt->close();
        t_json(['ok'=>$ok,'msg'=>$msg]);
    }
    if ($action === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $conn->query("UPDATE threshold_promotions SET status = IF(status=1,0,1), updated_at=NOW() WHERE id={$id}");
        t_json(['ok'=>true,'msg'=>'تم تحديث الحالة']);
    }
    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $conn->query("DELETE FROM threshold_promotions WHERE id={$id} LIMIT 1");
        t_json(['ok'=>true,'msg'=>'تم حذف القاعدة']);
    }
}

$q = trim((string)($_GET['q'] ?? ''));
$typeFilter = trim((string)($_GET['promo_type'] ?? ''));
$statusFilter = trim((string)($_GET['status'] ?? ''));
$rows=[];
$sql="SELECT tp.*, p.name AS product_name, p.price AS product_price, pv.variant_name, pv.price AS variant_price, pr.name AS province_name FROM threshold_promotions tp LEFT JOIN products p ON p.id=tp.product_id LEFT JOIN product_variants pv ON pv.id=tp.variant_id LEFT JOIN provinces pr ON pr.id=tp.province_id WHERE 1=1";
if($q !== ''){
    $safe = $conn->real_escape_string($q);
    $sql .= " AND (tp.title LIKE '%{$safe}%' OR tp.notes LIKE '%{$safe}%' OR p.name LIKE '%{$safe}%')";
}
if($typeFilter !== ''){
    $safe = $conn->real_escape_string($typeFilter);
    $sql .= " AND tp.promo_type = '{$safe}'";
}
if($statusFilter === '1' || $statusFilter === '0'){
    $sql .= " AND tp.status = " . (int)$statusFilter;
}
$sql .= " ORDER BY tp.priority DESC, tp.min_subtotal DESC, tp.id DESC";
if($res=$conn->query($sql)){
    while($row=$res->fetch_assoc()) $rows[]=$row;
    $res->close();
}

$stats = [
    'total' => count($rows),
    'active' => 0,
    'special' => 0,
    'free_delivery' => 0,
];
foreach($rows as $row){
    if((int)($row['status'] ?? 0) === 1) $stats['active']++;
    if(($row['promo_type'] ?? '') === 'free_delivery') $stats['free_delivery']++; else $stats['special']++;
}

$pageTitle='عروض الحد الأدنى للسلة';
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>
<div class="nay-dashboard-page">
    <div class="nay-dashboard-main">
        <div class="nay-dashboard-hero">
            <div>
                <h1>عروض الحد الأدنى للسلة</h1>
                <p>إدارة قواعد الشحن المجاني أو السعر الخاص لمنتج عند تجاوز حد معيّن من إجمالي السلة، مع اختيار أسرع للمنتجات وإظهار السعر الأصلي قبل الحفظ.</p>
            </div>
            <div class="nay-actions">
                <button class="nay-btn primary" type="button" onclick="openModal()"><i class="fa-solid fa-plus"></i> إضافة قاعدة</button>
                <a class="nay-btn" href="/app/admin/settings/promotions.php"><i class="fa-solid fa-gear"></i> إعدادات العروض</a>
            </div>
        </div>

        <div class="nay-stats-grid">
            <div class="nay-card"><div class="nay-stat-label">كل القواعد</div><div class="nay-stat-value"><?= number_format($stats['total']) ?></div><div class="nay-stat-sub">العروض المسجلة</div></div>
            <div class="nay-card"><div class="nay-stat-label">مفعّلة</div><div class="nay-stat-value"><?= number_format($stats['active']) ?></div><div class="nay-stat-sub">جاهزة للتطبيق</div></div>
            <div class="nay-card"><div class="nay-stat-label">سعر خاص</div><div class="nay-stat-value"><?= number_format($stats['special']) ?></div><div class="nay-stat-sub">لقواعد المنتج</div></div>
            <div class="nay-card"><div class="nay-stat-label">شحن مجاني</div><div class="nay-stat-value"><?= number_format($stats['free_delivery']) ?></div><div class="nay-stat-sub">لقواعد التوصيل</div></div>
        </div>

        <div class="nay-card" style="margin-bottom:18px;">
            <form method="get" class="nay-form-grid">
                <div>
                    <label class="nay-label">بحث</label>
                    <input class="nay-input" type="text" name="q" value="<?= t_h($q) ?>" placeholder="عنوان القاعدة أو المنتج">
                </div>
                <div>
                    <label class="nay-label">النوع</label>
                    <select class="nay-input" name="promo_type">
                        <option value="">الكل</option>
                        <option value="special_price_product" <?= $typeFilter === 'special_price_product' ? 'selected' : '' ?>>سعر خاص لمنتج</option>
                        <option value="free_delivery" <?= $typeFilter === 'free_delivery' ? 'selected' : '' ?>>شحن مجاني</option>
                    </select>
                </div>
                <div>
                    <label class="nay-label">الحالة</label>
                    <select class="nay-input" name="status">
                        <option value="">الكل</option>
                        <option value="1" <?= $statusFilter === '1' ? 'selected' : '' ?>>مفعلة</option>
                        <option value="0" <?= $statusFilter === '0' ? 'selected' : '' ?>>موقوفة</option>
                    </select>
                </div>
                <div style="display:flex;align-items:end;gap:10px;">
                    <button class="nay-btn primary" type="submit">فلترة</button>
                    <a class="nay-btn" href="index.php">إعادة ضبط</a>
                </div>
            </form>
        </div>

        <div class="nay-card">
            <?php if (!$rows): ?>
                <div class="nay-empty">ماكو قواعد مطابقة حالياً.</div>
            <?php else: ?>
                <div class="nay-table-wrap">
                    <table class="nay-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>العرض</th>
                                <th>النوع</th>
                                <th>الشرط</th>
                                <th>المنتج / الأصل</th>
                                <th>المحافظة</th>
                                <th>الحالة</th>
                                <th>التحكم</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach($rows as $row):
                            $originalPrice = (float)($row['variant_price'] ?? 0);
                            if ($originalPrice <= 0) $originalPrice = (float)($row['product_price'] ?? 0);
                        ?>
                            <tr>
                                <td><?= (int)$row['id'] ?></td>
                                <td><strong><?= t_h($row['title']) ?></strong><div class="muted"><?= t_h($row['notes'] ?? '') ?></div></td>
                                <td><?= ($row['promo_type'] ?? '')==='free_delivery' ? hub_status_badge('شحن مجاني', 'info') : hub_status_badge('سعر خاص', 'success') ?></td>
                                <td>فوق <?= number_format((float)$row['min_subtotal'],0) ?> د.ع<div class="muted">أولوية: <?= (int)$row['priority'] ?></div></td>
                                <td>
                                    <?php if(($row['promo_type'] ?? '')==='free_delivery'): ?>
                                        —
                                    <?php else: ?>
                                        <strong><?= t_h($row['product_name'] ?? '-') ?></strong>
                                        <?php if(!empty($row['variant_name'])): ?><div class="muted"><?= t_h($row['variant_name']) ?></div><?php endif; ?>
                                        <div class="muted">الأصلي: <?= number_format($originalPrice,0) ?> د.ع</div>
                                        <div class="muted">الخاص: <?= number_format((float)$row['special_price'],0) ?> د.ع</div>
                                    <?php endif; ?>
                                </td>
                                <td><?= !empty($row['province_name']) ? t_h($row['province_name']) : 'كل المحافظات' ?></td>
                                <td><?= (int)$row['status']===1 ? hub_status_badge('مفعلة', 'success') : hub_status_badge('موقوفة', 'warn') ?></td>
                                <td>
                                    <div class="mod-actions">
                                        <button class="nay-btn" type="button" onclick='openModal(<?= json_encode($row, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>)'>تعديل</button>
                                        <button class="nay-btn" type="button" onclick="toggleRow(<?= (int)$row['id'] ?>)">حالة</button>
                                        <button class="nay-btn danger" type="button" onclick="deleteRow(<?= (int)$row['id'] ?>)">حذف</button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="mod-modal" id="modModal" hidden>
    <div class="mod-card">
        <div class="nay-card-header-inline" style="margin-bottom:16px"><h3 id="modalTitle">إضافة قاعدة</h3><span>السعر الأصلي يظهر قبل الحفظ</span></div>
        <form id="saveForm" class="nay-form-grid" onsubmit="saveRow(event)">
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="id" id="f_id">
            <input type="hidden" name="product_id" id="f_product_id" value="0">
            <div>
                <label class="nay-label">عنوان القاعدة</label>
                <input class="nay-input" name="title" id="f_title" required>
            </div>
            <div>
                <label class="nay-label">نوع القاعدة</label>
                <select class="nay-input" name="promo_type" id="f_promo_type">
                    <option value="special_price_product">سعر خاص لمنتج</option>
                    <option value="free_delivery">شحن مجاني</option>
                </select>
            </div>
            <div>
                <label class="nay-label">الحد الأدنى للسلة</label>
                <input class="nay-input" type="number" step="0.01" min="0" name="min_subtotal" id="f_min_subtotal" value="0">
            </div>
            <div>
                <label class="nay-label">الأولوية</label>
                <input class="nay-input" type="number" step="1" name="priority" id="f_priority" value="0">
            </div>
            <div class="special-only" style="grid-column:1/-1">
                <label class="nay-label">بحث عن المنتج</label>
                <input class="nay-input" type="text" id="productSearch" placeholder="اكتب اسم المنتج للبحث السريع">
                <div id="productResults" class="picker-list"></div>
                <div id="selectedProductCard" class="selected-product" hidden>
                    <strong id="selectedProductName">—</strong>
                    <div class="muted" id="selectedProductPrice">—</div>
                </div>
            </div>
            <div class="special-only">
                <label class="nay-label">الفاريانت (اختياري)</label>
                <select class="nay-input" name="variant_id" id="f_variant_id"><option value="0">كل الفاريانتات / المنتج</option></select>
            </div>
            <div class="special-only">
                <label class="nay-label">السعر الخاص</label>
                <input class="nay-input" type="number" step="0.01" min="0" name="special_price" id="f_special_price" value="0">
                <div class="muted" id="priceHint">الأصلي: —</div>
            </div>
            <div>
                <label class="nay-label">المحافظة المقيدة</label>
                <select class="nay-input" name="province_id" id="f_province_id"><option value="0">كل المحافظات</option><?php foreach($provinces as $p): ?><option value="<?= (int)$p['id'] ?>"><?= t_h($p['name']) ?></option><?php endforeach; ?></select>
            </div>
            <div>
                <label class="nay-label">الحالة</label>
                <select class="nay-input" name="status" id="f_status"><option value="1">مفعلة</option><option value="0">موقوفة</option></select>
            </div>
            <div style="grid-column:1/-1">
                <label class="nay-label">ملاحظات</label>
                <textarea class="nay-input" name="notes" id="f_notes" rows="3"></textarea>
            </div>
            <div style="grid-column:1/-1;display:flex;gap:10px;justify-content:flex-end">
                <button class="nay-btn primary" type="submit">حفظ</button>
                <button class="nay-btn" type="button" onclick="closeModal()">إلغاء</button>
            </div>
        </form>
    </div>
</div>
<div class="mod-toast" id="toast"></div>

<style>
.nay-form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}
.nay-label{display:block;margin-bottom:6px;font-size:13px;font-weight:700;color:#334155}
.nay-input{width:100%;padding:11px 12px;border:1px solid #dbe3ef;border-radius:12px;background:#fff;font:inherit}
textarea.nay-input{resize:vertical}
.mod-actions{display:flex;gap:8px;flex-wrap:wrap}.nay-btn.danger{background:#fee2e2;color:#991b1b;border-color:#fecaca}
.mod-modal{position:fixed;inset:0;background:rgba(15,23,42,.45);display:flex;align-items:center;justify-content:center;padding:16px;z-index:1600}
.mod-card{width:min(920px,100%);background:#fff;border-radius:22px;padding:22px;box-shadow:0 24px 60px rgba(15,23,42,.2)}
.mod-toast{position:fixed;top:16px;left:16px;background:#16a34a;color:#fff;padding:12px 16px;border-radius:12px;display:none;z-index:1700}.mod-toast.error{background:#dc2626}
.picker-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-top:10px;max-height:230px;overflow:auto}.picker-item{border:1px solid #dbe3ef;border-radius:14px;padding:12px;cursor:pointer;background:#f8fafc}.picker-item:hover,.picker-item.active{border-color:#94a3b8;background:#eef2ff}.selected-product{margin-top:10px;padding:12px;border:1px dashed #cbd5e1;border-radius:14px;background:#f8fafc}.hidden{display:none !important}
@media(max-width:768px){.nay-form-grid,.picker-list{grid-template-columns:1fr}.mod-card{padding:16px}}
</style>
<script>
const products = <?= json_encode(array_map(fn($p) => ['id'=>(int)$p['id'],'name'=>(string)$p['name'],'price'=>(float)($p['price'] ?? 0),'has_variants'=>(int)($p['has_variants'] ?? 0)], $products), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
const variants = <?= json_encode(array_map(fn($v) => ['id'=>(int)$v['id'],'product_id'=>(int)$v['product_id'],'variant_name'=>(string)$v['variant_name'],'price'=>(float)($v['price'] ?? 0),'stock_qty'=>(int)($v['stock_qty'] ?? 0)], $variants), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
const modal = document.getElementById('modModal');
const productSearch = document.getElementById('productSearch');
const productResults = document.getElementById('productResults');
const selectedProductCard = document.getElementById('selectedProductCard');
const selectedProductName = document.getElementById('selectedProductName');
const selectedProductPrice = document.getElementById('selectedProductPrice');
const priceHint = document.getElementById('priceHint');
function toast(msg, err=false){const t=document.getElementById('toast');t.textContent=msg;t.className='mod-toast'+(err?' error':'');t.style.display='block';setTimeout(()=>t.style.display='none',2400)}
function currency(v){return new Intl.NumberFormat('en-US',{maximumFractionDigits:0}).format(Number(v||0))+' د.ع'}
function closeModal(){modal.hidden=true;}
function syncType(){ const special = document.getElementById('f_promo_type').value === 'special_price_product'; document.querySelectorAll('.special-only').forEach(el=>el.classList.toggle('hidden', !special)); }
function syncVariants(selected=0){ const pid = Number(document.getElementById('f_product_id').value||0); const sel = document.getElementById('f_variant_id'); sel.innerHTML='<option value="0">كل الفاريانتات / المنتج</option>'; variants.filter(v=>v.product_id===pid).forEach(v=>{ const opt=document.createElement('option'); opt.value=v.id; opt.textContent=`${v.variant_name} — ${currency(v.price)}`; if(Number(selected)===Number(v.id)) opt.selected=true; sel.appendChild(opt); }); updateOriginalPriceHint(); }
function updateOriginalPriceHint(){ const pid=Number(document.getElementById('f_product_id').value||0); const vid=Number(document.getElementById('f_variant_id').value||0); const product=products.find(p=>p.id===pid); let original=product?Number(product.price||0):0; if(vid>0){ const variant=variants.find(v=>v.id===vid); if(variant) original=Number(variant.price||0); } priceHint.textContent='الأصلي: ' + (original>0?currency(original):'—'); if(product){ selectedProductCard.hidden=false; selectedProductName.textContent=product.name; selectedProductPrice.textContent='السعر الأصلي: ' + (original>0?currency(original):'—'); } else { selectedProductCard.hidden=true; } }
function chooseProduct(id){ document.getElementById('f_product_id').value=String(id); const product=products.find(p=>p.id===Number(id)); productSearch.value=product?product.name:''; renderProducts(productSearch.value); syncVariants(0); }
function renderProducts(query=''){ const q = (query||'').trim().toLowerCase(); productResults.innerHTML=''; let rows = products; if(q){ rows = rows.filter(p=>p.name.toLowerCase().includes(q)); }
 rows.slice(0,16).forEach(p=>{ const item=document.createElement('button'); item.type='button'; item.className='picker-item'+(Number(document.getElementById('f_product_id').value||0)===p.id?' active':''); item.innerHTML=`<strong>${p.name}</strong><div class="muted">${currency(p.price||0)}</div>`; item.onclick=()=>chooseProduct(p.id); productResults.appendChild(item); }); if(!rows.length){ productResults.innerHTML='<div class="muted">ماكو نتائج مطابقة.</div>'; }}
function openModal(row=null){ document.getElementById('saveForm').reset(); document.getElementById('f_id').value=''; document.getElementById('f_product_id').value='0'; document.getElementById('modalTitle').textContent=row?'تعديل القاعدة':'إضافة قاعدة'; if(row){ for(const k in row){ const el=document.getElementById('f_'+k); if(el) el.value=row[k]??''; } document.getElementById('f_product_id').value=String(row.product_id||0); const prod=products.find(p=>p.id===Number(row.product_id||0)); productSearch.value=prod?prod.name:''; syncVariants(row.variant_id||0); } else { productSearch.value=''; renderProducts(''); syncVariants(0); } syncType(); updateOriginalPriceHint(); modal.hidden=false; renderProducts(productSearch.value); }
document.getElementById('f_promo_type').addEventListener('change', syncType); document.getElementById('f_variant_id').addEventListener('change', updateOriginalPriceHint); productSearch.addEventListener('input', ()=>renderProducts(productSearch.value));
async function postData(data){const body = new URLSearchParams(data instanceof FormData ? [...data.entries()] : Object.entries(data)); const res=await fetch('index.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body}); return res.json();}
async function saveRow(e){e.preventDefault(); const res=await postData(new FormData(e.target)); toast(res.msg,!res.ok); if(res.ok) setTimeout(()=>location.reload(),600)}
async function toggleRow(id){const res=await postData({action:'toggle',id}); toast(res.msg,!res.ok); if(res.ok) setTimeout(()=>location.reload(),400)}
async function deleteRow(id){ if(!confirm('تأكيد حذف القاعدة؟')) return; const res=await postData({action:'delete',id}); toast(res.msg,!res.ok); if(res.ok) setTimeout(()=>location.reload(),400)}
modal.addEventListener('click',(e)=>{ if(e.target===modal) closeModal(); });
</script>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
