<?php defined('ABSPATH') || exit;
$action = $_GET['action'] ?? 'list';
$edit_id = absint($_GET['edit'] ?? 0);
$edit_p = $edit_id ? wc_get_product($edit_id) : null;
if($action==='edit' && !$edit_p) $action='list';
?>
<div class="wrap dza-wrap" dir="rtl">
<?php include __DIR__.'/nav.php'; ?>
<div class="dza-header">
<h1><?php echo wp_kses_post($action==='new'?'➕ منتج جديد':($action==='edit'?'✏️ تعديل: '.esc_html($edit_p->get_name()):'🏷️ المنتجات')); ?></h1>
<div style="display:flex;gap:8px">
<?php if($action==='list'): ?>
<a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod-products&action=new')); ?>" class="dza-btn primary">➕ إضافة منتج</a>
<a href="<?php echo esc_url(admin_url('edit.php?post_type=product')); ?>" target="_blank" class="dza-btn ghost" style="border-color:#7b2d8e;color:#7b2d8e">🔧 المنتجات في WooCommerce ↗</a>
<?php else: ?>
<a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod-products')); ?>" class="dza-btn ghost">↩️ العودة للقائمة</a>
<?php if($edit_id): ?><a href="<?php echo esc_url(admin_url('post.php?post='.$edit_id.'&action=edit')); ?>" target="_blank" class="dza-btn ghost" style="border-color:#7b2d8e;color:#7b2d8e">🔧 التعديل عبر WooCommerce ↗</a><?php endif; ?>
<?php endif; ?>
</div>
</div>
<div class="dza-content">

<?php
// ╔════════════════════════════════════════════╗
//  LIST VIEW
// ╚════════════════════════════════════════════╝
if($action==='list'):
$products = get_posts(['post_type'=>'product','posts_per_page'=>100,'post_status'=>['publish','draft'],'orderby'=>'date','order'=>'DESC']);
if(empty($products)): ?>
<div class="dza-card" style="text-align:center;padding:48px">
<div style="font-size:56px;margin-bottom:12px">📦</div>
<h3 style="border:none;color:#475569;font-size:18px">لا توجد منتجات بعد</h3>
<p style="color:#94a3b8;margin-bottom:16px">أنشئ أول منتج لبدء استقبال الطلبات</p>
<a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod-products&action=new')); ?>" class="dza-btn primary" style="padding:12px 32px">➕ إضافة منتج</a>
</div>
<?php else: ?>
<div class="dza-card" style="padding:0;overflow:hidden">
<table class="dza-table" style="margin:0">
<thead><tr><th style="width:50px"></th><th>المنتج</th><th>السعر</th><th>المخزون</th><th>النوع</th><th>الحالة</th><th style="width:120px"></th></tr></thead>
<tbody>
<?php 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';
    $is_dig=get_post_meta($pp->ID,'_dzqcod_digital',true)==='yes';
    $is_off=get_post_meta($pp->ID,'_dzqcod_disabled',true)==='yes';
    $has_t=(bool)get_post_meta($pp->ID,'_dzqcod_qty_pricing',true);
    $stk=$p->get_stock_quantity();
    $price_txt=$cpc_on?number_format((float)(get_post_meta($pp->ID,'_dzqcod_custom_base',true)?:0),0).' دج <small style="color:#94a3b8">+ أبعاد</small>':number_format((float)$p->get_price(),0).' دج';
?>
<tr>
<td><?php if($thumb): ?><img src="<?php echo esc_url($thumb); ?>" style="width:42px;height:42px;object-fit:cover;border-radius:8px"><?php else: ?><div style="width:42px;height:42px;background:#f1f5f9;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:20px">📦</div><?php endif; ?></td>
<td><strong><?php echo esc_html($p->get_name()); ?></strong>
<div style="font-size:10px;color:#94a3b8;margin-top:2px;direction:ltr;font-family:monospace">[dzqcod_order product_id="<?php echo esc_html($pp->ID); ?>"]</div></td>
<td style="font-weight:700"><?php echo esc_html($price_txt); ?></td>
<td><?php if($stk===null):?><span style="color:#22c55e">∞</span><?php elseif($stk>0):?><span style="color:#22c55e;font-weight:700"><?php echo esc_html($stk);?></span><?php else:?><span style="color:#ef4444;font-weight:700">نفد</span><?php endif;?></td>
<td style="font-size:11px"><?php
    $tags=[];
    if($cpc_on) $tags[]='<span style="background:#fef3c7;color:#92400e;padding:2px 8px;border-radius:6px;font-size:10px;font-weight:700">🏭 مخصص</span>';
    if($is_dig) $tags[]='<span style="background:#ede9fe;color:#5b21b6;padding:2px 8px;border-radius:6px;font-size:10px;font-weight:700">💾 رقمي</span>';
    if($has_t) $tags[]='<span style="background:#dbeafe;color:#1e40af;padding:2px 8px;border-radius:6px;font-size:10px;font-weight:700">🏷️ شرائح</span>';
    echo $tags ? implode(' ',$tags) : '<span style="color:#cbd5e1">عادي</span>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- badge HTML output
?></td>
<td><?php if($is_off):?><span class="dza-badge" style="background:#fee2e2;color:#dc2626">معطّل</span><?php elseif($pp->post_status==='draft'):?><span class="dza-badge" style="background:#f1f5f9;color:#64748b">مسودة</span><?php else:?><span class="dza-badge" style="background:#dcfce7;color:#166534">منشور</span><?php endif;?></td>
<td style="white-space:nowrap"><a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod-products&action=edit&edit='.$pp->ID)); ?>" class="dza-btn ghost" style="padding:5px 14px;font-size:12px">✏️ تعديل</a> <a href="<?php echo esc_url(admin_url('post.php?post='.$pp->ID.'&action=edit')); ?>" target="_blank" class="dza-btn ghost" style="padding:5px 10px;font-size:12px;border-color:#7b2d8e;color:#7b2d8e" title="WooCommerce">🔧</a> <button class="dza-btn ghost dzp-delete" data-id="<?php echo (int)$pp->ID; ?>" style="padding:5px 10px;font-size:12px;border-color:#ef4444;color:#ef4444" title="حذف">🗑️</button></td>
</tr>
<?php endforeach; ?>
</tbody></table>
</div>
<?php endif;

// ╔════════════════════════════════════════════╗
//  CREATE / EDIT VIEW
// ╚════════════════════════════════════════════╝
elseif($action==='new' || $action==='edit'):
$pid=$edit_id;
$name=$edit_p?$edit_p->get_name():''; $desc=$edit_p?$edit_p->get_description():'';
$price=$edit_p?(float)$edit_p->get_regular_price():0; $sale_price=$edit_p?(float)$edit_p->get_sale_price():0;
$thumb_id=$edit_p?$edit_p->get_image_id():0; $thumb_url=$thumb_id?wp_get_attachment_image_url($thumb_id,'medium'):'';
$status=$edit_p?$edit_p->get_status():'publish';
// DZQCOD
$dz_off=$pid?get_post_meta($pid,'_dzqcod_disabled',true):'';
$dz_colors=$pid?get_post_meta($pid,'_dzqcod_colors',true):'';
$dz_sizes=$pid?get_post_meta($pid,'_dzqcod_sizes',true):'';
$dz_badge=$pid?get_post_meta($pid,'_dzqcod_badge',true):'';
$dz_digital=$pid?get_post_meta($pid,'_dzqcod_digital',true):'';
$dz_wa=$pid?get_post_meta($pid,'_dzqcod_whatsapp',true):'';
$qj=$pid?(get_post_meta($pid,'_dzqcod_qty_pricing',true)?:''):'';
$tiers=$qj?json_decode($qj,true):[];
// Custom
$cpc_on=$pid?get_post_meta($pid,'_dzqcod_custom_enabled',true)==='yes':false;
$cpc_mode=$pid?(get_post_meta($pid,'_dzqcod_pricing_mode',true)?:'fixed'):'fixed';
$cpc_ppu=$pid?get_post_meta($pid,'_dzqcod_price_per_unit',true):'';
$cpc_unit=$pid?(get_post_meta($pid,'_dzqcod_unit_label',true)?:'م²'):'م²';
$cpc_base=$pid?get_post_meta($pid,'_dzqcod_custom_base',true):'';
$dims=$pid?(json_decode(get_post_meta($pid,'_dzqcod_dimensions',true)?:'',true)?:[]):[];
$opts=$pid?(json_decode(get_post_meta($pid,'_dzqcod_paid_options',true)?:'',true)?:[]):[];
$upload_on=$pid?get_post_meta($pid,'_dzqcod_upload_enabled',true)==='yes':false;
$note_on=$pid?get_post_meta($pid,'_dzqcod_custom_note',true)==='yes':false;
?>
<form id="dzp-form" data-pid="<?php echo esc_html($pid); ?>">
<div style="display:grid;grid-template-columns:1fr 320px;gap:16px;align-items:start">
<!-- LEFT -->
<div>
<div class="dza-card"><h3 style="font-size:16px">📋 معلومات المنتج</h3>
<div class="dzp-f"><label>اسم المنتج *</label><input type="text" name="name" value="<?php echo esc_attr($name);?>" placeholder="مثال: باب خشبي مخصص" required style="font-size:15px;font-weight:700;padding:12px"></div>
<div class="dzp-f"><label>وصف قصير</label><textarea name="description" rows="3" placeholder="وصف المنتج (اختياري)"><?php echo esc_html(esc_textarea($desc)); ?></textarea></div>
</div>

<!-- PRICING -->
<div class="dza-card" id="dzp-pricing-card"><h3 style="font-size:16px">💰 التسعير</h3>
<div id="dzp-normal-pricing" style="<?php echo esc_html($cpc_on?'display:none':''); ?>">
<div style="display:flex;gap:12px;flex-wrap:wrap">
<div class="dzp-f" style="flex:1;min-width:140px"><label>السعر (دج) *</label><input type="number" name="price" value="<?php echo esc_html($price>0?$price:''); ?>" placeholder="3500" min="0" style="font-size:16px;font-weight:800"></div>
<div class="dzp-f" style="flex:1;min-width:140px"><label>سعر التخفيض</label><input type="number" name="sale_price" value="<?php echo esc_html($sale_price>0?$sale_price:''); ?>" placeholder="اختياري" min="0"></div>
<div class="dzp-f" style="flex:1;min-width:140px"><label>💹 سعر التكلفة</label><input type="number" name="cost_price" value="<?php echo esc_attr($pid?get_post_meta($pid,'_dzqcod_cost_price',true):'');?>" placeholder="لحساب الأرباح" min="0" style="color:#059669"></div>
</div></div>
<div id="dzp-cpc-notice" style="<?php echo esc_html($cpc_on?'':'display:none'); ?>;background:#fff7ed;border:2px solid #fed7aa;border-radius:10px;padding:14px">
<div style="display:flex;align-items:center;gap:8px;margin-bottom:6px"><span style="font-size:20px">🏭</span><strong style="color:#c2410c">المنتج المخصص مفعّل</strong></div>
<p style="font-size:13px;color:#9a3412;margin:0">السعر = السعر الأساسي + الأبعاد × سعر الوحدة + الخيارات المدفوعة</p>
</div>
<!-- Tiers -->
<div style="margin-top:14px;border-top:1px solid #f1f5f9;padding-top:14px">
<h4 style="font-size:14px;margin:0 0 8px">🏷️ شرائح سعرية <small style="color:#94a3b8;font-weight:400">(اختياري)</small></h4>
<div id="dzp-tiers">
<?php foreach($tiers as $t): ?>
<div class="dzp-row" style="display:flex;gap:8px;margin-bottom:6px;align-items:center">
<input type="number" name="tier_min[]" value="<?php echo(int)$t['min_qty'];?>" placeholder="من" min="1" style="width:70px"><input type="number" name="tier_price[]" value="<?php echo(float)$t['price'];?>" placeholder="السعر" style="width:100px"><input type="text" name="tier_label[]" value="<?php echo esc_attr($t['label']??'');?>" placeholder="عنوان" style="flex:1"><button type="button" class="dzp-x" onclick="this.closest('.dzp-row').remove()">✕</button>
</div><?php endforeach; ?>
</div>
<button type="button" class="dza-btn ghost" style="font-size:12px;padding:6px 14px" onclick="addPriceTier()">➕ شريحة</button>
</div></div>
<script>function addPriceTier(){var h='<div class="dzp-row" style="display:flex;gap:8px;margin-bottom:6px;align-items:center"><input type="number" name="tier_min[]" placeholder="من" min="1" style="width:70px"><input type="number" name="tier_price[]" placeholder="السعر" style="width:100px"><input type="text" name="tier_label[]" placeholder="عنوان" style="flex:1"><button type="button" class="dzp-x" onclick="this.parentElement.remove()">✕</button></div>';document.getElementById("dzp-tiers").insertAdjacentHTML("beforeend",h);}</script>

<!-- VARIANTS -->
<div class="dza-card"><h3 style="font-size:16px">🎨 المتغيرات</h3>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
<div class="dzp-f"><label>الألوان <small style="color:#94a3b8">(فاصلة)</small></label><input type="text" name="colors" value="<?php echo esc_attr($dz_colors);?>" placeholder="أسود, أبيض, أزرق"></div>
<div class="dzp-f"><label>المقاسات <small style="color:#94a3b8">(فاصلة)</small></label><input type="text" name="sizes" value="<?php echo esc_attr($dz_sizes);?>" placeholder="S, M, L, XL"></div>
</div></div>

<!-- CUSTOM PRODUCT -->
<div class="dza-card" id="dzp-cpc-card" style="border-right:4px solid <?php echo esc_html($cpc_on?'#f97316':'#e2e8f0'); ?>">
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:14px">
<h3 style="font-size:16px;margin:0;border:none">🏭 منتج مخصص (ورشات)</h3>
<label class="dzp-sw"><input type="checkbox" name="custom_enabled" value="yes" <?php checked($cpc_on);?> id="dzp-cpc-toggle"><span class="dzp-sl"></span></label>
</div>
<p style="font-size:12px;color:#94a3b8;margin:0 0 14px">السعر يُحسب تلقائياً حسب الأبعاد والخيارات</p>
<div id="dzp-cpc-fields" style="<?php echo esc_html($cpc_on?'':'display:none'); ?>">
<!-- Mode -->
<div style="background:#fff7ed;border-radius:10px;padding:14px;margin-bottom:14px">
<h4 style="margin:0 0 10px;font-size:14px">💰 وضع التسعير</h4>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:8px;margin-bottom:12px">
<?php foreach(['fixed'=>'ثابت + خيارات','area'=>'مساحة (ط×ع)','linear'=>'طول فقط','volume'=>'حجم (ط×ع×ا)','weight'=>'وزن (كغ)'] as $mk=>$ml): ?>
<label class="dzp-mo <?php echo esc_html($cpc_mode===$mk?'on':''); ?>"><input type="radio" name="pricing_mode" value="<?php echo esc_html($mk);?>" <?php checked($cpc_mode,$mk);?> style="display:none"><?php echo esc_html($ml);?></label>
<?php endforeach; ?>
</div>
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px">
<div class="dzp-f"><label style="font-size:11px">سعر أساسي (دج)</label><input type="number" name="custom_base" value="<?php echo esc_attr($cpc_base);?>" placeholder="0" style="font-weight:700"></div>
<div class="dzp-f"><label style="font-size:11px">سعر الوحدة (دج)</label><input type="number" name="ppu" value="<?php echo esc_attr($cpc_ppu);?>" placeholder="5000" style="font-weight:700"></div>
<div class="dzp-f"><label style="font-size:11px">وحدة القياس</label><input type="text" name="unit_label" value="<?php echo esc_attr($cpc_unit);?>" placeholder="م²"></div>
</div></div>
<!-- Dims -->
<div style="background:#f0f4ff;border-radius:10px;padding:14px;margin-bottom:14px">
<h4 style="margin:0 0 8px;font-size:14px">📐 حقول الأبعاد</h4>
<div id="dzp-dims">
<?php foreach($dims as $d): ?>
<div class="dzp-row" style="display:flex;gap:6px;margin-bottom:6px;align-items:center;flex-wrap:wrap">
<input type="text" name="dim_name[]" value="<?php echo esc_attr($d['name']);?>" placeholder="الطول" style="flex:2;min-width:80px">
<input type="text" name="dim_unit[]" value="<?php echo esc_attr($d['unit']??'سم');?>" placeholder="سم" style="width:50px">
<input type="number" name="dim_min[]" value="<?php echo esc_attr($d['min']??'');?>" placeholder="أدنى" step="0.1" style="width:60px">
<input type="number" name="dim_max[]" value="<?php echo esc_attr($d['max']??'');?>" placeholder="أقصى" step="0.1" style="width:60px">
<button type="button" class="dzp-x" onclick="this.closest('.dzp-row').remove()">✕</button>
</div><?php endforeach; ?>
</div>
<button type="button" class="dza-btn ghost" style="font-size:12px;padding:6px 14px" id="dzp-add-dim">➕ بُعد</button>
</div>
<!-- Opts -->
<div style="background:#f0fdf4;border-radius:10px;padding:14px;margin-bottom:14px">
<h4 style="margin:0 0 8px;font-size:14px">✨ خيارات مدفوعة</h4>
<div id="dzp-opts">
<?php foreach($opts as $o): ?>
<div class="dzp-row" style="display:flex;gap:6px;margin-bottom:6px;align-items:center;flex-wrap:wrap">
<input type="text" name="opt_name[]" value="<?php echo esc_attr($o['name']);?>" placeholder="زجاج مزدوج" style="flex:2;min-width:80px">
<select name="opt_type[]" style="width:80px"><option value="checkbox" <?php selected($o['type']??'','checkbox');?>>صح/خطأ</option><option value="select" <?php selected($o['type']??'','select');?>>قائمة</option><option value="number" <?php selected($o['type']??'','number');?>>رقم</option></select>
<input type="number" name="opt_price[]" value="<?php echo esc_attr($o['price']??'');?>" placeholder="السعر" style="width:80px">
<input type="text" name="opt_values[]" value="<?php echo esc_attr($o['values']??'');?>" placeholder="قيمة1:1000,قيمة2:2000" style="flex:2;min-width:100px">
<button type="button" class="dzp-x" onclick="this.closest('.dzp-row').remove()">✕</button>
</div><?php endforeach; ?>
</div>
<button type="button" class="dza-btn ghost" style="font-size:12px;padding:6px 14px" id="dzp-add-opt">➕ خيار</button>
</div>
<!-- Upload + Note -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
<label style="display:flex;align-items:center;gap:8px;cursor:pointer;padding:10px;background:#f8fafc;border-radius:8px;border:1px solid #e2e8f0">
<input type="checkbox" name="upload_enabled" value="yes" <?php checked($upload_on);?>> <span style="font-size:13px;font-weight:600">📁 رفع ملفات</span></label>
<label style="display:flex;align-items:center;gap:8px;cursor:pointer;padding:10px;background:#f8fafc;border-radius:8px;border:1px solid #e2e8f0">
<input type="checkbox" name="custom_note" value="yes" <?php checked($note_on);?>> <span style="font-size:13px;font-weight:600">📝 ملاحظات</span></label>
</div>
</div></div>
</div>
<!-- RIGHT SIDEBAR -->
<div>
<div class="dza-card"><h3 style="font-size:14px">📷 صورة المنتج</h3>
<div id="dzp-img-box" style="width:100%;aspect-ratio:1;background:#f8fafc;border:2px dashed #e2e8f0;border-radius:12px;display:flex;align-items:center;justify-content:center;cursor:pointer;overflow:hidden" onclick="dzpImg()">
<?php if($thumb_url): ?><img src="<?php echo esc_url($thumb_url);?>" style="width:100%;height:100%;object-fit:cover"><?php else: ?><div style="text-align:center;color:#94a3b8"><div style="font-size:36px">📷</div><div style="font-size:12px">انقر لاختيار</div></div><?php endif; ?>
</div><input type="hidden" name="image_id" id="dzp-img-id" value="<?php echo esc_html($thumb_id);?>"></div>

<div class="dza-card"><h3 style="font-size:14px">💳 طرق الدفع المتاحة</h3>
<p style="font-size:11px;color:#94a3b8;margin:0 0 8px">اختر طرق الدفع المسموحة لهذا المنتج</p>
<?php
$pm_saved = $pid ? get_post_meta($pid, '_dzqcod_payment_methods', true) : '';
$pm_arr = $pm_saved ? explode(',', $pm_saved) : ['cod'];
$pm_options = [
    'cod'=>'💵 الدفع عند التوصيل',
    'chargily'=>'💳 Chargily Pay',
    'baridimob'=>'📱 BaridiMob',
    'bank'=>'🏦 تحويل بنكي',
    'paypal'=>'🅿️ PayPal',
    'cash'=>'💰 كاش',
];
foreach($pm_options as $pmk=>$pml): ?>
<label style="display:flex;align-items:center;gap:8px;padding:6px 0;cursor:pointer;font-size:13px">
<input type="checkbox" name="payment_methods[]" value="<?php echo esc_html($pmk); ?>" <?php checked(in_array($pmk, $pm_arr, true)); ?>>
<span><?php echo esc_html($pml); ?></span>
</label>
<?php endforeach; ?>
</div>

<div class="dza-card"><h3 style="font-size:14px">📤 النشر</h3>
<div class="dzp-f"><label>الحالة</label><select name="status" id="dzp-status" style="font-weight:700"><option value="publish" <?php selected($status,'publish');?>>✅ منشور</option><option value="draft" <?php selected($status,'draft');?>>📝 مسودة</option><option value="future">📅 مجدول</option></select></div>
<div id="dzp-schedule" style="display:none;margin-bottom:8px">
<div class="dzp-f"><label style="font-size:11px">تاريخ النشر</label><input type="datetime-local" name="schedule_date" style="font-size:12px"></div>
</div>
<button type="submit" class="dza-btn primary" style="width:100%;padding:14px;font-size:15px;margin-top:8px" id="dzp-save"><?php echo esc_html($action==='new'?'➕ إنشاء المنتج':'💾 حفظ التعديلات'); ?></button>
<?php if($pid): ?><div style="text-align:center;margin-top:6px"><a href="<?php echo esc_url(admin_url('post.php?post='.$pid.'&action=edit')); ?>" target="_blank" style="font-size:11px;color:#6366f1">تعديل في WooCommerce ↗</a></div><?php endif; ?>
</div>

<!-- URLs & Links -->
<?php if($pid):
$purl = get_permalink($pid);
$short = '[dzqcod_order product_id="'.$pid.'"]';
$utm_base = $purl.'?utm_source=facebook&utm_medium=cpc&utm_campaign=sale&utm_content=ad1';
?>
<div class="dza-card" style="background:#f0f4ff">
<h3 style="font-size:14px;border:none;margin:0 0 6px">🔗 الروابط</h3>
<div style="margin-bottom:8px"><label style="font-size:10px;color:#94a3b8;font-weight:700">📋 الشورتكود</label>
<div style="background:#fff;padding:8px;border-radius:6px;direction:ltr;font-family:monospace;font-size:11px;cursor:pointer;border:1px solid #c7d2fe;word-break:break-all" onclick="navigator.clipboard.writeText(this.textContent);this.style.background='#dcfce7';setTimeout(()=>this.style.background='#fff',800)"><?php echo esc_html($short); ?></div></div>
<div style="margin-bottom:8px"><label style="font-size:10px;color:#94a3b8;font-weight:700">🌐 رابط المنتج</label>
<div style="background:#fff;padding:8px;border-radius:6px;direction:ltr;font-family:monospace;font-size:10px;cursor:pointer;border:1px solid #c7d2fe;word-break:break-all" onclick="navigator.clipboard.writeText(this.textContent);this.style.background='#dcfce7';setTimeout(()=>this.style.background='#fff',800)"><?php echo esc_html($purl); ?></div></div>
<div style="margin-bottom:8px"><label style="font-size:10px;color:#94a3b8;font-weight:700">📊 رابط UTM (Facebook Ads)</label>
<div style="background:#fff;padding:8px;border-radius:6px;direction:ltr;font-family:monospace;font-size:9px;cursor:pointer;border:1px solid #c7d2fe;word-break:break-all" onclick="navigator.clipboard.writeText(this.textContent);this.style.background='#dcfce7';setTimeout(()=>this.style.background='#fff',800)"><?php echo esc_html($utm_base); ?></div></div>
<details style="font-size:11px"><summary style="cursor:pointer;font-weight:700;color:#6366f1">🔧 مولّد UTM مخصص</summary>
<div style="margin-top:6px;display:grid;grid-template-columns:1fr 1fr;gap:4px">
<input type="text" id="utm-src" placeholder="source" style="padding:4px;border:1px solid #e2e8f0;border-radius:4px;font-size:10px;direction:ltr">
<input type="text" id="utm-med" placeholder="medium" style="padding:4px;border:1px solid #e2e8f0;border-radius:4px;font-size:10px;direction:ltr">
<input type="text" id="utm-camp" placeholder="campaign" style="padding:4px;border:1px solid #e2e8f0;border-radius:4px;font-size:10px;direction:ltr">
<input type="text" id="utm-cont" placeholder="content" style="padding:4px;border:1px solid #e2e8f0;border-radius:4px;font-size:10px;direction:ltr">
</div>
<div id="utm-result" style="background:#fff;padding:6px;border-radius:4px;margin-top:4px;font-size:9px;word-break:break-all;direction:ltr;font-family:monospace;cursor:pointer;border:1px solid #e2e8f0" onclick="navigator.clipboard.writeText(this.textContent)"><?php echo esc_html($purl); ?></div>
</details>
</div>
<?php endif; ?>

<!-- Gallery / Media -->
<div class="dza-card">
<h3 style="font-size:14px">🖼️ الوسائط</h3>
<?php $gallery_ids=$edit_p?$edit_p->get_gallery_image_ids():[]; $video_url=$pid?get_post_meta($pid,'_dzqcod_video_url',true):''; ?>
<div class="dzp-f"><label style="font-size:11px">🎬 رابط فيديو (YouTube/Vimeo)</label>
<input type="text" name="video_url" value="<?php echo esc_attr($video_url); ?>" placeholder="https://youtube.com/watch?v=..." style="direction:ltr;font-size:11px"></div>
<div class="dzp-f"><label style="font-size:11px">🖼️ معرض الصور <small>(<?php echo (int)count($gallery_ids); ?> صورة)</small></label>
<div style="display:flex;gap:4px;flex-wrap:wrap;margin-bottom:4px" id="dzp-gallery">
<?php foreach($gallery_ids as $gid): $gurl=wp_get_attachment_image_url($gid,'thumbnail'); if($gurl): ?>
<div style="position:relative"><img src="<?php echo esc_url($gurl); ?>" style="width:48px;height:48px;object-fit:cover;border-radius:6px"><input type="hidden" name="gallery_ids[]" value="<?php echo esc_html($gid); ?>"></div>
<?php endif; endforeach; ?>
</div>
<button type="button" class="dza-btn ghost" style="font-size:11px;padding:4px 10px" onclick="dzpGallery()">➕ صور</button>
</div>
<a href="https://www.canva.com/design" target="_blank" class="dza-btn ghost" style="width:100%;text-align:center;font-size:11px;margin-top:6px">🎨 تصميم بـ Canva ↗</a>
</div>

<!-- Digital Product Features -->
<div class="dza-card">
<h3 style="font-size:14px">⚙️ إضافي</h3>
<div class="dzp-f"><label>شارة</label><input type="text" name="badge" value="<?php echo esc_attr($dz_badge);?>" placeholder="🔥 الأكثر مبيعاً"></div>
<div class="dzp-f"><label>واتساب خاص</label><input type="text" name="whatsapp" value="<?php echo esc_attr($dz_wa);?>" placeholder="213555123456" style="direction:ltr"></div>
<label style="display:flex;align-items:center;gap:8px;cursor:pointer;margin-top:8px"><input type="checkbox" name="digital" value="yes" <?php checked($dz_digital,'yes');?> id="dzp-dig-toggle"> <span style="font-size:12px;font-weight:600">💾 منتج رقمي (قابل للتنزيل)</span></label>
<div id="dzp-dig-fields" style="<?php echo esc_html($dz_digital==='yes'?'':'display:none'); ?>;margin-top:8px;background:#ede9fe;padding:14px;border-radius:10px;border:1px solid #c4b5fd">
<?php $dl_url=$pid?get_post_meta($pid,'_dzqcod_download_url',true):'';
$dl_limit=$pid?(get_post_meta($pid,'_dzqcod_download_limit',true)?:'3'):'3';
$dl_expiry=$pid?(get_post_meta($pid,'_dzqcod_download_expiry',true)?:'48'):'48';
$dl_files=$pid?get_post_meta($pid,'_dzqcod_download_files',true):''; ?>
<div style="font-size:12px;color:#5b21b6;font-weight:700;margin-bottom:8px">📁 ملفات التحميل</div>
<div style="display:flex;gap:6px;margin-bottom:8px">
<div class="dzp-f" style="flex:2;margin:0"><label style="font-size:10px;color:#5b21b6">🔗 رابط التحميل (URL)</label><input type="text" name="download_url" value="<?php echo esc_attr($dl_url); ?>" placeholder="https://drive.google.com/..." style="direction:ltr;font-size:11px"></div>
<div style="flex:1;display:flex;align-items:flex-end">
<button type="button" class="dza-btn ghost" style="font-size:11px;width:100%;padding:8px" onclick="var i=document.createElement('input');i.type='file';i.onchange=function(){var f=this.files[0];if(f){var fd=new FormData();fd.append('action','dzqcod_upload_file');fd.append('nonce',dza.nonce);fd.append('file',f);jQuery.ajax({url:dza.ajax,type:'POST',data:fd,processData:false,contentType:false,success:function(r){if(r.success)document.querySelector('[name=download_url]').value=r.data.url}})}};i.click()">📤 رفع ملف</button>
</div></div>
<div class="dzp-f" style="margin-bottom:6px"><label style="font-size:10px;color:#5b21b6">📎 ملفات إضافية (رابط لكل سطر)</label><textarea name="download_files" rows="2" style="font-size:11px;direction:ltr" placeholder="https://file1.zip&#10;https://file2.pdf"><?php echo esc_html(esc_textarea($dl_files)); ?></textarea></div>
<div style="display:flex;gap:6px">
<div class="dzp-f" style="flex:1;margin:0"><label style="font-size:10px;color:#5b21b6">📥 عدد مرات التحميل</label><input type="number" name="download_limit" value="<?php echo esc_attr($dl_limit); ?>" min="1" style="font-size:11px"></div>
<div class="dzp-f" style="flex:1;margin:0"><label style="font-size:10px;color:#5b21b6">⏰ صلاحية الرابط (ساعة)</label><input type="number" name="download_expiry" value="<?php echo esc_attr($dl_expiry); ?>" min="1" style="font-size:11px"></div>
</div>
<div style="margin-top:6px;font-size:10px;color:#7c3aed;background:#f5f3ff;padding:6px;border-radius:6px">💡 عند تفعيل المنتج الرقمي، سيُعيّن تلقائياً كـ <strong>Virtual + Downloadable</strong> في ووكومرس. يُرسل رابط التحميل للعميل بعد تأكيد الدفع.</div>
</div>
<label style="display:flex;align-items:center;gap:8px;cursor:pointer;margin-top:6px"><input type="checkbox" name="disabled" value="yes" <?php checked($dz_off,'yes');?>> <span style="font-size:12px;font-weight:600;color:#ef4444">❌ تعطيل DZQCOD</span></label>
</div>
</div>
</div>
</form>

<style>
.dzp-f{margin-bottom:10px}
.dzp-f label{display:block;font-weight:700;font-size:13px;margin-bottom:4px;color:#374151}
.dzp-f input,.dzp-f select,.dzp-f textarea{width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:8px;font-family:inherit;font-size:14px;transition:.2s;outline:none}
.dzp-f input:focus,.dzp-f select:focus,.dzp-f textarea:focus{border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,.1)}
.dzp-row input,.dzp-row select{padding:8px;border:1px solid #e2e8f0;border-radius:6px;font-family:inherit;font-size:13px}
.dzp-x{color:#ef4444;background:none;border:none;cursor:pointer;font-size:16px;padding:4px}
.dzp-sw{position:relative;display:inline-block;width:48px;height:26px}
.dzp-sw input{opacity:0;width:0;height:0}
.dzp-sl{position:absolute;cursor:pointer;inset:0;background:#cbd5e1;border-radius:26px;transition:.3s}
.dzp-sl:before{content:'';position:absolute;height:20px;width:20px;right:3px;bottom:3px;background:#fff;border-radius:50%;transition:.3s}
.dzp-sw input:checked+.dzp-sl{background:#f97316}
.dzp-sw input:checked+.dzp-sl:before{transform:translateX(-22px)}
.dzp-mo{display:block;padding:10px;border:2px solid #fed7aa;border-radius:8px;cursor:pointer;text-align:center;font-size:12px;font-weight:700;transition:.2s;background:#fff}
.dzp-mo:hover,.dzp-mo.on{border-color:#f97316;background:#fff7ed}
@media(max-width:768px){#dzp-form>div{grid-template-columns:1fr!important}}
</style>

<script>
jQuery(function($){
    // Schedule toggle
    $('#dzp-status').on('change',function(){$('#dzp-schedule').toggle(this.value==='future')});
    // Digital toggle
    $('#dzp-dig-toggle').on('change',function(){$('#dzp-dig-fields').slideToggle(200)});
    // UTM generator
    <?php if($pid): ?>
    var purl='<?php echo esc_html(esc_js($purl??'')); ?>';
    ['utm-src','utm-med','utm-camp','utm-cont'].forEach(function(id){
        var el=document.getElementById(id);if(el)el.addEventListener('input',function(){
            var s=$('#utm-src').val(),m=$('#utm-med').val(),c=$('#utm-camp').val(),co=$('#utm-cont').val();
            var u=purl+'?';if(s)u+='utm_source='+s+'&';if(m)u+='utm_medium='+m+'&';if(c)u+='utm_campaign='+c+'&';if(co)u+='utm_content='+co;
            $('#utm-result').text(u.replace(/&$/,''));
        });
    });
    <?php endif; ?>
    // Gallery picker
    window.dzpGallery=function(){
        var frame=wp.media({title:'اختر صور المعرض',multiple:true,library:{type:'image'}});
        frame.on('select',function(){
            var sel=frame.state().get('selection');
            sel.forEach(function(a){
                a=a.toJSON();
                $('#dzp-gallery').append('<div style="position:relative"><img src="'+a.url+'" style="width:48px;height:48px;object-fit:cover;border-radius:6px"><input type="hidden" name="gallery_ids[]" value="'+a.id+'"></div>');
            });
        });
        frame.open();
    };
    // Toggle custom product
    $('#dzp-cpc-toggle').on('change',function(){
        var on=this.checked;
        $('#dzp-cpc-fields').slideToggle(200);
        $('#dzp-cpc-card').css('border-right-color',on?'#f97316':'#e2e8f0');
        $('#dzp-normal-pricing').toggle(!on);$('#dzp-cpc-notice').toggle(on);
    });
    $(document).on('change','[name=pricing_mode]',function(){$('.dzp-mo').removeClass('on');$(this).closest('.dzp-mo').addClass('on')});
    // Add dim/opt
    $('#dzp-add-dim').on('click',function(){
        $('#dzp-dims').append('<div class="dzp-row" style="display:flex;gap:6px;margin-bottom:6px;align-items:center;flex-wrap:wrap"><input type="text" name="dim_name[]" placeholder="الطول" style="flex:2;min-width:80px"><input type="text" name="dim_unit[]" value="سم" placeholder="سم" style="width:50px"><input type="number" name="dim_min[]" placeholder="أدنى" step="0.1" style="width:60px"><input type="number" name="dim_max[]" placeholder="أقصى" step="0.1" style="width:60px"><button type="button" class="dzp-x" onclick="this.closest(\'.dzp-row\').remove()">✕</button></div>');
    });
    $('#dzp-add-opt').on('click',function(){
        $('#dzp-opts').append('<div class="dzp-row" style="display:flex;gap:6px;margin-bottom:6px;align-items:center;flex-wrap:wrap"><input type="text" name="opt_name[]" placeholder="زجاج مزدوج" style="flex:2;min-width:80px"><select name="opt_type[]" style="width:80px"><option value="checkbox">صح/خطأ</option><option value="select">قائمة</option><option value="number">رقم</option></select><input type="number" name="opt_price[]" placeholder="السعر" style="width:80px"><input type="text" name="opt_values[]" placeholder="قيمة1:1000,قيمة2:2000" style="flex:2;min-width:100px"><button type="button" class="dzp-x" onclick="this.closest(\'.dzp-row\').remove()">✕</button></div>');
    });
    // Image picker
    window.dzpImg=function(){
        var frame=wp.media({title:'اختر صورة المنتج',multiple:false,library:{type:'image'}});
        frame.on('select',function(){var a=frame.state().get('selection').first().toJSON();$('#dzp-img-id').val(a.id);$('#dzp-img-box').html('<img src="'+a.url+'" style="width:100%;height:100%;object-fit:cover">')});
        frame.open();
    };
    // Delete product
    $(document).on('click','.dzp-delete',function(){
        var id=$(this).data('id'),$b=$(this);
        if(!confirm('⚠️ حذف المنتج #'+id+'؟ سيتم نقله إلى المهملات.'))return;
        $b.prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_delete_product',nonce:dza.nonce,product_id:id},function(r){
            if(r.success)$b.closest('tr').fadeOut(300);
            else{alert('❌ '+(r.data?r.data.message:'خطأ'));$b.prop('disabled',false).text('🗑️')}
        });
    });

    // Save
    $('#dzp-form').on('submit',function(e){
        e.preventDefault();var $b=$('#dzp-save').prop('disabled',true).text('⏳ جاري الحفظ...');
        $.post(dza.ajax,{action:'dzqcod_save_full_product',nonce:dza.nonce,product_id:$(this).data('pid')||0,data:$(this).serialize()},function(r){
            if(r.success){
                $b.text('✅ تم الحفظ!').css('background','#22c55e');
                if(!$('#dzp-form').data('pid')&&r.data.product_id) setTimeout(function(){window.location.href='<?php echo esc_url(admin_url('admin.php?page=dzqcod-products&action=edit&edit=')); ?>'+r.data.product_id},800);
                setTimeout(function(){$b.html('💾 حفظ التعديلات').css('background','').prop('disabled',false)},2000);
            } else {$b.text('❌ خطأ!').css('background','#ef4444');setTimeout(function(){$b.html('💾 حفظ').css('background','').prop('disabled',false)},2000)}
        });
    });
});
</script>
<?php endif; ?>
</div></div></div></div></div>
