<?php
namespace DZQCOD\Addons;
if (!defined('ABSPATH')) exit;
if (!\DZQCOD\Modules::is_on('email-marketing')) return;

class EmailMarketing {
    const PROVIDERS=['mailchimp'=>['n'=>'Mailchimp','url'=>'https://us1.api.mailchimp.com/3.0'],'sendinblue'=>['n'=>'Brevo (Sendinblue)','url'=>'https://api.brevo.com/v3'],'mailercloud'=>['n'=>'Mailercloud','url'=>'https://cloudapi.mailercloud.com/v1']];

    public static function init():void{
        foreach(['dzqcod_em_save_settings','dzqcod_em_sync','dzqcod_em_test','dzqcod_em_lists'] as $a)
            add_action("wp_ajax_{$a}",[self::class,$a]);
        add_action('dzqcod_admin_page_email-marketing',[self::class,'admin_page']);
        add_action('dzqcod_order_created',[self::class,'on_order'],40,2);
    }

    public static function on_order(int $oid,$order):void{
        $provider=\DZQCOD\Core::opt('em_provider','');$key=\DZQCOD\Core::opt('em_api_key','');
        if(!$provider||!$key)return;$email=$order->get_billing_email();if(!$email)return;
        $name=$order->get_billing_first_name().' '.$order->get_billing_last_name();$phone=$order->get_billing_phone();
        self::subscribe($provider,$key,$email,$name,$phone);
    }

    private static function subscribe(string $prov,string $key,string $email,string $name,string $phone):bool{
        $list=\DZQCOD\Core::opt('em_list_id','');
        if($prov==='mailchimp'){
            $dc=substr($key,strpos($key,'-')+1);
            $resp=wp_remote_post("https://{$dc}.api.mailchimp.com/3.0/lists/{$list}/members",['headers'=>['Authorization'=>'Basic '.base64_encode('any:'.$key),'Content-Type'=>'application/json'],'body'=>wp_json_encode(['email_address'=>$email,'status'=>'subscribed','merge_fields'=>['FNAME'=>$name,'PHONE'=>$phone]]),'timeout'=>10,'sslverify'=>false]);
            return !is_wp_error($resp)&&in_array(wp_remote_retrieve_response_code($resp),[200,201]);
        }
        if($prov==='sendinblue'){
            $resp=wp_remote_post('https://api.brevo.com/v3/contacts',['headers'=>['api-key'=>$key,'Content-Type'=>'application/json'],'body'=>wp_json_encode(['email'=>$email,'attributes'=>['FIRSTNAME'=>$name,'SMS'=>$phone],'listIds'=>[(int)$list],'updateEnabled'=>true]),'timeout'=>10,'sslverify'=>false]);
            return !is_wp_error($resp)&&wp_remote_retrieve_response_code($resp)<300;
        }
        return false;
    }

    public static function dzqcod_em_save_settings():void{
        check_ajax_referer('dzqcod_admin','nonce');
        foreach(['em_provider','em_api_key','em_list_id'] as $k)\DZQCOD\Core::set_opt($k,sanitize_text_field($_POST[$k]??''));
        wp_send_json_success();
    }
    public static function dzqcod_em_sync():void{
        check_ajax_referer('dzqcod_admin','nonce');$prov=\DZQCOD\Core::opt('em_provider','');$key=\DZQCOD\Core::opt('em_api_key','');
        if(!$prov||!$key)wp_send_json_error(['message'=>'إعدادات ناقصة']);
        $orders=wc_get_orders(['limit'=>200,'status'=>['wc-processing','wc-completed','wc-delivered'],'orderby'=>'date','order'=>'DESC']);
        $synced=0;foreach($orders as $o){$e=$o->get_billing_email();if($e&&self::subscribe($prov,$key,$e,$o->get_billing_first_name(),$o->get_billing_phone()))$synced++;}
        wp_send_json_success(['synced'=>$synced]);
    }
    public static function dzqcod_em_test():void{check_ajax_referer('dzqcod_admin','nonce');$ok=self::subscribe(\DZQCOD\Core::opt('em_provider',''),\DZQCOD\Core::opt('em_api_key',''),sanitize_email($_POST['email']??''),'Test','');wp_send_json_success(['ok'=>$ok]);}
    public static function dzqcod_em_lists():void{check_ajax_referer('dzqcod_admin','nonce');wp_send_json_success();}

    public static function admin_page():void{$prov=\DZQCOD\Core::opt('em_provider','');?>
<div class="dza-wrap" style="direction:rtl;font-family:Tajawal,sans-serif">
<h2 style="font-size:22px;margin-bottom:16px">📧 Email Marketing</h2>
<div style="max-width:600px;background:#fff;border-radius:12px;padding:24px;box-shadow:0 2px 8px rgba(0,0,0,.06)">
<div style="margin-bottom:12px"><label style="font-weight:700;font-size:12px">المزود</label>
<select id="em-prov" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px">
<option value="">— اختر —</option><?php foreach(self::PROVIDERS as $k=>$v):?><option value="<?php echo $k;?>" <?php selected($prov,$k);?>><?php echo $v['n'];?></option><?php endforeach;?>
</select></div>
<div style="margin-bottom:12px"><label style="font-weight:700;font-size:12px">API Key</label>
<input id="em-key" type="password" value="<?php echo esc_attr(\DZQCOD\Core::opt('em_api_key',''));?>" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px;direction:ltr"></div>
<div style="margin-bottom:12px"><label style="font-weight:700;font-size:12px">List / Audience ID</label>
<input id="em-list" value="<?php echo esc_attr(\DZQCOD\Core::opt('em_list_id',''));?>" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px;direction:ltr"></div>
<div style="display:flex;gap:8px;flex-wrap:wrap">
<button onclick="jQuery.post(dza.ajax,{action:'dzqcod_em_save_settings',nonce:dza.nonce,em_provider:jQuery('#em-prov').val(),em_api_key:jQuery('#em-key').val(),em_list_id:jQuery('#em-list').val()},function(r){alert(r.success?'✅ تم الحفظ':'خطأ')})" style="padding:10px 24px;background:#6366F1;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700">💾 حفظ</button>
<button onclick="jQuery.post(dza.ajax,{action:'dzqcod_em_sync',nonce:dza.nonce},function(r){alert(r.success?'✅ تم مزامنة '+r.data.synced+' جهة اتصال':'❌ '+(r.data&&r.data.message?r.data.message:'خطأ'))})" style="padding:10px 24px;background:#10B981;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700">🔄 مزامنة الزبائن</button>
</div>
<p style="font-size:11px;color:#94a3b8;margin-top:12px">✅ كل طلب جديد يُضاف تلقائياً للقائمة البريدية</p>
</div></div><?php
    }
}
EmailMarketing::init();
