<?php
namespace DZQCOD;
defined('ABSPATH') || exit;

class NotificationCenter {
    const TABLE = 'dz_notifications';
    public function __construct() {
        add_action('dzqcod_order_created', [$this, 'on_new_order'], 5, 2);
        add_action('woocommerce_order_status_changed', [$this, 'on_status_change'], 20, 4);
        add_action('admin_footer', [$this, 'render_bell']);
        add_action('wp_ajax_dzqcod_get_notifs', [$this, 'get_notifs']);
        add_action('wp_ajax_dzqcod_mark_notifs_read', [$this, 'mark_read']);
        $this->maybe_create_table();
    }
    private function maybe_create_table(): void {
        global $wpdb;if(get_option('dzqcod_notif_table_v1'))return;
        $wpdb->query("CREATE TABLE IF NOT EXISTS {$wpdb->prefix}".self::TABLE." (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,type VARCHAR(40) NOT NULL DEFAULT 'info',title VARCHAR(200) NOT NULL,body TEXT,link VARCHAR(500),is_read TINYINT(1) DEFAULT 0,created_at DATETIME DEFAULT CURRENT_TIMESTAMP,INDEX idx_read(is_read),INDEX idx_created(created_at)) ".$wpdb->get_charset_collate());
        update_option('dzqcod_notif_table_v1',1);
    }
    public function push(string $type,string $title,string $body='',string $link=''): void {
        global $wpdb;$wpdb->insert($wpdb->prefix.self::TABLE,compact('type','title','body','link'));
        $wpdb->query("DELETE FROM {$wpdb->prefix}".self::TABLE." WHERE id NOT IN (SELECT id FROM (SELECT id FROM {$wpdb->prefix}".self::TABLE." ORDER BY id DESC LIMIT 200) t)");
    }
    public function on_new_order(int $oid,$order): void {
        $name=$order->get_billing_first_name();$total=number_format((float)$order->get_total(),0).' DA';
        $fraud=(int)$order->get_meta('_dzqcod_fraud_score');$type=$fraud>=60?'warning':'order';
        $title=$fraud>=60?"⚠️ تحذير احتيال #{$oid} — {$fraud}/100":"🛒 طلب جديد #{$oid} — {$name}";
        $this->push($type,$title,$total,admin_url('admin.php?page=dzqcod-orders&view='.$oid));
    }
    public function on_status_change(int $oid,string $from,string $to,$order): void {
        $labels=Core::ST;$fl=str_replace('wc-','',$from);$tl=str_replace('wc-','',$to);
        if(isset($labels[$tl]))$this->push('status',"طلب #{$oid}: ".($labels[$tl]['i']??'')." ".($labels[$tl]['l']??$tl),'',admin_url('admin.php?page=dzqcod-orders&view='.$oid));
    }
    public function get_notifs(): void {
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$t=$wpdb->prefix.self::TABLE;
        $rows=$wpdb->get_results("SELECT * FROM {$t} ORDER BY id DESC LIMIT 30",ARRAY_A);
        $unread=(int)$wpdb->get_var("SELECT COUNT(*) FROM {$t} WHERE is_read=0");
        wp_send_json_success(['items'=>$rows,'unread'=>$unread]);
    }
    public function mark_read(): void {
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;
        $wpdb->query("UPDATE {$wpdb->prefix}".self::TABLE." SET is_read=1 WHERE is_read=0");wp_send_json_success();
    }
    public function render_bell(): void {
        if(!current_user_can('manage_woocommerce')&&!current_user_can('manage_options'))return;
        ?>
<div id="dzqcod-bell" style="position:fixed;bottom:24px;left:24px;z-index:9999;cursor:pointer" onclick="dzqcodToggleNotifs()">
<div style="background:#1a3c5e;color:#fff;width:48px;height:48px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:22px;box-shadow:0 4px 16px rgba(0,0,0,.3)">🔔</div>
<span id="dzqcod-bell-count" style="position:absolute;top:-4px;right:-4px;background:#e74c3c;color:#fff;border-radius:50%;min-width:20px;height:20px;font-size:11px;font-weight:700;display:none;align-items:center;justify-content:center">0</span>
</div>
<div id="dzqcod-notif-panel" style="display:none;position:fixed;bottom:80px;left:24px;z-index:9998;width:340px;max-height:420px;overflow-y:auto;background:#fff;border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,.18);border:1px solid #e5e7eb">
<div style="padding:12px 16px;font-weight:700;color:#1a3c5e;border-bottom:1px solid #e5e7eb;display:flex;justify-content:space-between;align-items:center"><span>🔔 الإشعارات</span><button onclick="dzqcodMarkRead()" style="font-size:11px;color:#6b7280;background:none;border:none;cursor:pointer">قراءة الكل</button></div>
<div id="dzqcod-notif-list"></div></div>
<script>
function dzqcodToggleNotifs(){var p=document.getElementById('dzqcod-notif-panel');p.style.display=p.style.display==='none'?'block':'none';if(p.style.display==='block')dzqcodLoadNotifs()}
function dzqcodLoadNotifs(){jQuery.post(ajaxurl,{action:'dzqcod_get_notifs',nonce:typeof dza!=='undefined'?dza.nonce:''},function(r){if(!r.success)return;var c=document.getElementById('dzqcod-bell-count');c.textContent=r.data.unread;c.style.display=r.data.unread>0?'flex':'none';var l=document.getElementById('dzqcod-notif-list');l.innerHTML=r.data.items.map(function(i){return'<a href="'+(i.link||'#')+'" style="display:block;padding:10px 16px;border-bottom:1px solid #f3f4f6;background:'+(i.is_read==='1'?'#fff':'#f0f9ff')+';text-decoration:none"><div style="font-size:13px;font-weight:600;color:#1a3c5e">'+i.title+'</div><div style="font-size:11px;color:#9ca3af;margin-top:2px">'+i.created_at+'</div></a>'}).join('')||'<p style="padding:16px;color:#9ca3af;text-align:center">لا إشعارات</p>'})}
function dzqcodMarkRead(){jQuery.post(ajaxurl,{action:'dzqcod_mark_notifs_read',nonce:typeof dza!=='undefined'?dza.nonce:''},function(){dzqcodLoadNotifs()})}
setTimeout(dzqcodLoadNotifs,2000);setInterval(function(){dzqcodLoadNotifs()},30000);
</script>
<?php
    }
}
