<?php defined('ABSPATH') || exit;
$oid = absint($_GET['id'] ?? 0);
$o = $oid ? wc_get_order($oid) : null;
if(!$o){ echo '<div class="dza-card" style="text-align:center;padding:40px"><h2>الطلب غير موجود</h2><a href="'.admin_url('admin.php?page=dzqcod-orders').'" class="dza-btn primary">العودة</a></div>'; return; } // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe static HTML
$st = str_replace('wc-','',$o->get_status());
$ws = \DZQCOD\Core::ST[$st] ?? ['l'=>$st,'c'=>'#64748b','i'=>'📋'];
$tracking = $o->get_meta('_dzqcod_tracking_number');
$provider = $o->get_meta('_dzqcod_shipping_provider') ?: \DZQCOD\Core::opt('shipping_provider','yalidine');
$phone = $o->get_billing_phone(); $phone2 = $o->get_meta('_dzqcod_phone2');
$name = trim($o->get_billing_first_name().' '.$o->get_billing_last_name());
$wilaya = $o->get_billing_state(); $commune = $o->get_billing_city();
$addr = $o->get_billing_address_1(); $note = $o->get_customer_note();
$source = $o->get_meta('_dzqcod_source') ?: 'web';
$fraud_score = (int)$o->get_meta('_dzqcod_fraud_score');
$delivery_mode = $o->get_meta('_dzqcod_delivery_mode') ?: 'home';
$dims_json = $o->get_meta('_dzqcod_custom_dimensions');
$opts_json = $o->get_meta('_dzqcod_custom_options');
$uploaded = $o->get_meta('_dzqcod_uploaded_files');
$custom_note = $o->get_meta('_dzqcod_custom_order_note');
$color = $o->get_meta('_dzqcod_color'); $size = $o->get_meta('_dzqcod_size');
$date_created = $o->get_date_created() ? $o->get_date_created()->format('Y-m-d H:i') : '-';
$payment = $o->get_payment_method_title() ?: 'COD';
$operator = $o->get_meta('_dzqcod_pos_operator');
$wa = preg_replace('/^0/','213',$phone);
$utm = json_decode($o->get_meta('_dzqcod_utm_data') ?: '{}', true);
?>
<div class="wrap dza-wrap" dir="rtl">
<?php include __DIR__.'/nav.php'; ?>
<div class="dza-header">
<h1><?php echo esc_html($ws['i']); ?> طلب #<?php echo esc_html($oid); ?></h1>
<div style="display:flex;gap:8px;align-items:center">
<span style="background:<?php echo esc_html($ws['c']);?>;color:#fff;padding:4px 14px;border-radius:8px;font-size:13px;font-weight:800"><?php echo esc_html($ws['l']); ?></span>
<a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod-orders')); ?>" class="dza-btn ghost">↩️ الطلبات</a>
</div></div>
<div class="dza-content">
<div style="display:grid;grid-template-columns:1fr 340px;gap:16px;align-items:start">
<!-- LEFT -->
<div>
<div class="dza-card"><h3 style="font-size:15px;border:none;margin:0 0 10px">📦 المنتجات</h3>
<table class="dza-table" style="margin:0"><thead><tr><th>المنتج</th><th style="text-align:center">الكمية</th><th>الوحدة</th><th>الإجمالي</th></tr></thead><tbody>
<?php foreach($o->get_items() as $item):
$pid=$item->get_product_id(); $ic=get_post_meta($pid,'_dzqcod_custom_enabled',true)==='yes';
$q=$item->get_quantity(); $t=(float)$item->get_total(); $u=$q>0?$t/$q:0; ?>
<tr><td><strong><?php echo esc_html($item->get_name()); ?></strong>
<?php if($ic): ?><span style="background:#fef3c7;color:#92400e;padding:1px 6px;border-radius:4px;font-size:9px;font-weight:700;margin-right:4px">🏭</span><?php endif; ?>
<?php if($color): ?><span style="background:#e0e7ff;color:#4338ca;padding:1px 6px;border-radius:4px;font-size:9px">🎨 <?php echo esc_html($color); ?></span><?php endif; ?>
<?php if($size): ?><span style="background:#fce7f3;color:#9d174d;padding:1px 6px;border-radius:4px;font-size:9px">📐 <?php echo esc_html($size); ?></span><?php endif; ?>
</td><td style="text-align:center;font-weight:700"><?php echo esc_html($q); ?></td><td><?php echo number_format($u,0); ?> دج</td><td style="font-weight:800"><?php echo number_format($t,0); ?> دج</td></tr>
<?php endforeach; ?>
<?php if((float)$o->get_shipping_total()>0): ?>
<tr style="background:#f0fdf4"><td colspan="3">🚚 <?php echo esc_html($delivery_mode==='desk'?'مكتب':'منزل'); ?></td><td style="font-weight:700"><?php echo number_format((float)$o->get_shipping_total(),0); ?> دج</td></tr>
<?php endif; ?>
<?php foreach($o->get_fees() as $fee): ?>
<tr style="background:#fef2f2"><td colspan="3" style="color:#ef4444"><?php echo esc_html($fee->get_name()); ?></td><td style="font-weight:700;color:#ef4444"><?php echo number_format((float)$fee->get_total(),0); ?> دج</td></tr>
<?php endforeach; ?>
</tbody>
<tfoot><tr style="background:linear-gradient(135deg,#ecfdf5,#d1fae5)"><td colspan="3" style="font-weight:900;font-size:16px">💰 الإجمالي</td><td style="font-weight:900;font-size:20px;color:#059669"><?php echo number_format((float)$o->get_total(),0); ?> دج</td></tr></tfoot>
</table></div>

<?php if($dims_json || $opts_json || $uploaded || $custom_note): ?>
<div class="dza-card"><h3 style="font-size:15px;border:none;margin:0 0 10px">🏭 المنتج المخصص</h3>
<?php if($dims_json): $dims=json_decode($dims_json,true); if(is_array($dims)): ?>
<div style="margin-bottom:10px"><strong style="font-size:12px;color:#667eea">📐 الأبعاد</strong>
<div style="display:flex;flex-wrap:wrap;gap:6px;margin-top:4px">
<?php foreach($dims as $dk=>$dv): ?><span style="background:#e0e7ff;color:#4338ca;padding:4px 10px;border-radius:6px;font-size:12px;font-weight:600"><?php echo esc_html(str_replace('dim_','',$dk).': '.$dv); ?></span><?php endforeach; ?>
</div></div><?php endif; endif; ?>
<?php if($opts_json): $opts=json_decode($opts_json,true); if(is_array($opts)): ?>
<div style="margin-bottom:10px"><strong style="font-size:12px;color:#f97316">✨ الخيارات</strong>
<div style="display:flex;flex-wrap:wrap;gap:6px;margin-top:4px">
<?php foreach($opts as $ok=>$ov): if($ov==='no'||$ov==='')continue; ?><span style="background:#fef3c7;color:#92400e;padding:4px 10px;border-radius:6px;font-size:12px;font-weight:600"><?php echo esc_html(str_replace('opt_','',$ok).': '.$ov); ?></span><?php endforeach; ?>
</div></div><?php endif; endif; ?>
<?php if($uploaded): $files=array_filter(array_map('trim',explode(',',$uploaded))); ?>
<div style="margin-bottom:10px"><strong style="font-size:12px;color:#22c55e">📎 ملفات العميل</strong>
<div style="margin-top:4px"><?php foreach($files as $fu): $ext=strtolower(pathinfo($fu,PATHINFO_EXTENSION)); ?>
<a href="<?php echo esc_url($fu); ?>" target="_blank" style="display:inline-flex;align-items:center;gap:4px;padding:6px 12px;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:6px;margin:2px;font-size:12px;text-decoration:none;color:#166534">
<?php echo in_array($ext,['jpg','jpeg','png','gif','webp'])?'🖼️':'📄'; echo esc_html(basename($fu)); ?> ⬇️</a>
<?php endforeach; ?></div></div><?php endif; ?>
<?php if($custom_note): ?>
<div><strong style="font-size:12px;color:#64748b">📝 ملاحظة الورشة</strong>
<div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:10px;margin-top:4px;font-size:13px"><?php echo esc_html(nl2br(esc_html($custom_note))); ?></div></div><?php endif; ?>
</div><?php endif; ?>

<div class="dza-card"><h3 style="font-size:15px;border:none;margin:0 0 10px">🚚 الشحن</h3>
<?php if($tracking): ?>
<div style="display:flex;align-items:center;gap:10px;margin-bottom:10px">
<div style="font-family:monospace;font-size:16px;background:#f1f5f9;padding:8px 14px;border-radius:8px;letter-spacing:1px;flex:1;cursor:pointer" onclick="navigator.clipboard.writeText('<?php echo esc_html(esc_js($tracking)); ?>')"><?php echo esc_html($tracking); ?></div>
<span style="padding:4px 10px;border-radius:6px;font-size:12px;font-weight:700;background:#e2e8f0"><?php echo esc_html(strtoupper($provider)); ?></span>
</div>
<button class="dza-btn ghost" style="font-size:12px" onclick="trackOrder(<?php echo esc_html($oid); ?>)">🔍 تتبع</button>
<div id="track-timeline" style="margin-top:10px;display:none"></div>
<?php else: ?>
<p style="color:#94a3b8;margin:0 0 10px">لم تُنشأ شحنة بعد</p>
<button class="dza-btn primary" onclick="jQuery.post(dza.ajax,{action:'dzqcod_ship_create',nonce:dza.nonce,order_id:<?php echo esc_html($oid); ?>},function(r){if(r.success)location.reload();else alert(r.data?r.data.message:'خطأ')})">🚚 إنشاء شحنة</button>
<?php endif; ?></div>

<div class="dza-card"><h3 style="font-size:15px;border:none;margin:0 0 10px">🔄 تغيير الحالة</h3>
<div style="display:flex;flex-wrap:wrap;gap:6px">
<?php foreach(\DZQCOD\Core::ST as $sk=>$sv): ?>
<button class="dza-btn <?php echo esc_html($sk===$st?'primary':'ghost'); ?>" style="font-size:11px;padding:6px 12px" onclick="if(confirm('تغيير؟'))jQuery.post(dza.ajax,{action:'dzqcod_update_order_status',nonce:dza.nonce,order_id:<?php echo esc_html($oid); ?>,status:'<?php echo esc_html($sk); ?>'},function(){location.reload()})" <?php echo esc_html($sk===$st?'disabled':''); ?>><?php echo esc_html($sv['i'].' '.$sv['l']); ?></button>
<?php endforeach; ?></div></div>

<div class="dza-card"><h3 style="font-size:15px;border:none;margin:0 0 10px">📝 ملاحظات</h3>
<div style="max-height:200px;overflow-y:auto;margin-bottom:10px">
<?php foreach(wc_get_order_notes(['order_id'=>$oid,'limit'=>15]) as $n): ?>
<div style="padding:6px 8px;border-right:3px solid <?php echo esc_html($n->added_by==='system'?'#94a3b8':'#667eea'); ?>;margin-bottom:4px;background:#f8fafc;border-radius:0 6px 6px 0;font-size:12px">
<span style="color:#94a3b8;font-size:10px"><?php echo esc_html($n->date_created->format('m/d H:i')); ?></span> <?php echo wp_kses_post($n->content); ?>
</div><?php endforeach; ?>
</div>
<div style="display:flex;gap:6px">
<input type="text" id="new-note" placeholder="أضف ملاحظة..." style="flex:1;padding:8px;border:1px solid #ddd;border-radius:8px">
<button class="dza-btn primary" style="font-size:12px" onclick="jQuery.post(dza.ajax,{action:'dzqcod_add_order_note',nonce:dza.nonce,order_id:<?php echo esc_html($oid); ?>,note:jQuery('#new-note').val()},function(){location.reload()})">➕</button>
</div></div>
</div><!-- end left -->

<!-- RIGHT SIDEBAR -->
<div>
<div class="dza-card"><h3 style="font-size:15px;border:none;margin:0 0 10px">👤 العميل</h3>
<div style="font-size:14px;font-weight:800;margin-bottom:8px"><?php echo esc_html($name); ?></div>
<div style="display:flex;flex-direction:column;gap:4px">
<a href="tel:<?php echo esc_attr($phone); ?>" style="display:flex;align-items:center;gap:6px;padding:8px;background:#f0fdf4;border-radius:8px;text-decoration:none;color:#166534;font-size:13px;font-weight:600">📱 <?php echo esc_html($phone); ?></a>
<?php if($phone2): ?><a href="tel:<?php echo esc_attr($phone2); ?>" style="display:flex;align-items:center;gap:6px;padding:8px;background:#f0f9ff;border-radius:8px;text-decoration:none;color:#0369a1;font-size:12px">📞 <?php echo esc_html($phone2); ?></a><?php endif; ?>
<a href="https://wa.me/<?php echo esc_html($wa); ?>" target="_blank" style="display:flex;align-items:center;gap:6px;padding:8px;background:#dcfce7;border-radius:8px;text-decoration:none;color:#166534;font-size:13px">💬 واتساب</a>
</div>
<div style="margin-top:10px;padding-top:10px;border-top:1px solid #f0f0f0;font-size:13px">
<div style="margin-bottom:4px">📍 <strong><?php echo esc_html($wilaya); ?></strong> — <?php echo esc_html($commune); ?></div>
<?php if($addr): ?><div style="color:#64748b">🏠 <?php echo esc_html($addr); ?></div><?php endif; ?>
<?php if($note): ?><div style="background:#fffbeb;padding:6px;border-radius:6px;font-size:12px;color:#92400e;margin-top:4px">💭 <?php echo esc_html($note); ?></div><?php endif; ?>
</div></div>

<div class="dza-card"><h3 style="font-size:15px;border:none;margin:0 0 10px">📋 معلومات</h3>
<div style="display:flex;flex-direction:column;gap:4px;font-size:13px">
<div style="display:flex;justify-content:space-between"><span style="color:#64748b">📅</span><span style="font-weight:600"><?php echo esc_html($date_created); ?></span></div>
<div style="display:flex;justify-content:space-between"><span style="color:#64748b">💳</span><span style="font-weight:600"><?php echo esc_html($payment); ?></span></div>
<div style="display:flex;justify-content:space-between"><span style="color:#64748b">📦</span><span style="font-weight:600"><?php echo esc_html($delivery_mode==='desk'?'🏪 مكتب':'🏠 منزل'); ?></span></div>
<div style="display:flex;justify-content:space-between"><span style="color:#64748b">📱</span><span style="font-weight:600"><?php echo esc_html($source); ?></span></div>
<?php if($operator): ?><div style="display:flex;justify-content:space-between"><span style="color:#64748b">👤 POS</span><span><?php echo esc_html($operator); ?></span></div><?php endif; ?>
<?php if($fraud_score>0): ?><div style="display:flex;justify-content:space-between"><span style="color:#64748b">🛡️</span><span style="color:<?php echo esc_html($fraud_score>70?'#ef4444':'#f97316'); ?>;font-weight:800"><?php echo esc_html($fraud_score); ?>%</span></div><?php endif; ?>
</div></div>

<div class="dza-card">
<a href="<?php echo esc_url($o->get_edit_order_url()); ?>" class="dza-btn ghost" style="width:100%;font-size:12px;text-align:center;margin-bottom:4px" target="_blank">📝 WooCommerce</a>
<button class="dza-btn ghost" style="width:100%;font-size:12px" onclick="window.print()">🖨️ طباعة</button>
</div>
</div></div></div></div></div></div>

<script>
function trackOrder(id){var $t=jQuery('#track-timeline').show().html('<div style="text-align:center;padding:20px;color:#94a3b8">⏳</div>');jQuery.post(dza.ajax,{action:'dzqcod_ship_track',nonce:dza.nonce,order_id:id},function(r){if(!r.success||!r.data.events){$t.html('<div style="color:#ef4444">لا توجد بيانات</div>');return}var h='<div style="border-right:3px solid #667eea;padding-right:12px">';r.data.events.forEach(function(e){h+='<div style="margin-bottom:8px"><div style="font-size:10px;color:#94a3b8">'+e.date+'</div><div style="font-size:13px;font-weight:600">'+e.status+'</div></div>'});$t.html(h+'</div>')})}
</script>
