<?php defined('ABSPATH') || exit;
$plan = \DZQCOD\Core::opt('license_plan','free');
if($plan==='free'){
    include __DIR__.'/nav.php';
    echo '<div class="dza-content" style="text-align:center;padding:60px"><div style="font-size:64px;margin-bottom:16px">🖥️</div><h2 style="color:#475569">نقطة البيع POS</h2><p style="color:#94a3b8;margin-bottom:20px">هذه الميزة متاحة في خطة PRO وما فوق</p><a href="'.admin_url('admin.php?page=dzqcod-license').'" class="dza-btn primary">🔓 ترقية الآن</a></div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe static HTML
    return;
}
$is_ent = $plan==='enterprise';
$cur_user = wp_get_current_user();
$user_name = $cur_user->display_name ?: $cur_user->user_login;
// Products
$products = get_posts(['post_type'=>'product','posts_per_page'=>200,'post_status'=>'publish']);
$items_json = [];
foreach($products as $pp){
    $p=wc_get_product($pp->ID); if(!$p)continue;
    $thumb=get_the_post_thumbnail_url($pp->ID,'thumbnail');
    $cpc_on=get_post_meta($pp->ID,'_dzqcod_custom_enabled',true)==='yes';
    $price=$cpc_on?(float)(get_post_meta($pp->ID,'_dzqcod_custom_base',true)?:$p->get_price()):(float)$p->get_price();
    $cats=wp_get_post_terms($pp->ID,'product_cat',['fields'=>'names']);
    $sku=$p->get_sku()?:'';
    $barcode=get_post_meta($pp->ID,'_dzqcod_barcode',true)?:$sku;
    // Custom product config
    $cpc_dims=[]; $cpc_opts=[]; $cpc_mode='fixed'; $cpc_ppu=0; $cpc_unit='م²';
    if($cpc_on){
        $cpc_dims=json_decode(get_post_meta($pp->ID,'_dzqcod_dimensions',true)?:'[]',true)?:[];
        $cpc_opts=json_decode(get_post_meta($pp->ID,'_dzqcod_paid_options',true)?:'[]',true)?:[];
        $cpc_mode=get_post_meta($pp->ID,'_dzqcod_pricing_mode',true)?:'fixed';
        $cpc_ppu=(float)(get_post_meta($pp->ID,'_dzqcod_price_per_unit',true)?:0);
        $cpc_unit=get_post_meta($pp->ID,'_dzqcod_unit_label',true)?:'م²';
    }
    $items_json[]=[
        'id'=>$pp->ID,'name'=>$p->get_name(),'price'=>$price,
        'img'=>$thumb?:'','sku'=>$sku,'barcode'=>$barcode,
        'stock'=>$p->get_stock_quantity(),'cat'=>$cats[0]??'عام',
        'custom'=>$cpc_on?true:false,
        'dims'=>$cpc_dims,'opts'=>$cpc_opts,
        'mode'=>$cpc_mode,'ppu'=>$cpc_ppu,'unit'=>$cpc_unit,
    ];
}
// Wilayas
global $wpdb; $pfx=$wpdb->prefix.DZQCOD_DB;
$wilayas=$wpdb->get_results("SELECT code,name_ar,shipping_home,shipping_desk FROM {$pfx}wilayas WHERE is_active=1 ORDER BY id");
$store_name=get_bloginfo('name');
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>POS — <?php echo esc_html($store_name); ?></title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800;900&display=swap" rel="stylesheet">
<style>
*{margin:0;padding:0;box-sizing:border-box}
:root{--bg:#0f172a;--card:#1e293b;--card2:#334155;--accent:#6366f1;--accent2:#818cf8;--green:#22c55e;--red:#ef4444;--orange:#f97316;--text:#f8fafc;--text2:#94a3b8;--border:#475569;--r:12px}
body{font-family:'Tajawal',sans-serif;background:var(--bg);color:var(--text);height:100vh;overflow:hidden;direction:rtl}

/* LAYOUT */
.pos{display:grid;grid-template-columns:1fr 400px;height:100vh}
.pos-left{display:flex;flex-direction:column;overflow:hidden}
.pos-right{background:var(--card);display:flex;flex-direction:column;border-right:1px solid var(--border);height:100vh}

/* TOP BAR */
.pos-bar{background:var(--card);padding:8px 16px;display:flex;align-items:center;gap:10px;border-bottom:1px solid var(--border);flex-wrap:wrap}
.pos-bar h1{font-size:15px;font-weight:900;color:var(--accent2);white-space:nowrap}
.pos-bar-info{display:flex;align-items:center;gap:12px;font-size:11px;color:var(--text2)}
.pos-bar-info .user{color:var(--accent2);font-weight:700}
.pos-search{flex:1;min-width:200px}
.pos-search input{width:100%;padding:9px 14px;background:var(--card2);border:1px solid var(--border);border-radius:var(--r);color:var(--text);font-size:14px;font-family:inherit;outline:none}
.pos-search input:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(99,102,241,.2)}
.pos-back{padding:7px 12px;background:var(--card2);border:none;border-radius:8px;color:var(--text2);cursor:pointer;font-family:inherit;font-size:12px;font-weight:700;text-decoration:none}
.pos-back:hover{background:var(--accent);color:#fff}

/* CATS */
.pos-cats{display:flex;gap:6px;overflow-x:auto;padding:8px 16px;background:var(--bg);scrollbar-width:none;flex-shrink:0}
.pos-cats::-webkit-scrollbar{display:none}
.pos-cat{padding:5px 14px;background:var(--card2);border-radius:20px;font-size:12px;font-weight:700;cursor:pointer;white-space:nowrap;transition:.2s;border:1px solid transparent}
.pos-cat:hover,.pos-cat.active{background:var(--accent);color:#fff}

/* GRID */
.pos-grid{flex:1;overflow-y:auto;padding:10px;display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:8px;align-content:start}
.pos-grid::-webkit-scrollbar{width:6px}.pos-grid::-webkit-scrollbar-thumb{background:var(--border);border-radius:6px}
.pos-item{background:var(--card);border-radius:var(--r);padding:8px;cursor:pointer;transition:.15s;border:2px solid transparent;text-align:center;position:relative}
.pos-item:hover{border-color:var(--accent);transform:translateY(-2px)}
.pos-item:active{transform:scale(.96)}
.pos-item img{width:72px;height:72px;object-fit:cover;border-radius:8px;margin-bottom:4px}
.pos-item .no-img{width:72px;height:72px;background:var(--card2);border-radius:8px;margin:0 auto 4px;display:flex;align-items:center;justify-content:center;font-size:24px}
.pos-item-name{font-size:11px;font-weight:700;line-height:1.3;margin-bottom:3px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.pos-item-price{font-size:13px;font-weight:900;color:var(--green)}

/* ══ CART ══ */
.pos-cart-head{padding:10px 14px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;flex-shrink:0}
/* FIX #2: scrollable cart with mouse wheel */
.pos-cart-items{flex:1;overflow-y:auto;padding:6px 10px;min-height:0}
.pos-cart-items::-webkit-scrollbar{width:4px}.pos-cart-items::-webkit-scrollbar-thumb{background:var(--border);border-radius:4px}
.pos-ci{background:var(--card2);border-radius:8px;padding:8px 10px;margin-bottom:5px;display:flex;gap:8px;align-items:center;animation:cSlide .15s ease}
@keyframes cSlide{from{opacity:0;transform:translateX(16px)}to{opacity:1;transform:none}}
.pos-ci-info{flex:1;min-width:0}
.pos-ci-name{font-size:12px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.pos-ci-price{font-size:10px;color:var(--text2)}
.pos-ci-qty{display:flex;align-items:center;gap:4px}
.pos-ci-qty button{width:26px;height:26px;border:none;border-radius:6px;font-size:14px;font-weight:900;cursor:pointer;display:flex;align-items:center;justify-content:center}
.pos-ci-qty button:active{transform:scale(.9)}
.pos-ci-qty .mi{background:var(--card);color:var(--text)}
.pos-ci-qty .pl{background:var(--accent);color:#fff}
.pos-ci-qty span{font-size:14px;font-weight:900;min-width:18px;text-align:center}
.pos-ci-total{font-size:13px;font-weight:900;color:var(--green);min-width:55px;text-align:left}
.pos-ci-rm{background:none;border:none;color:var(--red);cursor:pointer;font-size:14px;padding:2px;opacity:.5}
.pos-ci-rm:hover{opacity:1}
.pos-empty{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;color:var(--text2);font-size:13px}

/* ══ BOTTOM SECTION (always visible) ══ */
.pos-bottom{flex-shrink:0;border-top:1px solid var(--border);background:var(--card)}
.pos-cust{padding:6px 12px;display:flex;gap:6px}
.pos-inp{width:100%;padding:7px 10px;background:var(--card2);border:1px solid var(--border);border-radius:8px;color:var(--text);font-family:inherit;font-size:12px;outline:none}
.pos-inp:focus{border-color:var(--accent)}
.pos-del{display:flex;gap:6px;padding:4px 12px}
.pos-del-btn{flex:1;padding:8px;border:2px solid var(--border);border-radius:8px;background:var(--card2);color:var(--text);font-family:inherit;font-size:11px;font-weight:700;cursor:pointer;text-align:center;transition:.2s}
.pos-del-btn.on{border-color:var(--accent);background:rgba(99,102,241,.15)}
.pos-extras{padding:4px 12px;display:flex;gap:6px}
/* FIX #1: BIGGER TOTAL */
.pos-totals{padding:8px 14px}
.pos-tr{display:flex;justify-content:space-between;padding:2px 0;font-size:12px;color:var(--text2)}
.pos-grand{display:flex;justify-content:space-between;align-items:center;padding:10px 14px;background:linear-gradient(135deg,rgba(99,102,241,.15),rgba(34,197,94,.1));border-radius:10px;margin:6px 12px}
.pos-grand-label{font-size:14px;font-weight:800}
.pos-grand-val{font-size:28px;font-weight:900;color:var(--green);letter-spacing:1px}
/* FIX #3: buttons always visible */
.pos-acts{padding:8px 12px 12px;display:flex;gap:8px}
.pos-btn{flex:1;padding:12px;border:none;border-radius:var(--r);font-family:inherit;font-size:14px;font-weight:900;cursor:pointer;transition:.15s;display:flex;align-items:center;justify-content:center;gap:6px}
.pos-btn:active{transform:scale(.97)}
.pos-btn.pay{background:linear-gradient(135deg,var(--green),#16a34a);color:#fff;flex:2}
.pos-btn.clr{background:var(--red);color:#fff}
.pos-btn:disabled{opacity:.3;cursor:not-allowed;transform:none}

/* MODALS */
.pos-modal{position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,.8);display:none;align-items:center;justify-content:center;backdrop-filter:blur(4px)}
.pos-modal.show{display:flex}
.pos-modal-box{background:var(--card);border-radius:16px;padding:24px;width:380px;max-height:90vh;overflow-y:auto;animation:mZoom .2s ease}
@keyframes mZoom{from{transform:scale(.9);opacity:0}to{transform:none;opacity:1}}
.pos-pay-methods{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin:12px 0}
.pos-pm{padding:12px;border:2px solid var(--border);border-radius:10px;text-align:center;cursor:pointer;transition:.2s;background:var(--card2)}
.pos-pm:hover{border-color:var(--accent2)}.pos-pm.on{border-color:var(--green);background:rgba(34,197,94,.1)}
.pos-pm .ic{font-size:22px}.pos-pm .nm{font-size:11px;font-weight:700}

/* RECEIPT */
@media print{body *{visibility:hidden}#pos-receipt,#pos-receipt *{visibility:visible}#pos-receipt{position:fixed;top:0;left:0;width:80mm;background:#fff!important;color:#000!important;padding:8mm;font-size:11px}}
.pos-receipt{background:#fff;color:#000;padding:16px;border-radius:10px;font-size:11px;direction:rtl}
.pos-receipt h3{text-align:center;font-size:14px;margin-bottom:6px;border-bottom:2px dashed #ccc;padding-bottom:6px}
.pos-receipt table{width:100%;border-collapse:collapse;margin:8px 0}
.pos-receipt td{padding:2px 0;font-size:10px}
.pos-receipt .r-total{font-size:16px;font-weight:900;text-align:center;border-top:2px dashed #ccc;padding-top:6px;margin-top:6px}
</style>
</head>
<body>
<div class="pos">

<!-- ════════ LEFT: PRODUCTS ════════ -->
<div class="pos-left">
<div class="pos-bar">
<a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod')); ?>" class="pos-back">↩️</a>
<h1>🖥️ POS</h1>
<div class="pos-search"><input type="text" id="pos-search" placeholder="🔍 بحث بالاسم، الرمز أو الباركود..." autofocus></div>
<!-- FIX #5: date + time + user -->
<div class="pos-bar-info">
<span id="pos-date"></span>
<span id="pos-clock"></span>
<span class="user">👤 <?php echo esc_html($user_name); ?></span>
</div>
</div>
<div class="pos-cats" id="pos-cats"><div class="pos-cat active" data-cat="all">الكل</div></div>
<div class="pos-grid" id="pos-grid"></div>
</div>

<!-- ════════ RIGHT: CART ════════ -->
<div class="pos-right">
<div class="pos-cart-head">
<h2 style="font-size:15px;font-weight:900">🛒 السلة</h2>
<span id="pos-count" style="font-size:11px;color:var(--text2)">0 عنصر</span>
</div>

<!-- FIX #2: scrollable cart items -->
<div class="pos-cart-items" id="pos-items">
<div class="pos-empty"><div style="font-size:40px;opacity:.4;margin-bottom:6px">🛒</div>السلة فارغة</div>
</div>

<!-- ══ BOTTOM — always visible ══ -->
<div class="pos-bottom">
<div class="pos-cust">
<input type="text" class="pos-inp" id="c-name" placeholder="👤 اسم العميل">
<input type="text" class="pos-inp" id="c-phone" placeholder="📱 الهاتف" style="direction:ltr;text-align:right">
</div>
<div class="pos-del">
<button class="pos-del-btn on" data-d="store_pickup" onclick="setDel(this)">🏪 استلام</button>
<button class="pos-del-btn" data-d="home_delivery" onclick="setDel(this)">🚚 توصيل</button>
</div>
<div id="ship-fields" style="display:none;padding:2px 12px 4px">
<select class="pos-inp" id="c-wil" style="margin-bottom:4px">
<option value="">اختر الولاية</option>
<?php foreach($wilayas as $w): ?><option value="<?php echo esc_html($w->code);?>" data-s="<?php echo esc_html($w->shipping_home);?>"><?php echo esc_html($w->code.' - '.$w->name_ar);?></option><?php endforeach; ?>
</select>
<input type="text" class="pos-inp" id="c-addr" placeholder="📍 العنوان">
</div>
<div class="pos-extras">
<input type="number" class="pos-inp" id="c-disc" placeholder="🏷️ خصم (دج)" min="0" style="flex:1">
<input type="text" class="pos-inp" id="c-note" placeholder="📝 ملاحظة" style="flex:2">
</div>
<div class="pos-totals">
<div class="pos-tr"><span>المجموع الفرعي</span><span id="t-sub">0 دج</span></div>
<div class="pos-tr"><span>الشحن</span><span id="t-ship">0 دج</span></div>
<div class="pos-tr" id="t-disc-row" style="display:none;color:var(--red)"><span>الخصم</span><span id="t-disc">-0 دج</span></div>
</div>
<!-- FIX #1: BIG TOTAL -->
<div class="pos-grand">
<span class="pos-grand-label">💰 الإجمالي</span>
<span class="pos-grand-val" id="t-grand">0 دج</span>
</div>
<!-- FIX #3: buttons always visible -->
<div class="pos-acts">
<button class="pos-btn clr" onclick="clearCart()" title="إفراغ">🗑️</button>
<button class="pos-btn pay" id="btn-pay" disabled onclick="openPay()">💵 الدفع <span style="font-size:11px;opacity:.7">(F9)</span></button>
</div>
</div>
</div>
</div>

<!-- ════ PAYMENT MODAL ════ -->
<div class="pos-modal" id="m-pay">
<div class="pos-modal-box">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px">
<h3 style="font-size:18px">💵 إتمام الطلب</h3>
<button onclick="closePay()" style="background:none;border:none;color:var(--text2);font-size:20px;cursor:pointer">✕</button>
</div>
<div style="text-align:center;background:var(--card2);border-radius:12px;padding:16px;margin-bottom:12px">
<div style="font-size:11px;color:var(--text2)">الإجمالي</div>
<div style="font-size:36px;font-weight:900;color:var(--green)" id="m-total">0 دج</div>
</div>
<div style="font-size:12px;font-weight:700;margin-bottom:4px">طريقة الدفع</div>
<div class="pos-pay-methods">
<div class="pos-pm on" data-pm="cash" onclick="setPM(this)"><div class="ic">💵</div><div class="nm">نقداً</div></div>
<div class="pos-pm" data-pm="card" onclick="setPM(this)"><div class="ic">💳</div><div class="nm">بطاقة</div></div>
<div class="pos-pm" data-pm="baridimob" onclick="setPM(this)"><div class="ic">📱</div><div class="nm">بريدي موب</div></div>
<div class="pos-pm" data-pm="transfer" onclick="setPM(this)"><div class="ic">🏦</div><div class="nm">تحويل</div></div>
</div>
<?php if($is_ent): ?>
<div style="margin-bottom:10px"><label style="font-size:11px;font-weight:700">المبلغ المستلم</label>
<input type="number" class="pos-inp" id="m-recv" placeholder="المبلغ" min="0" style="font-size:20px;font-weight:900;text-align:center;margin-top:4px">
<div id="m-change" style="text-align:center;margin-top:4px;font-size:15px;font-weight:800;color:var(--orange);display:none"></div></div>
<?php endif; ?>
<button class="pos-btn pay" style="width:100%" id="btn-confirm" onclick="confirmOrder()">✅ تأكيد <span style="font-size:11px;opacity:.7">(F12)</span></button>
</div>
</div>

<!-- ════ RECEIPT MODAL ════ -->
<div class="pos-modal" id="m-receipt">
<div class="pos-modal-box" style="width:400px">
<div style="text-align:center;margin-bottom:10px">
<div style="font-size:44px">✅</div>
<h3 style="font-size:18px;color:var(--green)">تم إنشاء الطلب!</h3>
<div style="font-size:13px;color:var(--text2)" id="r-oid"></div>
</div>
<div id="pos-receipt" class="pos-receipt"></div>
<div style="display:flex;gap:8px;margin-top:12px">
<button class="pos-btn" style="flex:1;background:var(--card2);color:var(--text)" onclick="printReceipt()">🖨️ طباعة</button>
<button class="pos-btn pay" style="flex:1" onclick="closeReceipt()">🆕 طلب جديد</button>
</div>
</div>
</div>

<!-- ════ CUSTOM PRODUCT MODAL ════ -->
<div class="pos-modal" id="m-custom">
<div class="pos-modal-box" style="width:440px">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px">
<h3 style="font-size:16px">🏭 <span id="mc-name"></span></h3>
<button onclick="closeCustom()" style="background:none;border:none;color:var(--text2);font-size:20px;cursor:pointer">✕</button>
</div>
<div id="mc-dims"></div>
<div id="mc-opts" style="margin-top:8px"></div>
<div style="margin-top:12px;background:var(--card2);border-radius:10px;padding:12px">
<div style="display:flex;justify-content:space-between;font-size:12px;color:var(--text2)"><span>السعر الأساسي</span><span id="mc-base">0 دج</span></div>
<div style="display:flex;justify-content:space-between;font-size:12px;color:var(--text2)"><span>الأبعاد</span><span id="mc-dprice">0 دج</span></div>
<div style="display:flex;justify-content:space-between;font-size:12px;color:var(--text2)"><span>الخيارات</span><span id="mc-oprice">0 دج</span></div>
<div style="display:flex;justify-content:space-between;font-size:16px;font-weight:900;color:var(--green);margin-top:6px;padding-top:6px;border-top:1px solid var(--border)"><span>الإجمالي</span><span id="mc-total">0 دج</span></div>
</div>
<button class="pos-btn pay" style="width:100%;margin-top:10px" onclick="confirmCustom()">✅ إضافة للسلة</button>
</div>
</div>

<!-- SOUNDS -->
<audio id="snd-add" preload="auto"><source src="data:audio/wav;base64,UklGRl4AAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YToAAACAf35+fn9/gIGCg4OEhIODgoGAf359fHx8fH1+f4CBgoOEhIODgoGAf359fHx8"></audio>
<audio id="snd-rm" preload="auto"><source src="data:audio/wav;base64,UklGRl4AAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YToAAACEg4OCgYB/fn18e3t7fH1+f4CBgoOEhIODgoGAf359fHx8fX5/gIGCg4SEg4OCgQ=="></audio>
<audio id="snd-ok" preload="auto"><source src="data:audio/wav;base64,UklGRoAAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YVwAAACAgoSGiIqMjI2NjYyLiomHhYOBf319fHx8fX5/gIGCg4SFhoaGhoaFhIOCgYB/fn5+fn5/gIGBgoKCgoKCgoGBgYB/f39/f4CAgICAgICAf39/f39/gICA"></audio>

<script>
var P=<?php echo wp_json_encode($items_json, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>;
var AX='<?php echo esc_url(admin_url("admin-ajax.php")); ?>';
var NC='<?php echo esc_attr(wp_create_nonce("dzqcod_admin")); ?>';
var SN=<?php echo wp_json_encode($store_name); ?>;
var ENT=<?php echo esc_html($is_ent?'true':'false'); ?>;
var cart=[],del='store_pickup',pm='cash',shipC=0;

// FIX #4: Barcode scanner buffer
var bcBuf='',bcTimer=null;
document.addEventListener('keypress',function(e){
    // Barcode scanners send chars rapidly then Enter
    if(document.activeElement.tagName==='INPUT'&&document.activeElement.id!=='pos-search') return;
    if(e.key==='Enter'&&bcBuf.length>=3){
        var code=bcBuf.trim();bcBuf='';
        var found=P.find(function(p){return p.barcode===code||p.sku===code||String(p.id)===code});
        if(found){addToCart(found);document.getElementById('pos-search').value='';return}
    }
    if(e.key.length===1){bcBuf+=e.key;clearTimeout(bcTimer);bcTimer=setTimeout(function(){bcBuf=''},100)}
});

// FIX #5: Date + Time + User
function updateClock(){
    var d=new Date();
    document.getElementById('pos-date').textContent=d.toLocaleDateString('ar-DZ',{year:'numeric',month:'short',day:'numeric'});
    document.getElementById('pos-clock').textContent=d.toLocaleTimeString('ar-DZ',{hour:'2-digit',minute:'2-digit',second:'2-digit'});
}
updateClock();setInterval(updateClock,1000);

// ═══ INIT ═══
(function(){
    var cats=new Set(['all']);P.forEach(function(p){if(p.cat)cats.add(p.cat)});
    var $c=document.getElementById('pos-cats');
    cats.forEach(function(c){if(c!=='all'){var d=document.createElement('div');d.className='pos-cat';d.dataset.cat=c;d.textContent=c;d.onclick=function(){filterCat(c)};$c.appendChild(d)}});
    renderGrid();
})();

function renderGrid(f,cat){
    var g=document.getElementById('pos-grid');g.innerHTML='';
    var q=(f||'').toLowerCase();
    P.forEach(function(p){
        if(q&&p.name.toLowerCase().indexOf(q)<0&&(p.sku||'').toLowerCase().indexOf(q)<0&&(p.barcode||'').toLowerCase().indexOf(q)<0) return;
        if(cat&&cat!=='all'&&p.cat!==cat) return;
        var d=document.createElement('div');d.className='pos-item';d.onclick=function(){addToCart(p)};
        var img=p.img?'<img src="'+p.img+'">':'<div class="no-img">📦</div>';
        var badges='';
        if(p.custom)badges+='<span style="position:absolute;top:4px;right:4px;background:#f97316;color:#fff;font-size:9px;padding:2px 6px;border-radius:4px;font-weight:800;z-index:2">🏭 مخصص</span>';
        if(p.stock!==null&&p.stock>0&&p.stock<=5)badges+='<span style="position:absolute;top:4px;left:4px;background:#ef4444;color:#fff;font-size:9px;padding:2px 5px;border-radius:4px;font-weight:700;z-index:2">'+p.stock+'</span>';
        d.innerHTML='<div style="position:relative">'+badges+img+'</div><div class="pos-item-name">'+p.name+'</div><div class="pos-item-price">'+fmt(p.price)+'</div>';
        g.appendChild(d);
    });
    if(!g.children.length) g.innerHTML='<div style="grid-column:1/-1;text-align:center;padding:40px;color:var(--text2)">🔍 لم يتم العثور على منتجات</div>';
}
document.getElementById('pos-search').addEventListener('input',function(){renderGrid(this.value,document.querySelector('.pos-cat.active')?.dataset.cat)});
function filterCat(c){document.querySelectorAll('.pos-cat').forEach(function(e){e.classList.toggle('active',e.dataset.cat===c)});renderGrid(document.getElementById('pos-search').value,c)}

// ═══ CART ═══
var pendingCustom=null;
function addToCart(p){
    if(p.stock!==null&&p.stock<=0)return;
    // Custom product → open config modal
    if(p.custom===true||p.custom==='1'||p.custom===1){pendingCustom=p;openCustomModal(p);return}
    var ex=cart.find(function(i){return i.id===p.id&&!i.customData});
    if(ex)ex.qty++;else cart.push({id:p.id,name:p.name,price:p.price,qty:1});
    snd('add');renderCart();
}
function openCustomModal(p){
    document.getElementById('mc-name').textContent=p.name;
    document.getElementById('mc-base').textContent=fmt(p.price);
    // Dimensions
    var dh='';
    if(p.dims&&p.dims.length){
        dh='<div style="font-size:12px;font-weight:700;margin-bottom:6px;color:var(--accent2)">📐 الأبعاد</div>';
        p.dims.forEach(function(d,i){
            dh+='<div style="display:flex;gap:8px;align-items:center;margin-bottom:6px">';
            dh+='<label style="font-size:12px;min-width:60px;font-weight:700">'+(d.name||'بُعد '+(i+1))+'</label>';
            dh+='<input type="number" class="pos-inp mc-dim" data-idx="'+i+'" placeholder="'+(d.min||0)+' - '+(d.max||'')+'" min="'+(d.min||0)+'" '+(d.max?'max="'+d.max+'"':'')+' step="0.1" style="flex:1" oninput="calcCustom()">';
            dh+='<span style="font-size:11px;color:var(--text2)">'+(d.unit||'سم')+'</span></div>';
        });
    }
    document.getElementById('mc-dims').innerHTML=dh;
    // Options
    var oh='';
    if(p.opts&&p.opts.length){
        oh='<div style="font-size:12px;font-weight:700;margin-bottom:6px;color:var(--accent2)">✨ الخيارات</div>';
        p.opts.forEach(function(o,i){
            oh+='<div style="margin-bottom:6px">';
            if(o.type==='checkbox'){
                oh+='<label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-size:12px"><input type="checkbox" class="mc-opt" data-idx="'+i+'" data-type="checkbox" data-price="'+(o.price||0)+'" onchange="calcCustom()"> '+o.name+' <span style="color:var(--green);font-size:10px">(+'+(o.price||0)+' دج)</span></label>';
            } else if(o.type==='select'&&o.values){
                oh+='<label style="font-size:11px;font-weight:700">'+o.name+'</label>';
                oh+='<select class="pos-inp mc-opt" data-idx="'+i+'" data-type="select" onchange="calcCustom()" style="margin-top:2px"><option value="">— اختر —</option>';
                o.values.split(',').forEach(function(v){var ps=v.split(':');oh+='<option value="'+ps[0].trim()+'" data-price="'+(ps[1]||0)+'">'+ps[0].trim()+' (+'+(ps[1]||0)+' دج)</option>'});
                oh+='</select>';
            } else if(o.type==='number'){
                oh+='<div style="display:flex;gap:6px;align-items:center"><label style="font-size:11px;font-weight:700;min-width:60px">'+o.name+'</label><input type="number" class="pos-inp mc-opt" data-idx="'+i+'" data-type="number" data-price="'+(o.price||0)+'" min="0" value="0" oninput="calcCustom()" style="flex:1"><span style="font-size:10px;color:var(--text2)">×'+(o.price||0)+' دج</span></div>';
            }
            oh+='</div>';
        });
    }
    document.getElementById('mc-opts').innerHTML=oh;
    // Fixed mode: no dims no opts — just show base price
    if((!p.dims||!p.dims.length)&&(!p.opts||!p.opts.length)){
        document.getElementById('mc-dims').innerHTML='<div style="text-align:center;padding:16px;color:var(--text2)"><div style="font-size:32px;margin-bottom:8px">🏭</div><div style="font-size:14px;font-weight:700">منتج مخصص بسعر ثابت</div><div style="font-size:12px;margin-top:4px">السعر: '+fmt(p.price)+'</div></div>';
    }
    document.getElementById('mc-dprice').textContent='0 دج';
    document.getElementById('mc-oprice').textContent='0 دج';
    document.getElementById('mc-total').textContent=fmt(p.price);
    document.getElementById('m-custom').classList.add('show');
}
function calcCustom(){
    if(!pendingCustom)return;
    var p=pendingCustom,base=p.price,isCm=(p.unit||'').indexOf('سم')>=0||(p.unit||'').indexOf('cm')>=0;
    // Dims
    var dimVals=[];document.querySelectorAll('.mc-dim').forEach(function(el){dimVals.push(parseFloat(el.value)||0)});
    var dp=0;
    switch(p.mode){
        case 'area':var a=(dimVals[0]||0)*(dimVals[1]||0);if(isCm)a/=10000;dp=a*p.ppu;break;
        case 'linear':var l=dimVals[0]||0;if(isCm)l/=100;dp=l*p.ppu;break;
        case 'volume':var v=(dimVals[0]||0)*(dimVals[1]||0)*(dimVals[2]||0);if(isCm)v/=1000000;dp=v*p.ppu;break;
        case 'weight':dp=(dimVals[0]||0)*p.ppu;break;
    }
    // Opts
    var op=0;
    document.querySelectorAll('.mc-opt').forEach(function(el){
        var t=el.dataset.type;
        if(t==='checkbox'&&el.checked)op+=parseFloat(el.dataset.price)||0;
        else if(t==='select'&&el.value){var sel=el.options[el.selectedIndex];op+=parseFloat(sel?.dataset.price)||0}
        else if(t==='number')op+=(parseInt(el.value)||0)*(parseFloat(el.dataset.price)||0);
    });
    document.getElementById('mc-dprice').textContent=fmt(dp);
    document.getElementById('mc-oprice').textContent=fmt(op);
    document.getElementById('mc-total').textContent=fmt(base+dp+op);
}
function confirmCustom(){
    if(!pendingCustom)return;
    var p=pendingCustom;
    var dimData={},optData={};
    document.querySelectorAll('.mc-dim').forEach(function(el,i){dimData['dim_'+i]=el.value||'0'});
    document.querySelectorAll('.mc-opt').forEach(function(el){
        var i=el.dataset.idx,t=el.dataset.type;
        if(t==='checkbox')optData['opt_'+i]=el.checked?'yes':'no';
        else optData['opt_'+i]=el.value||'';
    });
    var totalStr=document.getElementById('mc-total').textContent;
    var total=parseFloat(totalStr.replace(/[^\d.]/g,''))||p.price;
    cart.push({id:p.id,name:p.name+'🏭',price:total,qty:1,customData:{dims:dimData,opts:optData}});
    snd('add');closeCustom();renderCart();
}
function closeCustom(){document.getElementById('m-custom').classList.remove('show');pendingCustom=null}
function renderCart(){
    var $c=document.getElementById('pos-items');
    if(!cart.length){$c.innerHTML='<div class="pos-empty"><div style="font-size:40px;opacity:.4;margin-bottom:6px">🛒</div>السلة فارغة</div>';calc();return}
    var h='';cart.forEach(function(i,x){
        h+='<div class="pos-ci"><div class="pos-ci-info"><div class="pos-ci-name">'+i.name+'</div><div class="pos-ci-price">'+fmt(i.price)+' × '+i.qty+'</div></div>';
        h+='<div class="pos-ci-qty"><button class="mi" onclick="cQty('+x+',-1)">−</button><span>'+i.qty+'</span><button class="pl" onclick="cQty('+x+',1)">+</button></div>';
        h+='<div class="pos-ci-total">'+fmt(i.price*i.qty)+'</div>';
        h+='<button class="pos-ci-rm" onclick="rmItem('+x+')">✕</button></div>';
    });
    $c.innerHTML=h;
    // Auto scroll to bottom on new item
    $c.scrollTop=$c.scrollHeight;
    calc();
}
function cQty(x,d){cart[x].qty=Math.max(1,cart[x].qty+d);renderCart()}
function rmItem(x){cart.splice(x,1);snd('rm');renderCart()}
function clearCart(){if(cart.length&&confirm('إفراغ السلة؟')){cart=[];snd('rm');renderCart()}}

// ═══ DELIVERY ═══
function setDel(el){document.querySelectorAll('.pos-del-btn').forEach(function(e){e.classList.remove('on')});el.classList.add('on');del=el.dataset.d;document.getElementById('ship-fields').style.display=del==='home_delivery'?'block':'none';shipC=0;calc()}
document.getElementById('c-wil')?.addEventListener('change',function(){shipC=parseFloat(this.options[this.selectedIndex]?.dataset.s||0);calc()});

// ═══ CALC ═══
function calc(){
    var sub=0;cart.forEach(function(i){sub+=i.price*i.qty});
    var disc=Math.max(0,parseFloat(document.getElementById('c-disc')?.value||0));
    var grand=Math.max(0,sub+shipC-disc);
    document.getElementById('t-sub').textContent=fmt(sub);
    document.getElementById('t-ship').textContent=fmt(shipC);
    var dr=document.getElementById('t-disc-row');
    if(disc>0){dr.style.display='flex';document.getElementById('t-disc').textContent='-'+fmt(disc)}else dr.style.display='none';
    document.getElementById('t-grand').textContent=fmt(grand);
    document.getElementById('pos-count').textContent=cart.length+' عنصر';
    document.getElementById('btn-pay').disabled=!cart.length;
}
document.getElementById('c-disc')?.addEventListener('input',calc);

// ═══ PAYMENT ═══
function openPay(){if(!cart.length)return;document.getElementById('m-total').textContent=document.getElementById('t-grand').textContent;document.getElementById('m-pay').classList.add('show')}
function closePay(){document.getElementById('m-pay').classList.remove('show')}
function setPM(el){document.querySelectorAll('.pos-pm').forEach(function(e){e.classList.remove('on')});el.classList.add('on');pm=el.dataset.pm}

if(ENT&&document.getElementById('m-recv')){
    document.getElementById('m-recv').addEventListener('input',function(){
        var t=parseFloat(document.getElementById('t-grand').textContent.replace(/[^\d.]/g,''))||0;
        var r=parseFloat(this.value)||0;var ch=r-t;
        var $c=document.getElementById('m-change');
        if(r>0&&ch>=0){$c.textContent='💰 الباقي: '+fmt(ch);$c.style.display='block'}else $c.style.display='none';
    });
}

function confirmOrder(){
    var $b=document.getElementById('btn-confirm');$b.disabled=true;$b.textContent='⏳...';
    var fd=new FormData();
    fd.append('action','dzqcod_pos_create_order');fd.append('nonce',NC);
    fd.append('items',JSON.stringify(cart.map(function(i){return{id:i.id,name:i.name,price:i.price,qty:i.qty,customData:i.customData||null}})));
    fd.append('customer_name',document.getElementById('c-name').value||'عميل POS');
    fd.append('customer_phone',document.getElementById('c-phone').value||'');
    fd.append('delivery_type',del);
    fd.append('wilaya',document.getElementById('c-wil')?.value||'');
    fd.append('address',document.getElementById('c-addr')?.value||'');
    fd.append('payment_method',pm);
    fd.append('discount',document.getElementById('c-disc')?.value||'0');
    fd.append('note',document.getElementById('c-note')?.value||'');
    fetch(AX,{method:'POST',body:fd}).then(r=>r.json()).then(function(r){
        $b.disabled=false;$b.innerHTML='✅ تأكيد <span style="font-size:11px;opacity:.7">(F12)</span>';
        if(r.success){snd('ok');closePay();showReceipt(r.data.receipt);cart=[];renderCart();
            ['c-name','c-phone','c-disc','c-note'].forEach(function(id){var e=document.getElementById(id);if(e)e.value=''})}
        else alert(r.data?.message||'خطأ');
    }).catch(function(){$b.disabled=false;$b.textContent='✅ تأكيد';alert('خطأ في الاتصال')});
}

// ═══ RECEIPT ═══
function showReceipt(r){
    document.getElementById('r-oid').textContent='طلب #'+r.order_id;
    var h='<h3>'+SN+'</h3><div style="text-align:center;font-size:10px;color:#888">'+r.date+'<br>طلب #'+r.order_id+'</div>';
    h+='<table><tr style="border-bottom:1px solid #eee"><td><b>المنتج</b></td><td style="text-align:center"><b>الكمية</b></td><td style="text-align:left"><b>السعر</b></td></tr>';
    r.items.forEach(function(i){h+='<tr><td>'+i.name+'</td><td style="text-align:center">'+i.qty+'</td><td style="text-align:left">'+fmt(i.price*i.qty)+'</td></tr>'});
    h+='</table>';
    h+='<div style="display:flex;justify-content:space-between;font-size:10px"><span>المجموع</span><span>'+r.subtotal+' دج</span></div>';
    if(+r.shipping>0) h+='<div style="display:flex;justify-content:space-between;font-size:10px"><span>الشحن</span><span>'+r.shipping+' دج</span></div>';
    if(+r.discount>0) h+='<div style="display:flex;justify-content:space-between;font-size:10px;color:red"><span>خصم</span><span>-'+r.discount+' دج</span></div>';
    h+='<div class="r-total">'+r.total+' دج</div>';
    h+='<div style="text-align:center;font-size:9px;color:#888;margin-top:6px">'+r.delivery+' • '+r.payment;
    if(r.customer&&r.customer!=='عميل POS') h+='<br>'+r.customer;
    if(r.phone) h+=' • '+r.phone;
    h+='<br>شكراً لكم! ⚡ NIBRA TECHNOLOGY</div>';
    document.getElementById('pos-receipt').innerHTML=h;
    document.getElementById('m-receipt').classList.add('show');
}
function printReceipt(){window.print()}
function closeReceipt(){document.getElementById('m-receipt').classList.remove('show')}

function snd(t){try{var a=document.getElementById('snd-'+(t==='ok'?'ok':t));if(a){a.currentTime=0;a.play()}}catch(e){}}
function fmt(n){return Math.round(n).toLocaleString('ar-DZ')+' دج'}

// KEYBOARD SHORTCUTS
document.addEventListener('keydown',function(e){
    if(e.key==='F2'){e.preventDefault();document.getElementById('pos-search').focus()}
    if(e.key==='F9'&&cart.length){e.preventDefault();openPay()}
    if(e.key==='Escape'){closePay();closeReceipt()}
    if(e.key==='F12'&&document.getElementById('m-pay').classList.contains('show')){e.preventDefault();confirmOrder()}
});
</script>
</body>
</html>
<?php exit; ?>
