<?php defined('ABSPATH') || exit;
$addons=\DZQCOD\Modules::get_addons(); $installed=\DZQCOD\Modules::installed_addons();
$plan=\DZQCOD\Core::opt('license_plan','free');
// Fetch remote addons
$remote_addons=get_transient('dzqcod_remote_addons');
if($remote_addons===false){
    $resp=wp_remote_get(\DZQCOD\Modules::API_BASE.'/addons',['timeout'=>8,'sslverify'=>apply_filters('dzqcod_ssl_verify',true),'headers'=>['X-DZQCOD-Version'=>DZQCOD_VER]]);
    if(!is_wp_error($resp)){$body=json_decode(wp_remote_retrieve_body($resp),true);$remote_addons=$body['addons']??[];}
    if(!$remote_addons)$remote_addons=[];
    set_transient('dzqcod_remote_addons',$remote_addons,6*HOUR_IN_SECONDS);
}
foreach($remote_addons as $ra){$found=false;foreach($addons as &$a){if($a['slug']===$ra['slug']){$a=array_merge($a,$ra);$found=true;break;}}if(!$found)$addons[]=$ra;}unset($a);
// Custom uploaded addons from addons/ directory
$custom_dir=DZQCOD_PATH.'addons/';
if(is_dir($custom_dir)){
    $local_slugs=array_column($addons,'slug');
    foreach(glob($custom_dir.'*.php') as $cf){
        $slug=pathinfo($cf,PATHINFO_FILENAME);
        if($slug==='DEVELOPER'||in_array($slug,$local_slugs))continue;
        $hdr=[];$data=file_get_contents($cf,false,null,0,1024);
        if(preg_match('/(?:Addon|Plugin) Name:\s*(.+)/i',$data,$m))$hdr['name']=trim($m[1]);
        if(preg_match('/Description:\s*(.+)/i',$data,$m))$hdr['desc']=trim($m[1]);
        if(preg_match('/Category:\s*(.+)/i',$data,$m))$hdr['cat']=trim($m[1]);
        $addons[]=['slug'=>$slug,'name'=>$hdr['name']??$slug,'desc'=>$hdr['desc']??'إضافة مخصصة','icon'=>'🔌','type'=>'custom','cat'=>$hdr['cat']??'tools','custom'=>true];
    }
    foreach(glob($custom_dir.'*',GLOB_ONLYDIR) as $cd){
        $slug=basename($cd);
        if(in_array($slug,$local_slugs))continue;
        $main=$cd.'/'.$slug.'.php';if(!is_file($main))$main=$cd.'/init.php';
        $hdr=[];if(is_file($main)){$data=file_get_contents($main,false,null,0,1024);
            if(preg_match('/(?:Addon|Plugin) Name:\s*(.+)/i',$data,$m))$hdr['name']=trim($m[1]);
            if(preg_match('/Description:\s*(.+)/i',$data,$m))$hdr['desc']=trim($m[1]);
        }
        $addons[]=['slug'=>$slug,'name'=>$hdr['name']??$slug,'desc'=>$hdr['desc']??'إضافة مخصصة','icon'=>'🔌','type'=>'custom','cat'=>'tools','custom'=>true];
    }
}
$cats=['all'=>'📦 الكل','shipping'=>'🚚 الشحن','payment'=>'💳 الدفع','marketing'=>'📈 التسويق','sales'=>'🛍️ المبيعات','automation'=>'🤖 الأتمتة','creative'=>'🎨 الإبداع','optimization'=>'🔬 التحسين','analytics'=>'📊 التقارير','security'=>'🔐 الأمان','channels'=>'📱 القنوات','products'=>'📦 المنتجات','integrations'=>'🔗 التكامل','tools'=>'🛠️ أدوات','enterprise'=>'🏢 مؤسسات','international'=>'🌍 دولي'];
$filter=sanitize_text_field($_GET['cat']??'');
// Stats
$total_count=count($addons); $active_count=count(array_filter($installed)); $free_count=0;$pro_count=0;$ent_count=0;$custom_count=0;
foreach($addons as $a){$t=$a['type']??'free';if($t==='free')$free_count++;elseif($t==='pro')$pro_count++;elseif($t==='enterprise')$ent_count++;elseif($t==='custom')$custom_count++;}
?>
<div class="wrap dza-wrap" dir="rtl">
<div class="dza-header"><h1>🛒 متجر الإضافات</h1>
<div style="display:flex;gap:8px;align-items:center">
<span class="dza-ver"><?php echo esc_html($total_count); ?> إضافة</span>
<label class="dza-btn primary" style="font-size:12px;cursor:pointer">📤 رفع إضافة<input type="file" id="upload-addon-file" accept=".zip,.php" style="display:none"></label>
<button class="dza-btn ghost" style="font-size:11px" onclick="jQuery.post(dza.ajax,{action:'dzqcod_refresh_addons',nonce:dza.nonce},function(){location.reload()})">🔄 تحديث</button>
</div></div>
<?php include __DIR__.'/_layout_start.php'; ?>
<div class="dza-content">

<!-- Stats Bar -->
<div style="display:grid;grid-template-columns:repeat(6,1fr);gap:8px;margin-bottom:16px;text-align:center">
<div style="background:#f0fdf4;border-radius:8px;padding:10px"><div style="font-size:20px;font-weight:900;color:#22c55e"><?php echo esc_html($active_count); ?></div><div style="font-size:10px;color:#64748b">مفعّلة</div></div>
<div style="background:#f8fafc;border-radius:8px;padding:10px"><div style="font-size:20px;font-weight:900;color:#475569"><?php echo esc_html($total_count); ?></div><div style="font-size:10px;color:#64748b">إجمالي</div></div>
<div style="background:#f8fafc;border-radius:8px;padding:10px"><div style="font-size:20px;font-weight:900;color:#6b7280"><?php echo esc_html($free_count); ?></div><div style="font-size:10px;color:#64748b">مجانية</div></div>
<div style="background:#eff6ff;border-radius:8px;padding:10px"><div style="font-size:20px;font-weight:900;color:#667eea"><?php echo esc_html($pro_count); ?></div><div style="font-size:10px;color:#64748b">PRO</div></div>
<div style="background:#fffbeb;border-radius:8px;padding:10px"><div style="font-size:20px;font-weight:900;color:#f59e0b"><?php echo esc_html($ent_count); ?></div><div style="font-size:10px;color:#64748b">Enterprise</div></div>
<div style="background:#fdf2f8;border-radius:8px;padding:10px"><div style="font-size:20px;font-weight:900;color:#ec4899"><?php echo esc_html($custom_count); ?></div><div style="font-size:10px;color:#64748b">مخصصة</div></div>
</div>

<!-- Search & Filters -->
<div style="display:flex;gap:8px;margin-bottom:12px;flex-wrap:wrap;align-items:center">
<input type="text" id="addon-search" placeholder="🔍 بحث عن إضافة..." style="flex:1;min-width:200px;padding:8px 14px;border:2px solid #e2e8f0;border-radius:8px;font-size:13px" oninput="filterAddons()">
<select id="addon-status-filter" style="padding:8px 12px;border:2px solid #e2e8f0;border-radius:8px;font-size:12px" onchange="filterAddons()">
<option value="">كل الحالات</option><option value="active">✅ مفعّلة</option><option value="inactive">⬜ غير مثبتة</option><option value="custom">🔌 مخصصة</option>
</select>
</div>
<div class="dza-filters" style="margin-bottom:14px;flex-wrap:wrap">
<a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod-addons')); ?>" class="dza-btn <?php echo esc_html(!$filter?'primary':''); ?>" style="font-size:11px;padding:5px 10px">📦 الكل</a>
<?php foreach($cats as $ck=>$cl): if($ck==='all')continue; ?><a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod-addons&cat='.$ck)); ?>" class="dza-btn <?php echo esc_html($filter===$ck?'primary':''); ?>" style="font-size:11px;padding:5px 10px"><?php echo esc_html($cl); ?></a><?php endforeach; ?>
</div>

<!-- Addons Grid -->
<div id="addons-grid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:12px">
<?php foreach($addons as $a): if($filter&&($a['cat']??'')!==$filter) continue;
$slug=$a['slug']??'';
$inst=!empty($installed[$slug]);
$locked=(($a['type']??'free')==='pro'&&!in_array($plan,['pro','enterprise']))||(($a['type']??'free')==='enterprise'&&$plan!=='enterprise');
$is_remote=!empty($a['remote']);
$is_custom=!empty($a['custom'])||($a['type']??'free')==='custom';
$type_color=match($a['type']??'free'){'pro'=>'#667eea','enterprise'=>'#f59e0b','custom'=>'#ec4899',default=>'#6b7280'};
?>
<div class="addon-card dza-card" data-slug="<?php echo esc_attr($slug); ?>" data-name="<?php echo esc_attr($a['name']??''); ?>" data-desc="<?php echo esc_attr($a['desc']??''); ?>" data-status="<?php echo esc_attr($inst?'active':($is_custom?'custom':'inactive')); ?>" style="position:relative;transition:.2s;<?php echo esc_html($inst?'border-right:3px solid #22c55e':''); ?>" onmouseenter="this.style.transform='translateY(-2px)';this.style.boxShadow='0 8px 24px rgba(0,0,0,.08)'" onmouseleave="this.style.transform='none';this.style.boxShadow='none'">
<?php if(($a['type']??'free')!=='free'): ?><span class="dza-badge" style="position:absolute;top:8px;left:8px;background:<?php echo esc_html($type_color); ?>;font-size:9px;padding:2px 7px"><?php echo esc_html(strtoupper($a['type']??'free')); ?></span><?php endif; ?>
<?php if($is_remote): ?><span class="dza-badge" style="position:absolute;top:8px;right:8px;background:#22c55e;font-size:8px;padding:2px 6px">☁️</span><?php endif; ?>
<?php if($is_custom): ?><span class="dza-badge" style="position:absolute;top:8px;right:8px;background:#ec4899;font-size:8px;padding:2px 6px">🔌 مخصصة</span><?php endif; ?>
<div style="font-size:32px;margin-bottom:6px"><?php echo esc_html($a['icon']??'🧩'); ?></div>
<h3 style="border:none;margin:0;font-size:14px"><?php echo esc_html($a['name']??''); ?></h3>
<p style="font-size:11px;color:#94a3b8;margin:2px 0 8px;min-height:28px"><?php echo esc_html($a['desc']??''); ?></p>
<?php if(!empty($a['version'])): ?><span style="font-size:9px;color:#cbd5e1">v<?php echo esc_html($a['version']); ?></span><?php endif; ?>
<span style="font-size:9px;color:#cbd5e1;margin-right:6px"><?php echo esc_html($cats[$a['cat']??'']??''); ?></span>
<div style="display:flex;gap:5px;margin-top:8px;flex-wrap:wrap">
<?php if($locked): ?>
<a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod-license')); ?>" class="dza-btn sm" style="font-size:11px">🔒 ترقية</a>
<?php elseif($inst): ?>
<button class="dza-btn sm success addon-toggle" data-slug="<?php echo esc_attr($slug); ?>" style="font-size:11px">✅ مفعّل</button>
<button class="dza-btn sm danger addon-uninstall" data-slug="<?php echo esc_attr($slug); ?>" style="font-size:11px;padding:4px 8px" title="تعطيل">⏸️</button>
<?php else: ?>
<button class="dza-btn sm primary addon-install" data-slug="<?php echo esc_attr($slug); ?>" data-remote="<?php echo esc_html(($is_remote||!empty($a['has_file']))?'1':'0'); ?>" style="font-size:11px"><?php echo esc_html(($is_remote&&!empty($a['has_file']))?'☁️ تحميل':'📥 تثبيت'); ?></button>
<?php endif; ?>
<?php if($is_custom&&$inst): ?>
<button class="dza-btn sm ghost addon-publish" data-slug="<?php echo esc_attr($slug); ?>" style="font-size:10px" title="نشر للسيرفر">☁️ نشر</button>
<?php endif; ?>
</div></div>
<?php endforeach; ?>
</div>

<!-- Upload Info -->
<div class="dza-card" style="margin-top:16px;background:#f8fafc;border-right:4px solid #667eea">
<h3 style="border:none;margin:0 0 8px;font-size:14px">🔌 تطوير إضافات مخصصة</h3>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;font-size:12px;color:#475569">
<div>
<strong>صيغة الملف:</strong>
<div style="background:#0f172a;color:#94a3b8;border-radius:8px;padding:10px;margin-top:6px;direction:ltr;font-family:monospace;font-size:10px;line-height:1.6">
<span style="color:#22c55e">// Addon Name: My Addon</span><br>
<span style="color:#22c55e">// Description: وصف الإضافة</span><br>
<span style="color:#22c55e">// Category: marketing</span><br><br>
<span style="color:#818cf8">defined</span>('ABSPATH') || exit;<br>
<span style="color:#818cf8">if</span> (!\DZQCOD\Modules::is_on('my-addon')) <span style="color:#818cf8">return</span>;<br>
</div></div>
<div>
<strong>طريقة الإضافة:</strong>
<ul style="margin:6px 0;padding-right:16px;line-height:2;list-style:disc">
<li>ارفع ملف <code>.php</code> واحد أو <code>.zip</code> متعدد الملفات</li>
<li>يُقرأ الاسم والوصف من Header الملف تلقائياً</li>
<li>يُفعّل مباشرة بعد الرفع ويظهر في السوق</li>
<li>يمكن نشره للسيرفر ليظهر لكل المستخدمين ☁️</li>
</ul>
<a href="<?php echo esc_url(DZQCOD_URL.'addons/DEVELOPER.php'); ?>" target="_blank" class="dza-btn sm ghost" style="margin-top:4px">📚 دليل المطوّر</a>
</div></div></div>

</div></div>
<script>jQuery(function($){
// Install
$(document).on('click','.addon-install',function(){var $b=$(this),s=$b.data('slug');$b.prop('disabled',true).text('⏳');
$.post(dza.ajax,{action:'dzqcod_install_addon',nonce:dza.nonce,slug:s,remote:$b.data('remote')},function(r){
    if(r.success){$b.removeClass('primary').addClass('success').text('✅ مفعّل').addClass('addon-toggle').removeClass('addon-install');$b.closest('.addon-card').css('border-right','3px solid #22c55e')}
    else alert(r.data?r.data.message:'خطأ');$b.prop('disabled',false)})});
// Toggle
$(document).on('click','.addon-toggle,.addon-uninstall',function(){var $b=$(this),s=$b.data('slug');$b.prop('disabled',true);
$.post(dza.ajax,{action:'dzqcod_toggle_addon',nonce:dza.nonce,slug:s},function(r){location.reload()})});
// Upload
$('#upload-addon-file').on('change',function(){
    var f=this.files[0];if(!f)return;
    if(!confirm('رفع وتثبيت الإضافة: '+f.name+'?'))return;
    var fd=new FormData();fd.append('action','dzqcod_upload_addon');fd.append('nonce',dza.nonce);fd.append('addon_file',f);
    $.ajax({url:dza.ajax,type:'POST',data:fd,contentType:false,processData:false,
        beforeSend:function(){$('.dza-header h1').append(' <span style="color:#667eea;font-size:13px">⏳ جاري الرفع...</span>')},
        success:function(r){if(r.success){alert('✅ '+r.data.message);location.reload()}else alert('❌ '+(r.data?r.data.message:'خطأ'))},
        error:function(){alert('❌ خطأ في الرفع')}
    });this.value='';
});
// Publish to cloud
$(document).on('click','.addon-publish',function(){
    var s=$(this).data('slug');
    if(!confirm('نشر الإضافة "'+s+'" إلى سيرفر NIBRA Cloud؟\nستصبح متاحة لكل المستخدمين.'))return;
    $(this).prop('disabled',true).text('⏳');
    $.post(dza.ajax,{action:'dzqcod_publish_addon',nonce:dza.nonce,slug:s},function(r){
        if(r.success)alert('✅ '+r.data.message);else alert('❌ '+(r.data?r.data.message:'خطأ'));location.reload();
    });
});
// Search
window.filterAddons=function(){
    var q=$('#addon-search').val().toLowerCase(),st=$('#addon-status-filter').val();
    $('.addon-card').each(function(){
        var $c=$(this),name=$c.data('name').toLowerCase(),desc=$c.data('desc').toLowerCase(),status=$c.data('status');
        var match=(q===''||(name+' '+desc).indexOf(q)>-1)&&(st===''||status===st);
        $c.toggle(match);
    });
};
});</script>
</div></div>
<?php include __DIR__."/_layout_end.php"; ?>
