<?php
/**
 * Addon: Workflows — أتمتة سير العمل
 * Type: enterprise
 */
namespace DZQCOD\Addons;
if (!defined('ABSPATH')) exit;
if (!\DZQCOD\Modules::is_on('workflows')) return;

class Workflows {
    const TRIGGERS=['order_created'=>'📦 طلب جديد','order_confirmed'=>'✅ تأكيد طلب','order_shipped'=>'🚚 شحن','order_delivered'=>'📬 تسليم','order_returned'=>'🔄 مرتجع','order_cancelled'=>'❌ إلغاء','payment_received'=>'💰 دفع','fraud_detected'=>'🛡️ احتيال','stock_low'=>'📉 مخزون منخفض','new_customer'=>'👤 زبون جديد','review_received'=>'⭐ تقييم'];
    const ACTIONS=['send_whatsapp'=>'💬 إرسال واتساب','send_sms'=>'📱 إرسال SMS','send_email'=>'📧 إرسال بريد','change_status'=>'🔄 تغيير حالة','assign_agent'=>'👤 تعيين وكيل','add_note'=>'📝 إضافة ملاحظة','create_shipment'=>'🚚 إنشاء شحنة','apply_tag'=>'🏷️ إضافة وسم','webhook'=>'🔗 Webhook','delay'=>'⏰ تأخير'];
    const CONDITIONS=['order_total_gt'=>'المبلغ أكبر من','order_total_lt'=>'المبلغ أقل من','wilaya_is'=>'الولاية =','product_is'=>'المنتج =','customer_orders_gt'=>'عدد طلبات الزبون >','payment_method'=>'وسيلة الدفع =','shipping_company'=>'شركة الشحن ='];

    public static function init():void{
        foreach(['dzqcod_wf_save','dzqcod_wf_delete','dzqcod_wf_toggle','dzqcod_wf_list'] as $a)add_action("wp_ajax_{$a}",[self::class,$a]);
        add_action('dzqcod_admin_page_workflows',[self::class,'admin_page']);
        add_action('admin_init',[self::class,'install'],5);
        // Hook all triggers
        add_action('dzqcod_order_created',[self::class,'on_event'],50,2);
        add_action('woocommerce_order_status_changed',[self::class,'on_status_change'],50,4);
    }

    public static function install():void{
        if(get_option('dzqcod_wf_v','0')==='1.0')return;
        global $wpdb;$cs=$wpdb->get_charset_collate();
        $wpdb->query("CREATE TABLE IF NOT EXISTS {$wpdb->prefix}dz_workflows (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,name VARCHAR(200),trigger_event VARCHAR(50),conditions_json TEXT,actions_json TEXT,is_active TINYINT(1) DEFAULT 1,priority INT DEFAULT 10,run_count INT DEFAULT 0,last_run DATETIME DEFAULT NULL,created_at DATETIME DEFAULT CURRENT_TIMESTAMP) $cs");
        update_option('dzqcod_wf_v','1.0');
    }

    public static function on_event(int $oid,$order):void{self::run_workflows('order_created',$oid,$order);}
    public static function on_status_change(int $oid,string $from,string $to,$order):void{
        $map=['confirmed'=>'order_confirmed','shipped'=>'order_shipped','delivered'=>'order_delivered','returned'=>'order_returned','cancelled'=>'order_cancelled'];
        if(isset($map[$to]))self::run_workflows($map[$to],$oid,$order);
    }

    private static function run_workflows(string $trigger,int $oid,$order):void{
        global $wpdb;$t=$wpdb->prefix.'dz_workflows';
        $flows=$wpdb->get_results($wpdb->prepare("SELECT * FROM {$t} WHERE trigger_event=%s AND is_active=1 ORDER BY priority",$trigger),ARRAY_A);
        foreach($flows as $f){
            $conds=json_decode($f['conditions_json']?:'[]',true)?:[];$pass=true;
            foreach($conds as $c){
                $v=$c['value']??'';
                if($c['type']==='order_total_gt'&&(float)$order->get_total()<=(float)$v)$pass=false;
                if($c['type']==='order_total_lt'&&(float)$order->get_total()>=(float)$v)$pass=false;
                if($c['type']==='wilaya_is'&&$order->get_shipping_state()!==$v)$pass=false;
            }
            if(!$pass)continue;
            $actions=json_decode($f['actions_json']?:'[]',true)?:[];
            foreach($actions as $a){
                if($a['type']==='change_status'&&!empty($a['value']))$order->update_status($a['value']);
                if($a['type']==='add_note'&&!empty($a['value']))$order->add_order_note('[Workflow] '.$a['value']);
            }
            $wpdb->update($t,['run_count'=>(int)$f['run_count']+1,'last_run'=>current_time('mysql')],['id'=>$f['id']]);
        }
    }

    public static function dzqcod_wf_save():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$t=$wpdb->prefix.'dz_workflows';$id=absint($_POST['wf_id']??0);
        $data=['name'=>sanitize_text_field($_POST['name']??''),'trigger_event'=>sanitize_text_field($_POST['trigger_event']??''),'conditions_json'=>wp_json_encode((array)json_decode(stripslashes($_POST['conditions']??'[]'),true)),'actions_json'=>wp_json_encode((array)json_decode(stripslashes($_POST['actions']??'[]'),true)),'priority'=>absint($_POST['priority']??10)];
        if($id)$wpdb->update($t,$data,['id'=>$id]);else{$data['is_active']=1;$wpdb->insert($t,$data);$id=$wpdb->insert_id;}
        wp_send_json_success(['id'=>$id]);
    }
    public static function dzqcod_wf_delete():void{check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$wpdb->delete($wpdb->prefix.'dz_workflows',['id'=>absint($_POST['wf_id']??0)]);wp_send_json_success();}
    public static function dzqcod_wf_toggle():void{check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$t=$wpdb->prefix.'dz_workflows';$id=absint($_POST['wf_id']??0);$cur=(int)$wpdb->get_var($wpdb->prepare("SELECT is_active FROM {$t} WHERE id=%d",$id));$wpdb->update($t,['is_active'=>$cur?0:1],['id'=>$id]);wp_send_json_success();}
    public static function dzqcod_wf_list():void{check_ajax_referer('dzqcod_admin','nonce');global $wpdb;wp_send_json_success($wpdb->get_results("SELECT * FROM {$wpdb->prefix}dz_workflows ORDER BY priority",ARRAY_A));}

    public static function admin_page():void{
        global $wpdb;$flows=$wpdb->get_results("SELECT * FROM {$wpdb->prefix}dz_workflows ORDER BY priority",ARRAY_A);
        ?>
<div class="dza-wrap" style="direction:rtl;font-family:Tajawal,sans-serif">
<h2 style="font-size:24px;margin-bottom:20px">⚡ Workflows — أتمتة سير العمل</h2>
<button onclick="wfForm(0)" style="padding:8px 20px;background:#6366F1;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700;margin-bottom:16px">➕ سير عمل جديد</button>
<div style="background:#fff;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.06);overflow-x:auto">
<table style="width:100%;border-collapse:collapse;font-size:12px"><thead><tr style="background:#f8f9fa;font-weight:700"><th style="padding:8px">#</th><th style="padding:8px;text-align:right">الاسم</th><th style="padding:8px;text-align:center">المحفز</th><th style="padding:8px;text-align:center">التنفيذات</th><th style="padding:8px;text-align:center">الحالة</th><th style="padding:8px;text-align:center">إجراءات</th></tr></thead><tbody>
<?php $triggers=self::TRIGGERS;foreach($flows as $f):?>
<tr style="border-bottom:1px solid #f0f0f0"><td style="padding:8px;color:#888">#<?php echo $f['id'];?></td><td style="padding:8px;font-weight:700"><?php echo esc_html($f['name']);?></td><td style="padding:8px;text-align:center;font-size:11px"><?php echo $triggers[$f['trigger_event']]??$f['trigger_event'];?></td><td style="padding:8px;text-align:center"><?php echo $f['run_count'];?></td><td style="padding:8px;text-align:center"><span style="padding:2px 8px;border-radius:4px;font-size:10px;font-weight:700;<?php echo $f['is_active']?'background:#d1fae5;color:#10B981':'background:#fee2e2;color:#ef4444';?>"><?php echo $f['is_active']?'نشط':'متوقف';?></span></td>
<td style="padding:8px;text-align:center"><button onclick="wfToggle(<?php echo $f['id'];?>)" style="padding:3px 6px;background:#f1f5f9;border:none;border-radius:4px;cursor:pointer;font-size:10px"><?php echo $f['is_active']?'⏸️':'▶️';?></button> <button onclick="if(confirm('حذف؟'))jQuery.post(dza.ajax,{action:'dzqcod_wf_delete',nonce:dza.nonce,wf_id:<?php echo $f['id'];?>},function(){location.reload()})" style="padding:3px 6px;background:none;border:none;color:#ef4444;cursor:pointer;font-size:10px">🗑️</button></td></tr>
<?php endforeach;if(empty($flows)):?><tr><td colspan="6" style="padding:30px;text-align:center;color:#aaa">لا توجد سير عمل</td></tr><?php endif;?>
</tbody></table></div></div>
<div id="wf-modal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);z-index:99999;overflow-y:auto"><div id="wf-body" style="max-width:600px;margin:40px auto;background:#fff;border-radius:16px;padding:32px;direction:rtl;position:relative"></div></div>
<script>
var wfTriggers=<?php echo wp_json_encode(self::TRIGGERS);?>,wfActions=<?php echo wp_json_encode(self::ACTIONS);?>;
function wfForm(id){var tO='';for(var k in wfTriggers)tO+='<option value="'+k+'">'+wfTriggers[k]+'</option>';var aO='';for(var k in wfActions)aO+='<option value="'+k+'">'+wfActions[k]+'</option>';
var h='<h3>➕ سير عمل جديد</h3><button onclick="jQuery(\'#wf-modal\').hide()" style="position:absolute;top:12px;left:12px;background:none;border:none;font-size:20px;cursor:pointer">✕</button>';
h+='<div style="margin-bottom:12px"><label style="font-weight:700;font-size:12px">الاسم</label><input id="wf-name" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div style="margin-bottom:12px"><label style="font-weight:700;font-size:12px">المحفز (Trigger)</label><select id="wf-trigger" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px">'+tO+'</select></div>';
h+='<div style="margin-bottom:12px"><label style="font-weight:700;font-size:12px">الإجراء (Action)</label><select id="wf-action" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px">'+aO+'</select></div>';
h+='<div style="margin-bottom:12px"><label style="font-weight:700;font-size:12px">القيمة</label><input id="wf-value" placeholder="مثلاً: حالة جديدة أو رسالة" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div style="text-align:center;margin-top:16px"><button onclick="wfSave()" style="padding:10px 40px;background:#6366F1;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700">💾 حفظ</button></div>';
jQuery('#wf-body').html(h);jQuery('#wf-modal').show()}
function wfSave(){jQuery.post(dza.ajax,{action:'dzqcod_wf_save',nonce:dza.nonce,name:jQuery('#wf-name').val(),trigger_event:jQuery('#wf-trigger').val(),actions:JSON.stringify([{type:jQuery('#wf-action').val(),value:jQuery('#wf-value').val()}]),conditions:'[]'},function(r){if(r.success)location.reload();else alert('خطأ')})}
function wfToggle(id){jQuery.post(dza.ajax,{action:'dzqcod_wf_toggle',nonce:dza.nonce,wf_id:id},function(){location.reload()})}
</script>
        <?php
    }
}
Workflows::init();
