<?php
/**
 * Addon: Multi-Store
 * Type: enterprise
 */
namespace DZQCOD\Addons;
if (!defined('ABSPATH')) exit;
if (!\DZQCOD\Modules::is_on('multi-store')) return;

class MultiStore {
    public static function init():void{
        foreach(['dzqcod_ms_save_store','dzqcod_ms_delete_store','dzqcod_ms_switch','dzqcod_ms_list'] as $a)
            add_action("wp_ajax_{$a}",[self::class,$a]);
        add_action('dzqcod_admin_page_multi-store',[self::class,'admin_page']);
        add_action('admin_init',[self::class,'install'],5);
    }

    public static function install():void{
        if(get_option('dzqcod_ms_v','0')==='1.0')return;
        global $wpdb;$cs=$wpdb->get_charset_collate();
        $wpdb->query("CREATE TABLE IF NOT EXISTS {$wpdb->prefix}dz_stores (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,name VARCHAR(200) NOT NULL,domain VARCHAR(200) DEFAULT '',phone VARCHAR(30) DEFAULT '',address TEXT,wilaya VARCHAR(10) DEFAULT '',logo_url VARCHAR(500) DEFAULT '',color VARCHAR(10) DEFAULT '#6366F1',is_active TINYINT(1) DEFAULT 1,settings_json LONGTEXT,created_at DATETIME DEFAULT CURRENT_TIMESTAMP) $cs");
        update_option('dzqcod_ms_v','1.0');
    }

    public static function current_store():int{return absint(get_option('dzqcod_current_store',0));}

    public static function dzqcod_ms_save_store():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$t=$wpdb->prefix.'dz_stores';$id=absint($_POST['store_id']??0);
        $data=['name'=>sanitize_text_field($_POST['name']??''),'domain'=>sanitize_text_field($_POST['domain']??''),'phone'=>sanitize_text_field($_POST['phone']??''),'address'=>sanitize_textarea_field($_POST['address']??''),'wilaya'=>sanitize_text_field($_POST['wilaya']??''),'color'=>sanitize_hex_color($_POST['color']??'#6366F1'),'is_active'=>(int)(!empty($_POST['is_active']))];
        if($id)$wpdb->update($t,$data,['id'=>$id]);else{$wpdb->insert($t,$data);$id=$wpdb->insert_id;}
        wp_send_json_success(['id'=>$id]);
    }
    public static function dzqcod_ms_delete_store():void{check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$wpdb->delete($wpdb->prefix.'dz_stores',['id'=>absint($_POST['store_id']??0)]);wp_send_json_success();}
    public static function dzqcod_ms_switch():void{check_ajax_referer('dzqcod_admin','nonce');update_option('dzqcod_current_store',absint($_POST['store_id']??0));wp_send_json_success();}
    public static function dzqcod_ms_list():void{check_ajax_referer('dzqcod_admin','nonce');global $wpdb;wp_send_json_success($wpdb->get_results("SELECT * FROM {$wpdb->prefix}dz_stores ORDER BY id",ARRAY_A));}

    public static function admin_page():void{
        global $wpdb;$stores=$wpdb->get_results("SELECT * FROM {$wpdb->prefix}dz_stores ORDER BY id",ARRAY_A);$cur_id=self::current_store();
        ?>
<div class="dza-wrap" style="direction:rtl;font-family:Tajawal,sans-serif">
<h2 style="font-size:24px;margin-bottom:20px">🏪 إدارة المتاجر المتعددة</h2>
<button onclick="msForm(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="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px">
<?php foreach($stores as $s):$active=$s['id']==$cur_id;?>
<div style="background:#fff;border-radius:12px;padding:20px;box-shadow:0 2px 8px rgba(0,0,0,.06);border-top:4px solid <?php echo esc_attr($s['color']?:'#6366F1');?>;<?php echo $active?'ring:2px solid #10B981;box-shadow:0 0 0 2px #10B981':'';?>">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
<h3 style="margin:0;font-size:16px;border:none"><?php echo esc_html($s['name']);?></h3>
<?php if($active):?><span style="background:#10B981;color:#fff;padding:2px 8px;border-radius:4px;font-size:10px;font-weight:700">✅ نشط</span><?php endif;?>
</div>
<?php if($s['domain']):?><div style="font-size:11px;color:#64748b">🌐 <?php echo esc_html($s['domain']);?></div><?php endif;?>
<?php if($s['phone']):?><div style="font-size:11px;color:#64748b">📞 <?php echo esc_html($s['phone']);?></div><?php endif;?>
<?php if($s['wilaya']):?><div style="font-size:11px;color:#64748b">📍 ولاية <?php echo esc_html($s['wilaya']);?></div><?php endif;?>
<div style="display:flex;gap:6px;margin-top:12px">
<?php if(!$active):?><button onclick="msSwitch(<?php echo $s['id'];?>)" style="padding:4px 12px;background:#10B981;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:11px">🔄 تفعيل</button><?php endif;?>
<button onclick="msForm(<?php echo $s['id'];?>)" style="padding:4px 12px;background:#f1f5f9;border:none;border-radius:6px;cursor:pointer;font-size:11px">✏️</button>
<button onclick="if(confirm('حذف؟'))jQuery.post(dza.ajax,{action:'dzqcod_ms_delete_store',nonce:dza.nonce,store_id:<?php echo $s['id'];?>},function(){location.reload()})" style="padding:4px 12px;background:#fef2f2;color:#ef4444;border:none;border-radius:6px;cursor:pointer;font-size:11px">🗑️</button>
</div></div>
<?php endforeach;if(empty($stores)):?><div style="background:#fff;border-radius:12px;padding:40px;text-align:center;color:#aaa">لا توجد متاجر — أنشئ أول متجر</div><?php endif;?>
</div></div>
<div id="ms-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="ms-body" style="max-width:500px;margin:60px auto;background:#fff;border-radius:16px;padding:32px;direction:rtl;position:relative"></div></div>
<script>
var msStores=<?php echo wp_json_encode($stores);?>;
function msForm(id){var s=id?msStores.find(function(x){return parseInt(x.id)===id}):null;var h='<h3>'+(id?'✏️ تعديل':'➕ متجر جديد')+'</h3><input type="hidden" id="ms-id" value="'+(id||0)+'">';
h+='<div style="margin-bottom:12px"><label style="font-weight:700;font-size:12px">اسم المتجر</label><input id="ms-name" value="'+(s?s.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">الدومين</label><input id="ms-domain" value="'+(s?s.domain:'')+'" placeholder="store.example.com" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px;direction:ltr"></div>';
h+='<div style="margin-bottom:12px"><label style="font-weight:700;font-size:12px">الهاتف</label><input id="ms-phone" value="'+(s?s.phone:'')+'" 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">الولاية</label><input id="ms-wilaya" value="'+(s?s.wilaya:'')+'" 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">اللون</label><input type="color" id="ms-color" value="'+(s?s.color:'#6366F1')+'" style="width:60px;height:36px;border:none;cursor:pointer"></div>';
h+='<div style="text-align:center;margin-top:16px"><button onclick="msSave()" style="padding:10px 40px;background:#6366F1;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700">💾 حفظ</button></div>';
h+='<button onclick="jQuery(\'#ms-modal\').hide()" style="position:absolute;top:12px;left:12px;background:none;border:none;font-size:20px;cursor:pointer">✕</button>';
jQuery('#ms-body').html(h);jQuery('#ms-modal').show()}
function msSave(){jQuery.post(dza.ajax,{action:'dzqcod_ms_save_store',nonce:dza.nonce,store_id:jQuery('#ms-id').val(),name:jQuery('#ms-name').val(),domain:jQuery('#ms-domain').val(),phone:jQuery('#ms-phone').val(),wilaya:jQuery('#ms-wilaya').val(),color:jQuery('#ms-color').val(),is_active:1},function(r){if(r.success)location.reload();else alert('خطأ')})}
function msSwitch(id){jQuery.post(dza.ajax,{action:'dzqcod_ms_switch',nonce:dza.nonce,store_id:id},function(){location.reload()})}
</script>
        <?php
    }
}
MultiStore::init();
