<?php defined('ABSPATH') || exit; global $wpdb;$wpdb->suppress_errors(true); $p=$wpdb->prefix.DZQCOD_DB;
// Alter table if needed (add columns safely)
$wpdb->query("ALTER TABLE {$p}offers ADD COLUMN IF NOT EXISTS coupon_code VARCHAR(50) DEFAULT NULL AFTER name");
$wpdb->query("ALTER TABLE {$p}offers ADD COLUMN IF NOT EXISTS description TEXT AFTER coupon_code");
$wpdb->query("ALTER TABLE {$p}offers ADD COLUMN IF NOT EXISTS min_amount DECIMAL(10,2) DEFAULT 0 AFTER value");
$wpdb->query("ALTER TABLE {$p}offers ADD COLUMN IF NOT EXISTS product_ids TEXT AFTER min_amount");
$offers=$wpdb->get_results("SELECT * FROM {$p}offers ORDER BY priority ASC, id DESC");
$edit_id=absint($_GET['edit_offer']??0); $edit_offer=null;
if($edit_id){foreach($offers as $o)if((int)$o->id===$edit_id){$edit_offer=$o;break;}}
$currency=\DZQCOD\Core::opt('currency_symbol','دج');
?>
<div class="wrap dza-wrap" dir="rtl">
<div class="dza-header"><h1>🎁 العروض والكوبونات</h1>
<div style="display:flex;gap:8px"><span class="dza-ver"><?php echo count($offers); ?> عرض</span>
<button class="dza-btn ghost" style="font-size:11px" onclick="document.getElementById('offer-form').style.display='block'">➕ إضافة عرض</button></div></div>
<?php include __DIR__.'/nav.php'; ?>
<div class="dza-content">

<!-- Hot Offers Shortcode Info -->
<div class="dza-card" style="background:#eff6ff;border-right:4px solid #3b82f6;padding:12px 16px;margin-bottom:16px">
<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px">
<div><strong style="color:#1e40af">🔥 صفحة العروض الساخنة</strong>
<div style="font-size:12px;color:#64748b;margin-top:2px">ضع هذا الشورتكود في أي صفحة لعرض كل العروض النشطة مع كوبونات مخفية</div></div>
<div style="display:flex;gap:6px;align-items:center">
<code style="background:#dbeafe;padding:6px 14px;border-radius:8px;font-size:13px;font-weight:700;color:#1e40af;cursor:pointer" onclick="navigator.clipboard.writeText('[dzqcod_hot_offers]');this.textContent='✅ تم النسخ!';setTimeout(()=>this.textContent='[dzqcod_hot_offers]',1500)">[dzqcod_hot_offers]</code>
</div></div></div>

<!-- Add/Edit Offer Form -->
<div class="dza-card" id="offer-form" style="<?php echo esc_html($edit_offer?'':'display:none'); ?>;border-right:4px solid #667eea">
<h3 style="border:none;margin:0 0 12px"><?php echo esc_html($edit_offer?'✏️ تعديل العرض: '.$edit_offer->name:'➕ إضافة عرض جديد'); ?></h3>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
<div><label style="font-size:12px;font-weight:700">اسم العرض *</label>
<input type="text" id="of-name" placeholder="عرض الصيف 🔥" value="<?php echo esc_attr($edit_offer->name??''); ?>" style="width:100%;padding:10px;border:2px solid #e2e8f0;border-radius:8px;font-size:14px"></div>
<div><label style="font-size:12px;font-weight:700">كود الكوبون <small style="color:#94a3b8">(يتولد تلقائياً)</small></label>
<input type="text" id="of-code" placeholder="DZ123ABCD" value="<?php echo esc_attr($edit_offer->coupon_code??''); ?>" style="width:100%;padding:10px;border:2px solid #e2e8f0;border-radius:8px;font-size:14px;direction:ltr;font-weight:700;letter-spacing:2px"></div>
<div><label style="font-size:12px;font-weight:700">النوع</label>
<select id="of-type" style="width:100%;padding:10px;border:2px solid #e2e8f0;border-radius:8px;font-size:13px">
<option value="percentage" <?php selected($edit_offer->type??'','percentage'); ?>>📊 نسبة %</option>
<option value="fixed" <?php selected($edit_offer->type??'','fixed'); ?>>💰 مبلغ ثابت</option>
<option value="free_shipping" <?php selected($edit_offer->type??'','free_shipping'); ?>>🚚 شحن مجاني</option>
<option value="buy_x_get_y" <?php selected($edit_offer->type??'','buy_x_get_y'); ?>>🎁 اشترِ X واحصل Y</option></select></div>
<div><label style="font-size:12px;font-weight:700">القيمة</label>
<input type="number" id="of-value" placeholder="10" value="<?php echo esc_attr($edit_offer->value??''); ?>" min="0" style="width:100%;padding:10px;border:2px solid #e2e8f0;border-radius:8px;font-size:14px"></div>
<div><label style="font-size:12px;font-weight:700">الحد الأدنى للطلب (<?php echo esc_html($currency); ?>)</label>
<input type="number" id="of-min" placeholder="0 = بدون حد" value="<?php echo esc_attr($edit_offer->min_amount??0); ?>" min="0" style="width:100%;padding:10px;border:2px solid #e2e8f0;border-radius:8px"></div>
<div><label style="font-size:12px;font-weight:700">الحد الأقصى للاستخدام</label>
<input type="number" id="of-max" placeholder="0 = غير محدود" value="<?php echo esc_attr($edit_offer->max_uses??0); ?>" min="0" style="width:100%;padding:10px;border:2px solid #e2e8f0;border-radius:8px"></div>
<div><label style="font-size:12px;font-weight:700">تاريخ البداية</label>
<input type="datetime-local" id="of-start" value="<?php echo esc_attr($edit_offer->starts_at??''); ?>" style="width:100%;padding:10px;border:2px solid #e2e8f0;border-radius:8px"></div>
<div><label style="font-size:12px;font-weight:700">تاريخ الانتهاء</label>
<input type="datetime-local" id="of-end" value="<?php echo esc_attr($edit_offer->ends_at??''); ?>" style="width:100%;padding:10px;border:2px solid #e2e8f0;border-radius:8px"></div>
</div>
<div style="margin-top:10px"><label style="font-size:12px;font-weight:700">وصف العرض</label>
<textarea id="of-desc" rows="2" placeholder="وصف قصير يظهر للعميل في صفحة العروض..." style="width:100%;padding:10px;border:2px solid #e2e8f0;border-radius:8px;font-size:13px;resize:vertical"><?php echo esc_textarea($edit_offer->description??''); ?></textarea></div>
<div style="margin-top:10px"><label style="font-size:12px;font-weight:700">منتجات محددة (IDs مفصولة بفاصلة — فارغ = كل المنتجات)</label>
<input type="text" id="of-products" placeholder="12,45,78" value="<?php echo esc_attr($edit_offer->product_ids??''); ?>" style="width:100%;padding:10px;border:2px solid #e2e8f0;border-radius:8px;direction:ltr"></div>
<div style="display:flex;gap:8px;margin-top:14px">
<input type="hidden" id="of-id" value="<?php echo esc_attr($edit_id); ?>">
<button class="dza-btn primary" id="save-offer" style="padding:10px 24px;font-size:14px">💾 <?php echo esc_html($edit_offer?'تحديث العرض':'حفظ وإنشاء كوبون'); ?></button>
<?php if($edit_offer): ?><a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod-offers')); ?>" class="dza-btn ghost" style="padding:10px 24px">إلغاء</a><?php endif; ?>
<button class="dza-btn ghost" onclick="document.getElementById('offer-form').style.display='none'" style="padding:10px 16px">✕</button>
</div></div>

<!-- Offers List -->
<h2 style="font-size:16px;margin:20px 0 10px">🎁 العروض الحالية</h2>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:12px">
<?php if(empty($offers)): ?>
<div class="dza-card" style="text-align:center;padding:40px;background:#f8fafc;grid-column:1/-1"><div style="font-size:48px">🎁</div><h3 style="border:none;color:#94a3b8">لا توجد عروض بعد</h3><p style="color:#94a3b8;font-size:13px">أنشئ أول عرض بالزر أعلاه</p></div>
<?php else: foreach($offers as $of):
$types=['percentage'=>'📊 نسبة','fixed'=>'💰 مبلغ ثابت','free_shipping'=>'🚚 شحن مجاني','buy_x_get_y'=>'🎁 اشترِ واحصل'];
$expired=$of->ends_at&&strtotime($of->ends_at)<time();
$type_label=$types[$of->type]??$of->type;
$value_label=$of->type==='percentage'?$of->value.'%':($of->type==='free_shipping'?'مجاني':number_format($of->value,0).' '.$currency);
?>
<div class="dza-card" style="position:relative;border-right:4px solid <?php echo esc_html($of->is_active&&!$expired?'#22c55e':'#94a3b8'); ?>">
<?php if($expired): ?><span style="position:absolute;top:8px;left:8px;background:#ef4444;color:#fff;padding:2px 8px;border-radius:4px;font-size:10px;font-weight:700">⏰ منتهي</span><?php endif; ?>
<div style="display:flex;justify-content:space-between;align-items:start">
<div><h3 style="border:none;margin:0;font-size:15px"><?php echo esc_html($of->name); ?></h3>
<div style="font-size:12px;color:#64748b;margin-top:2px"><?php echo esc_html($type_label); ?> — <strong style="color:#667eea"><?php echo esc_html($value_label); ?></strong></div></div>
<span style="font-size:24px;font-weight:900;color:<?php echo esc_html($of->is_active?'#22c55e':'#94a3b8'); ?>"><?php echo esc_html($of->is_active?'●':'○'); ?></span>
</div>
<?php if(!empty($of->coupon_code)): ?>
<div style="margin-top:10px;padding:8px 12px;background:#f0f9ff;border:2px dashed #3b82f6;border-radius:8px;display:flex;align-items:center;justify-content:space-between">
<div style="font-size:11px;color:#64748b">كود الكوبون</div>
<code style="font-size:16px;font-weight:900;letter-spacing:3px;color:#1e40af;cursor:pointer" onclick="navigator.clipboard.writeText('<?php echo esc_html($of->coupon_code); ?>');this.textContent='✅ تم!';setTimeout(()=>this.textContent='<?php echo esc_html($of->coupon_code); ?>',1200)"><?php echo esc_html($of->coupon_code); ?></code>
</div>
<?php endif; ?>
<?php if(!empty($of->description)): ?><p style="font-size:12px;color:#64748b;margin:6px 0 0"><?php echo esc_html($of->description); ?></p><?php endif; ?>
<div style="display:flex;gap:4px;margin-top:8px;font-size:11px;color:#94a3b8;flex-wrap:wrap">
<span>استخدام: <?php echo esc_html($of->used_count); ?><?php echo esc_html($of->max_uses?' / '.$of->max_uses:''); ?></span>
<?php if($of->min_amount>0): ?><span>• حد أدنى: <?php echo number_format($of->min_amount,0); ?> <?php echo esc_html($currency); ?></span><?php endif; ?>
<?php if($of->starts_at): ?><span>• من: <?php echo esc_html(date('Y/m/d',strtotime($of->starts_at))); ?></span><?php endif; ?>
<?php if($of->ends_at): ?><span>• إلى: <?php echo esc_html(date('Y/m/d',strtotime($of->ends_at))); ?></span><?php endif; ?>
</div>
<div style="display:flex;gap:6px;margin-top:10px">
<a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod-offers&edit_offer='.$of->id)); ?>" class="dza-btn sm">✏️ تعديل</a>
<button class="dza-btn sm toggle-offer" data-id="<?php echo esc_html($of->id); ?>" data-active="<?php echo esc_html($of->is_active); ?>"><?php echo esc_html($of->is_active?'⏸️ إيقاف':'▶️ تفعيل'); ?></button>
<button class="dza-btn sm danger del-offer" data-id="<?php echo esc_html($of->id); ?>">🗑️</button>
</div></div>
<?php endforeach; endif; ?>
</div></div></div>
</div></div>
<script>jQuery(function($){
$('#save-offer').on('click',function(){
    var b=$(this);b.prop('disabled',true).text('⏳');
    $.post(dza.ajax,{action:'dzqcod_save_offer',nonce:dza.nonce,
        offer_id:$('#of-id').val(),name:$('#of-name').val(),coupon_code:$('#of-code').val(),
        type:$('#of-type').val(),value:$('#of-value').val(),description:$('#of-desc').val(),
        min_amount:$('#of-min').val(),max_uses:$('#of-max').val(),product_ids:$('#of-products').val(),
        starts_at:$('#of-start').val(),ends_at:$('#of-end').val(),is_active:1
    },function(r){b.prop('disabled',false);if(r.success){alert('✅ '+r.data.message+'\nكود: '+r.data.coupon_code);location.reload()}else{b.text('❌');alert(r.data?.message||'خطأ')}});
});
$('.del-offer').on('click',function(){if(!confirm('حذف العرض والكوبون؟'))return;$.post(dza.ajax,{action:'dzqcod_delete_offer',nonce:dza.nonce,offer_id:$(this).data('id')},function(){location.reload()})});
$('.toggle-offer').on('click',function(){var $b=$(this),id=$b.data('id'),act=$b.data('active');$.post(dza.ajax,{action:'dzqcod_save_offer',nonce:dza.nonce,offer_id:id,is_active:act?0:1,name:'_keep_'},function(){location.reload()})});
});</script>
