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

class CRMIntegration {
    const PROVIDERS=['hubspot'=>['n'=>'HubSpot','url'=>'https://api.hubapi.com'],'zoho'=>['n'=>'Zoho CRM','url'=>'https://www.zohoapis.com']];

    public static function init():void{
        foreach(['dzqcod_crm_save','dzqcod_crm_sync','dzqcod_crm_test'] as $a)add_action("wp_ajax_{$a}",[self::class,$a]);
        add_action('dzqcod_admin_page_crm',[self::class,'admin_page']);
        add_action('dzqcod_order_created',[self::class,'on_order'],45,2);
    }
    public static function on_order(int $oid,$order):void{
        $prov=\DZQCOD\Core::opt('crm_provider','');$key=\DZQCOD\Core::opt('crm_api_key','');if(!$prov||!$key)return;
        $data=['email'=>$order->get_billing_email(),'firstname'=>$order->get_billing_first_name(),'lastname'=>$order->get_billing_last_name(),'phone'=>$order->get_billing_phone(),'city'=>$order->get_shipping_city(),'amount'=>(float)$order->get_total()];
        if($prov==='hubspot'){
            wp_remote_post('https://api.hubapi.com/crm/v3/objects/contacts',['headers'=>['Authorization'=>'Bearer '.$key,'Content-Type'=>'application/json'],'body'=>wp_json_encode(['properties'=>$data]),'timeout'=>10,'sslverify'=>apply_filters('dzqcod_ssl_verify',true)]);
            wp_remote_post('https://api.hubapi.com/crm/v3/objects/deals',['headers'=>['Authorization'=>'Bearer '.$key,'Content-Type'=>'application/json'],'body'=>wp_json_encode(['properties'=>['dealname'=>'Order #'.$oid,'amount'=>$data['amount'],'pipeline'=>'default']]),'timeout'=>10,'sslverify'=>apply_filters('dzqcod_ssl_verify',true)]);
        }
    }
    public static function dzqcod_crm_save():void{check_ajax_referer('dzqcod_admin','nonce');foreach(['crm_provider','crm_api_key'] as $k)\DZQCOD\Core::set_opt($k,sanitize_text_field($_POST[$k]??''));wp_send_json_success();}
    public static function dzqcod_crm_sync():void{
        check_ajax_referer('dzqcod_admin','nonce');$orders=wc_get_orders(['limit'=>100,'status'=>['wc-processing','wc-completed','wc-delivered'],'orderby'=>'date','order'=>'DESC']);
        $synced=0;foreach($orders as $o){self::on_order($o->get_id(),$o);$synced++;}wp_send_json_success(['synced'=>$synced]);
    }
    public static function dzqcod_crm_test():void{check_ajax_referer('dzqcod_admin','nonce');wp_send_json_success(['message'=>'OK']);}
    public static function admin_page():void{$prov=\DZQCOD\Core::opt('crm_provider','');?>
<div class="dza-wrap" style="direction:rtl;font-family:Tajawal,sans-serif">
<h2 style="font-size:22px;margin-bottom:16px">🔗 CRM Integration</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="crm-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 / Access Token</label>
<input id="crm-key" type="password" value="<?php echo esc_attr(\DZQCOD\Core::opt('crm_api_key',''));?>" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px;direction:ltr"></div>
<div style="display:flex;gap:8px">
<button onclick="jQuery.post(dza.ajax,{action:'dzqcod_crm_save',nonce:dza.nonce,crm_provider:jQuery('#crm-prov').val(),crm_api_key:jQuery('#crm-key').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_crm_sync',nonce:dza.nonce},function(r){alert(r.success?'✅ مزامنة '+r.data.synced+' طلب':'خطأ')})" 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
    }
}
CRMIntegration::init();
