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

class InstagramShop {
    public static function init():void{
        foreach(['dzqcod_ig_save','dzqcod_ig_feed','dzqcod_ig_sync'] as $a)add_action("wp_ajax_{$a}",[self::class,$a]);
        add_action('dzqcod_admin_page_instagram-shop',[self::class,'admin_page']);
        add_shortcode('dzqcod_instagram',[self::class,'shortcode']);
    }
    public static function dzqcod_ig_save():void{check_ajax_referer('dzqcod_admin','nonce');foreach(['ig_token','ig_user_id','ig_auto_post'] as $k)\DZQCOD\Core::set_opt($k,sanitize_text_field($_POST[$k]??''));wp_send_json_success();}
    public static function dzqcod_ig_feed():void{
        check_ajax_referer('dzqcod_admin','nonce');$token=\DZQCOD\Core::opt('ig_token','');
        if(!$token)wp_send_json_error(['message'=>'Access Token مطلوب']);
        $resp=wp_remote_get("https://graph.instagram.com/me/media?fields=id,caption,media_type,media_url,thumbnail_url,permalink,timestamp&limit=20&access_token={$token}",['timeout'=>10,'sslverify'=>false]);
        if(is_wp_error($resp))wp_send_json_error(['message'=>$resp->get_error_message()]);
        wp_send_json_success(json_decode(wp_remote_retrieve_body($resp),true));
    }
    public static function dzqcod_ig_sync():void{
        check_ajax_referer('dzqcod_admin','nonce');
        $products=wc_get_products(['status'=>'publish','limit'=>20,'orderby'=>'date','order'=>'DESC']);$items=[];
        foreach($products as $p){$img=wp_get_attachment_url($p->get_image_id());
            $items[]=['id'=>$p->get_id(),'name'=>$p->get_name(),'price'=>$p->get_price(),'img'=>$img,'link'=>get_permalink($p->get_id())];}
        wp_send_json_success(['products'=>$items,'count'=>count($items)]);
    }
    public static function shortcode($atts):string{
        $atts=shortcode_atts(['count'=>'6','cols'=>'3'],$atts);$token=\DZQCOD\Core::opt('ig_token','');
        if(!$token)return '<p style="text-align:center;color:#888">Instagram غير متصل</p>';
        $cached=get_transient('dzqcod_ig_feed');
        if(!$cached){$resp=wp_remote_get("https://graph.instagram.com/me/media?fields=id,media_url,permalink,media_type,thumbnail_url&limit={$atts['count']}&access_token={$token}",['timeout'=>10,'sslverify'=>false]);
            if(!is_wp_error($resp)){$cached=json_decode(wp_remote_retrieve_body($resp),true);set_transient('dzqcod_ig_feed',$cached,3600);}}
        if(empty($cached['data']))return '';
        $html='<div style="display:grid;grid-template-columns:repeat('.$atts['cols'].',1fr);gap:8px">';
        foreach(array_slice($cached['data'],0,(int)$atts['count']) as $m){$url=$m['media_type']==='VIDEO'?($m['thumbnail_url']??''):$m['media_url'];
            $html.='<a href="'.esc_url($m['permalink']).'" target="_blank" style="display:block;border-radius:8px;overflow:hidden"><img src="'.esc_url($url).'" style="width:100%;aspect-ratio:1;object-fit:cover" loading="lazy"></a>';}
        return $html.'</div>';
    }
    public static function admin_page():void{?>
<div class="dza-wrap" style="direction:rtl;font-family:Tajawal,sans-serif">
<h2 style="font-size:22px;margin-bottom:16px">📸 Instagram Shopping</h2>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
<div style="background:#fff;border-radius:12px;padding:24px;box-shadow:0 2px 8px rgba(0,0,0,.06)">
<h4 style="margin:0 0 12px">⚙️ الإعدادات</h4>
<div style="margin-bottom:12px"><label style="font-weight:700;font-size:12px">Access Token (Instagram Graph API)</label>
<input id="ig-token" type="password" value="<?php echo esc_attr(\DZQCOD\Core::opt('ig_token',''));?>" 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_ig_save',nonce:dza.nonce,ig_token:jQuery('#ig-token').val()},function(r){alert(r.success?'✅':'خطأ')})" style="padding:8px 16px;background:#6366F1;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700;font-size:12px">💾 حفظ</button>
<button onclick="igFeed()" style="padding:8px 16px;background:#E1306C;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700;font-size:12px">📸 جلب المنشورات</button>
</div>
<p style="font-size:11px;color:#94a3b8;margin-top:8px">شورت كود: <code>[dzqcod_instagram count="6" cols="3"]</code></p>
</div>
<div style="background:#fff;border-radius:12px;padding:24px;box-shadow:0 2px 8px rgba(0,0,0,.06)">
<h4 style="margin:0 0 12px">📸 آخر المنشورات</h4>
<div id="ig-feed" style="color:#aaa;text-align:center;padding:20px">اضغط جلب المنشورات</div>
</div></div></div>
<script>
function igFeed(){jQuery('#ig-feed').html('⏳');jQuery.post(dza.ajax,{action:'dzqcod_ig_feed',nonce:dza.nonce},function(r){
    if(!r.success){jQuery('#ig-feed').html('❌ '+(r.data&&r.data.message?r.data.message:'خطأ'));return}
    var posts=r.data.data||[],h='<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:6px">';
    posts.forEach(function(p){var url=p.media_type==='VIDEO'?(p.thumbnail_url||''):p.media_url;
        h+='<a href="'+p.permalink+'" target="_blank" style="display:block;border-radius:6px;overflow:hidden"><img src="'+url+'" style="width:100%;aspect-ratio:1;object-fit:cover"></a>'});
    jQuery('#ig-feed').html(h+'</div>')})}
</script><?php
    }
}
InstagramShop::init();
