<?php defined('ABSPATH') || exit;
$S=\DZQCOD\Core::ST;
$queue=\DZQCOD\Core::i()->get_call_queue(50);
$sym=\DZQCOD\Core::opt('currency_symbol','دج');
$total_queue=count($queue);

// Stats
$pending=0;$callback=0;$no_answer=0;
foreach($queue as $q){
    $st=$q['status']??'';
    if($st==='pending-call')$pending++;
    elseif($st==='callback')$callback++;
    elseif($st==='no-answer')$no_answer++;
}

// Today's confirmed count
$today_confirmed=(int)wc_orders_count('wc-confirmed');

$outcomes=[
    'confirmed' =>['l'=>'✅ مؤكد',     'c'=>'#10b981','k'=>'C'],
    'callback'  =>['l'=>'📞 معاودة',   'c'=>'#f59e0b','k'=>'B'],
    'no-answer' =>['l'=>'❌ لا يجيب',   'c'=>'#94a3b8','k'=>'N'],
    'cancelled' =>['l'=>'🚫 ملغي',     'c'=>'#ef4444','k'=>'X'],
    'fake'      =>['l'=>'⚠️ مزيف',     'c'=>'#1e293b','k'=>'F'],
    'postponed' =>['l'=>'⏰ مؤجل',     'c'=>'#e67e22','k'=>'P'],
];
?>
<?php include __DIR__.'/_layout_start.php'; ?>
<div class="dza-header">
<h1>📞 مركز الاتصال</h1>
<div style="display:flex;gap:8px;align-items:center">
<span style="font-size:11px;color:#94a3b8"><?php echo $total_queue; ?> في الانتظار</span>
</div>
</div>
<div class="dza-content">

<!-- Stats Bar -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:16px">
<div class="dza-card" style="padding:12px;text-align:center;border-right:4px solid #f59e0b">
<div style="font-size:28px;font-weight:900;color:#f59e0b"><?php echo $pending;?></div>
<div style="font-size:10px;color:#94a3b8">⏳ بانتظار الاتصال</div>
</div>
<div class="dza-card" style="padding:12px;text-align:center;border-right:4px solid #e67e22">
<div style="font-size:28px;font-weight:900;color:#e67e22"><?php echo $callback;?></div>
<div style="font-size:10px;color:#94a3b8">📞 معاودة اتصال</div>
</div>
<div class="dza-card" style="padding:12px;text-align:center;border-right:4px solid #94a3b8">
<div style="font-size:28px;font-weight:900;color:#94a3b8"><?php echo $no_answer;?></div>
<div style="font-size:10px;color:#94a3b8">❌ لا يجيب</div>
</div>
<div class="dza-card" style="padding:12px;text-align:center;border-right:4px solid #10b981">
<div style="font-size:28px;font-weight:900;color:#10b981"><?php echo $today_confirmed;?></div>
<div style="font-size:10px;color:#94a3b8">✅ مؤكد اليوم</div>
</div>
</div>

<?php if(empty($queue)): ?>
<div class="dza-card" style="text-align:center;padding:48px">
<div style="font-size:56px;margin-bottom:12px">🎉</div>
<div style="font-size:18px;font-weight:900;color:#10b981;margin-bottom:4px">ممتاز! لا توجد طلبات في الانتظار</div>
<div style="color:#94a3b8;font-size:13px">كل الطلبات تم التعامل معها</div>
</div>

<?php else: ?>

<!-- Call Queue -->
<?php foreach($queue as $i=>$q):
$sc=$S[$q['status']]??['c'=>'#94a3b8','l'=>$q['status'],'i'=>'📋'];
$o_obj=wc_get_order($q['id']);
$cb_slot=$o_obj?$o_obj->get_meta('_dzqcod_callback_slot_label'):'';
$otp_ok=$o_obj?$o_obj->get_meta('_dzqcod_otp_confirmed')==='yes':false;
$fraud=(int)($q['fraud']??0);
$attempts=(int)($q['attempts']??0);

// Next Best Action logic
$nba='📞 اتصل الآن';$nba_c='#3b82f6';
if($q['status']==='callback'){$nba='📞 معاودة الاتصال';$nba_c='#e67e22';}
elseif($q['status']==='no-answer'&&$attempts>=3){$nba='💬 أرسل واتساب';$nba_c='#25d366';}
elseif($q['status']==='no-answer'){$nba='🔄 أعد المحاولة';$nba_c='#6366f1';}
if($fraud>=60){$nba='⚠️ تحقق أولاً — Fraud '.$fraud.'%';$nba_c='#ef4444';}
if($otp_ok){$nba='✅ مؤكد OTP — أكّد فوراً';$nba_c='#10b981';}
?>
<div class="dza-card" id="cc-<?php echo $q['id'];?>" style="padding:0;overflow:hidden;margin-bottom:10px;border-right:4px solid <?php echo esc_attr($sc['c']);?>;transition:.3s" <?php if($i===0):?>data-first="1"<?php endif;?>>

<!-- Header -->
<div style="display:flex;align-items:center;gap:10px;padding:14px 16px;background:#f8fafc;border-bottom:1px solid #f0f0f0">
<span style="font-weight:900;font-size:16px;color:#6366f1">#<?php echo $q['id'];?></span>
<span style="background:<?php echo esc_attr($sc['c']);?>;color:#fff;padding:2px 10px;border-radius:6px;font-size:10px;font-weight:700"><?php echo esc_html($sc['i'].' '.$sc['l']);?></span>
<?php if($attempts):?><span style="font-size:10px;color:#94a3b8">📞 محاولة <?php echo $attempts;?></span><?php endif;?>
<?php if($fraud>=50):?><span style="background:#fef2f2;color:#ef4444;padding:2px 8px;border-radius:6px;font-size:10px;font-weight:700">🛡️ خطر <?php echo $fraud;?>%</span><?php endif;?>
<?php if($otp_ok):?><span style="background:#f0fdf4;color:#10b981;padding:2px 8px;border-radius:6px;font-size:10px;font-weight:700">✅ OTP</span><?php endif;?>
<?php if($cb_slot):?><span style="background:#eef2ff;color:#6366f1;padding:2px 8px;border-radius:6px;font-size:10px">📅 <?php echo esc_html($cb_slot);?></span><?php endif;?>
<!-- Next Best Action -->
<span style="margin-right:auto;background:<?php echo esc_attr($nba_c);?>;color:#fff;padding:4px 12px;border-radius:8px;font-size:11px;font-weight:700"><?php echo esc_html($nba);?></span>
</div>

<!-- Body -->
<div style="padding:14px 16px">
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:10px">
<!-- Customer Info -->
<div>
<div style="font-size:16px;font-weight:800;margin-bottom:4px"><?php echo esc_html($q['name']);?></div>
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
<a href="tel:<?php echo esc_attr($q['phone']);?>" style="background:#10b981;color:#fff;padding:6px 14px;border-radius:8px;font-size:13px;font-weight:700;text-decoration:none;display:inline-flex;align-items:center;gap:4px">📞 <?php echo esc_html($q['phone']);?></a>
<?php if($q['phone2']):?><a href="tel:<?php echo esc_attr($q['phone2']);?>" style="background:#3b82f6;color:#fff;padding:6px 12px;border-radius:8px;font-size:12px;text-decoration:none">📱 <?php echo esc_html($q['phone2']);?></a><?php endif;?>
<a href="https://wa.me/213<?php echo esc_attr(ltrim($q['phone'],'0'));?>" target="_blank" style="background:#25d366;color:#fff;padding:6px 12px;border-radius:8px;font-size:12px;text-decoration:none">💬 واتساب</a>
</div>
<div style="font-size:12px;color:#64748b;margin-top:6px">📍 <?php echo esc_html(($q['wilaya']?:'-').' — '.($q['commune']?:'-'));?></div>
</div>
<!-- Order Info -->
<div style="text-align:left;direction:ltr">
<div style="font-size:24px;font-weight:900;color:#10b981;text-align:right;direction:rtl"><?php echo number_format((float)$q['total'],0);?> <?php echo esc_html($sym);?></div>
<div style="font-size:12px;color:#64748b;margin-top:4px;text-align:right;direction:rtl">🛒 <?php echo esc_html($q['items']);?></div>
<?php if($q['color']):?><span style="font-size:11px;color:#94a3b8">🎨 <?php echo esc_html($q['color']);?></span><?php endif;?>
<?php if($q['size']):?><span style="font-size:11px;color:#94a3b8;margin-right:8px">📐 <?php echo esc_html($q['size']);?></span><?php endif;?>
</div>
</div>

<?php if($q['notes']):?><div style="background:#fffbeb;border-radius:6px;padding:6px 10px;font-size:11px;color:#92400e;margin-bottom:8px">📝 <?php echo esc_html($q['notes']);?></div><?php endif;?>

<!-- Script Suggestion -->
<div style="background:#f0f9ff;border-radius:8px;padding:8px 12px;margin-bottom:10px;font-size:11px;color:#1e40af;border-right:3px solid #3b82f6">
💬 <strong>نص مقترح:</strong> "مرحباً <?php echo esc_html($q['name']);?>، نتصل بك لتأكيد طلبك رقم <?php echo $q['id'];?> — <?php echo esc_html($q['items']);?> بمبلغ <?php echo number_format((float)$q['total'],0);?> <?php echo esc_html($sym);?>. التوصيل لـ <?php echo esc_html($q['wilaya']?:'-');?>. هل نأكد الطلب؟"
</div>

<!-- Outcome Buttons -->
<div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:8px">
<?php foreach($outcomes as $k=>$v):?>
<button class="dza-btn sm log-call" data-id="<?php echo $q['id'];?>" data-outcome="<?php echo esc_attr($k);?>" style="padding:8px 14px;border:none;border-radius:8px;font-size:11px;font-weight:700;cursor:pointer;background:<?php echo esc_attr($v['c']);?>;color:#fff;font-family:inherit;transition:.2s" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='none'" title="اختصار: <?php echo esc_attr($v['k']);?>"><?php echo esc_html($v['l']);?></button>
<?php endforeach;?>
</div>

<!-- Notes -->
<div style="display:flex;gap:6px">
<input type="text" class="call-notes" data-id="<?php echo $q['id'];?>" placeholder="ملاحظات سريعة..." style="flex:1;padding:8px 12px;border:2px solid #e2e8f0;border-radius:8px;font-size:12px;font-family:inherit;transition:.2s" onfocus="this.style.borderColor='#6366f1'" onblur="this.style.borderColor='#e2e8f0'">
</div>
</div>
</div>
<?php endforeach;?>

<!-- Next Call Button (floating) -->
<?php if($total_queue > 1): ?>
<div style="position:sticky;bottom:16px;text-align:center;z-index:10">
<button onclick="dzNextCall()" style="background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;border:none;padding:12px 32px;border-radius:12px;font-size:14px;font-weight:800;cursor:pointer;box-shadow:0 4px 24px rgba(99,102,241,.4);font-family:inherit;transition:.3s" onmouseover="this.style.transform='translateY(-3px)'" onmouseout="this.style.transform='none'">📞 الطلب التالي ↓</button>
</div>
<?php endif;?>

<?php endif;?>

</div>

<script>
// Log call outcome
jQuery(document).on('click','.log-call',function(){
    var $btn=jQuery(this),id=$btn.data('id'),outcome=$btn.data('outcome');
    var notes=jQuery('.call-notes[data-id="'+id+'"]').val()||'';
    $btn.text('⏳...');
    jQuery.post(ajaxurl,{action:'dzqcod_log_call',nonce:dza.nonce,order_id:id,outcome:outcome,notes:notes},function(r){
        if(r.success){
            var $card=jQuery('#cc-'+id);
            $card.css({opacity:.5,transform:'translateX(-20px)',transition:'.4s'});
            setTimeout(function(){$card.slideUp(300,function(){$card.remove()})},200);
        } else $btn.text('❌');
    });
});

// Next call - scroll to next card
function dzNextCall(){
    var cards=document.querySelectorAll('.dza-card[id^="cc-"]');
    for(var i=0;i<cards.length;i++){
        var r=cards[i].getBoundingClientRect();
        if(r.top>100){cards[i].scrollIntoView({behavior:'smooth',block:'center'});cards[i].style.boxShadow='0 0 0 3px #6366f1';setTimeout(function(c){c.style.boxShadow=''},1500,cards[i]);break;}
    }
}

// Keyboard shortcuts
document.addEventListener('keydown',function(e){
    if(e.target.tagName==='INPUT'||e.target.tagName==='TEXTAREA')return;
    var first=document.querySelector('.dza-card[id^="cc-"]');if(!first)return;
    var id=first.id.replace('cc-','');
    var map={'c':'confirmed','b':'callback','n':'no-answer','x':'cancelled','f':'fake','p':'postponed'};
    if(map[e.key.toLowerCase()]){
        first.querySelector('.log-call[data-outcome="'+map[e.key.toLowerCase()]+'"]').click();
    }
});
</script>

<?php include __DIR__.'/_layout_end.php'; ?>
