<?php
/**
 * Addon Name: Accounting Pro
 * Description: نظام محاسبي شامل — فواتير، ضرائب (TVA/TAP/IRG/G50)، مصاريف، سجل يومي، ميزان المراجعة
 * Version: 1.0.0
 * Author: NIBRA Technology
 * Type: enterprise
 * Category: analytics
 */
namespace DZQCOD\Addons;
if (!defined('ABSPATH')) exit;
if (!\DZQCOD\Modules::is_on('accounting-pro')) return;

class AccountingPro {
    const DB_INV='dz_acc_invoices';const DB_ITEMS='dz_acc_inv_items';const DB_EXP='dz_acc_expenses';
    const DB_JRN='dz_acc_journal';const DB_TAX='dz_acc_tax_returns';const DB_CUST='dz_acc_customers';
    const COA=['101'=>'رأس المال','12'=>'نتيجة الدورة','21'=>'أصول ثابتة','30'=>'مخزون','401'=>'الموردون','411'=>'الزبائن','421'=>'رواتب','44'=>'الدولة','445'=>'TVA مستحقة','4456'=>'TVA مسترجعة','447'=>'TAP/IRG','512'=>'البنك','53'=>'الصندوق','60'=>'مشتريات','61'=>'خدمات خارجية','62'=>'خدمات أخرى','63'=>'أعباء مستخدمين','64'=>'ضرائب','65'=>'أعباء تشغيلية','66'=>'أعباء مالية','68'=>'اهتلاك','69'=>'IBS','70'=>'المبيعات','75'=>'منتجات أخرى','76'=>'منتجات مالية'];
    const TAX=['DZ'=>['tva'=>19,'tap'=>1,'irg'=>5,'ibs'=>19,'timbre'=>50],'TN'=>['tva'=>19],'MA'=>['tva'=>20],'EG'=>['tva'=>14],'SA'=>['tva'=>15],'AE'=>['tva'=>5]];
    const EXP_CATS=['shipping'=>['l'=>'🚚 شحن','a'=>'61'],'ads'=>['l'=>'📢 إعلانات','a'=>'62'],'salary'=>['l'=>'👥 رواتب','a'=>'63'],'rent'=>['l'=>'🏠 إيجار','a'=>'61'],'supplies'=>['l'=>'📦 مشتريات','a'=>'60'],'telecom'=>['l'=>'📱 اتصالات','a'=>'62'],'software'=>['l'=>'💻 برمجيات','a'=>'62'],'packaging'=>['l'=>'📦 تغليف','a'=>'60'],'tax'=>['l'=>'🏛️ ضرائب','a'=>'64'],'bank_fees'=>['l'=>'🏦 عمولات','a'=>'66'],'transport'=>['l'=>'🚗 نقل','a'=>'62'],'other'=>['l'=>'📋 أخرى','a'=>'65']];
    const INV_ST=['draft'=>['l'=>'📝 مسودة','c'=>'#9CA3AF'],'sent'=>['l'=>'📤 مرسلة','c'=>'#3B82F6'],'paid'=>['l'=>'✅ مدفوعة','c'=>'#10B981'],'partial'=>['l'=>'⏳ جزئية','c'=>'#F59E0B'],'overdue'=>['l'=>'🔴 متأخرة','c'=>'#EF4444'],'cancelled'=>['l'=>'❌ ملغاة','c'=>'#6B7280'],'refunded'=>['l'=>'🔄 مسترجعة','c'=>'#8B5CF6']];
    const INV_TYPES=['sale'=>'فاتورة بيع','purchase'=>'فاتورة شراء','credit_note'=>'إشعار دائن','proforma'=>'فاتورة شكلية','delivery'=>'بون تسليم'];

    public static function init(): void {
        foreach(['dzqcod_acc_save_inv','dzqcod_acc_del_inv','dzqcod_acc_inv_status','dzqcod_acc_dup_inv','dzqcod_acc_save_exp','dzqcod_acc_del_exp','dzqcod_acc_jrn_add','dzqcod_acc_jrn_del','dzqcod_acc_g50','dzqcod_acc_dash','dzqcod_acc_report','dzqcod_acc_export','dzqcod_acc_sync','dzqcod_acc_settings','dzqcod_acc_search_products','dzqcod_acc_save_cust','dzqcod_acc_search_cust','dzqcod_acc_del_cust'] as $a)
            add_action("wp_ajax_{$a}",[self::class,$a]);
        add_action('dzqcod_order_created',[self::class,'auto_invoice'],30,2);
        add_action('woocommerce_order_status_delivered',[self::class,'mark_paid']);
        add_action('dzqcod_admin_page_accounting-pro',[self::class,'admin_page']);
        add_action('admin_init',[self::class,'install'],5);
    }
    public static function install(): void {
        if(get_option('dzqcod_acc_v','0')==='1.1')return;
        global $wpdb;$cs=$wpdb->get_charset_collate();$p=$wpdb->prefix;
        $wpdb->query("CREATE TABLE IF NOT EXISTS {$p}".self::DB_INV." (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,inv_num VARCHAR(30) NOT NULL UNIQUE,inv_type VARCHAR(20) DEFAULT 'sale',order_id BIGINT UNSIGNED DEFAULT 0,cust_name VARCHAR(200) DEFAULT '',cust_phone VARCHAR(30) DEFAULT '',cust_address TEXT,cust_nif VARCHAR(30) DEFAULT '',cust_nis VARCHAR(30) DEFAULT '',cust_ai VARCHAR(30) DEFAULT '',cust_rc VARCHAR(30) DEFAULT '',subtotal DECIMAL(14,2) DEFAULT 0,tax_tva DECIMAL(14,2) DEFAULT 0,tax_tap DECIMAL(14,2) DEFAULT 0,tax_timbre DECIMAL(14,2) DEFAULT 0,discount DECIMAL(14,2) DEFAULT 0,shipping DECIMAL(14,2) DEFAULT 0,total DECIMAL(14,2) DEFAULT 0,paid_amount DECIMAL(14,2) DEFAULT 0,pay_method VARCHAR(30) DEFAULT 'cod',pay_ref VARCHAR(100) DEFAULT '',currency VARCHAR(5) DEFAULT 'DZD',status VARCHAR(20) DEFAULT 'draft',tva_rate DECIMAL(5,2) DEFAULT 19,notes TEXT,due_date DATE DEFAULT NULL,paid_date DATE DEFAULT NULL,created_at DATETIME DEFAULT CURRENT_TIMESTAMP,updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,INDEX idx_o(order_id),INDEX idx_s(status),INDEX idx_d(created_at)) $cs");
        $wpdb->query("CREATE TABLE IF NOT EXISTS {$p}".self::DB_ITEMS." (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,invoice_id BIGINT UNSIGNED NOT NULL,product_id BIGINT UNSIGNED DEFAULT 0,description VARCHAR(500),qty DECIMAL(10,2) DEFAULT 1,unit_price DECIMAL(14,2) DEFAULT 0,tva_rate DECIMAL(5,2) DEFAULT 19,tva_amount DECIMAL(14,2) DEFAULT 0,discount_pct DECIMAL(5,2) DEFAULT 0,line_total DECIMAL(14,2) DEFAULT 0,INDEX idx_i(invoice_id)) $cs");
        $wpdb->query("CREATE TABLE IF NOT EXISTS {$p}".self::DB_EXP." (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,category VARCHAR(30) DEFAULT 'other',description VARCHAR(500),amount DECIMAL(14,2) DEFAULT 0,tva_amount DECIMAL(14,2) DEFAULT 0,tva_rate DECIMAL(5,2) DEFAULT 0,pay_method VARCHAR(30) DEFAULT 'cash',reference VARCHAR(100) DEFAULT '',supplier VARCHAR(200) DEFAULT '',account_code VARCHAR(10) DEFAULT '65',is_recurring TINYINT(1) DEFAULT 0,expense_date DATE NOT NULL,created_at DATETIME DEFAULT CURRENT_TIMESTAMP,INDEX idx_c(category),INDEX idx_d(expense_date)) $cs");
        $wpdb->query("CREATE TABLE IF NOT EXISTS {$p}".self::DB_JRN." (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,entry_date DATE NOT NULL,reference VARCHAR(100) DEFAULT '',description VARCHAR(500),debit_acc VARCHAR(10) NOT NULL,credit_acc VARCHAR(10) NOT NULL,amount DECIMAL(14,2) NOT NULL DEFAULT 0,src_type VARCHAR(30) DEFAULT '',src_id BIGINT UNSIGNED DEFAULT 0,created_at DATETIME DEFAULT CURRENT_TIMESTAMP,INDEX idx_d(entry_date)) $cs");
        $wpdb->query("CREATE TABLE IF NOT EXISTS {$p}".self::DB_TAX." (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,period_month INT,period_year INT,return_type VARCHAR(10) DEFAULT 'G50',revenue DECIMAL(14,2) DEFAULT 0,tva_collected DECIMAL(14,2) DEFAULT 0,tva_deductible DECIMAL(14,2) DEFAULT 0,tva_due DECIMAL(14,2) DEFAULT 0,tap DECIMAL(14,2) DEFAULT 0,irg DECIMAL(14,2) DEFAULT 0,timbre DECIMAL(14,2) DEFAULT 0,total_due DECIMAL(14,2) DEFAULT 0,status VARCHAR(20) DEFAULT 'draft',filed_date DATE DEFAULT NULL,created_at DATETIME DEFAULT CURRENT_TIMESTAMP,UNIQUE KEY idx_p(period_month,period_year,return_type)) $cs");
        update_option('dzqcod_acc_v','1.1');
        // Customers table
        $wpdb->query("CREATE TABLE IF NOT EXISTS {$p}".self::DB_CUST." (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,name VARCHAR(200) NOT NULL,phone VARCHAR(30) DEFAULT '',email VARCHAR(200) DEFAULT '',address TEXT,wilaya VARCHAR(100) DEFAULT '',nif VARCHAR(30) DEFAULT '',nis VARCHAR(30) DEFAULT '',ai VARCHAR(30) DEFAULT '',rc VARCHAR(30) DEFAULT '',notes TEXT,total_invoices INT DEFAULT 0,total_amount DECIMAL(14,2) DEFAULT 0,created_at DATETIME DEFAULT CURRENT_TIMESTAMP,INDEX idx_n(name),INDEX idx_p(phone)) $cs");
    }

    private static function next_num(string $t='sale'):string{global $wpdb;$tb=$wpdb->prefix.self::DB_INV;$pf=['sale'=>'FA','purchase'=>'FC','credit_note'=>'AV','proforma'=>'PF','delivery'=>'BL'][$t]??'FA';$y=gmdate('Y');$last=$wpdb->get_var($wpdb->prepare("SELECT inv_num FROM {$tb} WHERE inv_num LIKE %s ORDER BY id DESC LIMIT 1",$pf.'-'.$y.'-%'));$seq=$last?((int)substr($last,strrpos($last,'-')+1)+1):1;return $pf.'-'.$y.'-'.str_pad($seq,5,'0',STR_PAD_LEFT);}
    private static function jrn(string $ref,string $desc,string $dr,string $cr,float $amt,string $st='',int $sid=0):void{global $wpdb;$wpdb->insert($wpdb->prefix.self::DB_JRN,['entry_date'=>current_time('Y-m-d'),'reference'=>$ref,'description'=>$desc,'debit_acc'=>$dr,'credit_acc'=>$cr,'amount'=>$amt,'src_type'=>$st,'src_id'=>$sid]);}

    public static function auto_invoice(int $oid,$order):void{
        if(\DZQCOD\Core::opt('acc_auto_invoice','yes')!=='yes')return;
        global $wpdb;$t=$wpdb->prefix.self::DB_INV;
        if($wpdb->get_var($wpdb->prepare("SELECT id FROM {$t} WHERE order_id=%d",$oid)))return;
        $cc=\DZQCOD\Core::opt('country','DZ');$tax=self::TAX[$cc]??self::TAX['DZ'];$tva_r=(float)($tax['tva']??0);$sub=0;$items=[];
        foreach($order->get_items() as $i){$q=$i->get_quantity();$p=(float)$i->get_total()/max($q,1);$l=$q*$p;$sub+=$l;
            $items[]=['product_id'=>$i->get_product_id(),'description'=>$i->get_name(),'qty'=>$q,'unit_price'=>round($p,2),'tva_rate'=>$tva_r,'tva_amount'=>round($l*$tva_r/100,2),'line_total'=>round($l,2)];}
        $ship=(float)$order->get_shipping_total();$tva=round($sub*$tva_r/100,2);$tap=isset($tax['tap'])?round($sub*$tax['tap']/100,2):0;$tim=$tax['timbre']??0;$tot=$sub+$tva+$ship+$tim;
        $num=self::next_num('sale');
        $wpdb->insert($t,['inv_num'=>$num,'inv_type'=>'sale','order_id'=>$oid,'cust_name'=>$order->get_billing_first_name().' '.$order->get_billing_last_name(),'cust_phone'=>$order->get_billing_phone(),'cust_address'=>$order->get_shipping_address_1().', '.$order->get_shipping_city().', '.$order->get_shipping_state(),'subtotal'=>$sub,'tax_tva'=>$tva,'tax_tap'=>$tap,'tax_timbre'=>$tim,'shipping'=>$ship,'total'=>$tot,'tva_rate'=>$tva_r,'currency'=>\DZQCOD\Core::opt('currency_code','DZD'),'status'=>'sent','pay_method'=>$order->get_payment_method()?:'cod']);
        $inv_id=$wpdb->insert_id;$it=$wpdb->prefix.self::DB_ITEMS;foreach($items as $item){$item['invoice_id']=$inv_id;$wpdb->insert($it,$item);}
        self::jrn($num,'فاتورة بيع #'.$oid,'411','70',$sub,'invoice',$inv_id);
        if($tva>0)self::jrn($num,'TVA #'.$oid,'411','445',$tva,'invoice',$inv_id);
        $order->update_meta_data('_dzqcod_invoice_id',$inv_id);$order->update_meta_data('_dzqcod_invoice_number',$num);$order->save();
    }
    public static function mark_paid(int $oid):void{global $wpdb;$t=$wpdb->prefix.self::DB_INV;$inv=$wpdb->get_row($wpdb->prepare("SELECT * FROM {$t} WHERE order_id=%d AND status!='paid'",$oid));if(!$inv)return;$wpdb->update($t,['status'=>'paid','paid_amount'=>$inv->total,'paid_date'=>current_time('Y-m-d')],['id'=>$inv->id]);self::jrn($inv->inv_num,'تحصيل '.$inv->inv_num,$inv->pay_method==='cod'?'53':'512','411',(float)$inv->total,'payment',$inv->id);}

    // ═══ AJAX — INVOICES ═══
    public static function dzqcod_acc_save_inv():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$t=$wpdb->prefix.self::DB_INV;$id=absint($_POST['invoice_id']??0);
        $type=sanitize_text_field($_POST['inv_type']??'sale');
        $data=['inv_type'=>$type,'cust_name'=>sanitize_text_field($_POST['cust_name']??''),'cust_phone'=>sanitize_text_field($_POST['cust_phone']??''),'cust_address'=>sanitize_textarea_field($_POST['cust_address']??''),'cust_nif'=>sanitize_text_field($_POST['cust_nif']??''),'cust_nis'=>sanitize_text_field($_POST['cust_nis']??''),'cust_ai'=>sanitize_text_field($_POST['cust_ai']??''),'cust_rc'=>sanitize_text_field($_POST['cust_rc']??''),'subtotal'=>(float)($_POST['subtotal']??0),'tax_tva'=>(float)($_POST['tax_tva']??0),'tax_tap'=>(float)($_POST['tax_tap']??0),'tax_timbre'=>(float)($_POST['tax_timbre']??0),'discount'=>(float)($_POST['discount']??0),'shipping'=>(float)($_POST['shipping']??0),'total'=>(float)($_POST['total']??0),'tva_rate'=>(float)($_POST['tva_rate']??19),'pay_method'=>sanitize_text_field($_POST['pay_method']??'cod'),'status'=>sanitize_text_field($_POST['status']??'draft'),'notes'=>sanitize_textarea_field($_POST['notes']??''),'due_date'=>sanitize_text_field($_POST['due_date']??'')?:null,'currency'=>\DZQCOD\Core::opt('currency_code','DZD')];
        if($id){$wpdb->update($t,$data,['id'=>$id]);}else{$data['inv_num']=self::next_num($type);$wpdb->insert($t,$data);$id=$wpdb->insert_id;}
        // Auto-save customer
        self::save_customer_from_invoice($_POST);
        $it=$wpdb->prefix.self::DB_ITEMS;$wpdb->delete($it,['invoice_id'=>$id]);
        $descs=(array)($_POST['item_desc']??[]);$units=(array)($_POST['item_unit']??[]);$qtys=(array)($_POST['item_qty']??[]);$prices=(array)($_POST['item_price']??[]);$tvas=(array)($_POST['item_tva']??[]);
        for($i=0;$i<count($descs);$i++){if(empty($descs[$i]))continue;$q=(float)($qtys[$i]??1);$pr=(float)($prices[$i]??0);$tv=(float)($tvas[$i]??19);$ln=$q*$pr;$unit=sanitize_text_field($units[$i]??'وحدة');
            $wpdb->insert($it,['invoice_id'=>$id,'description'=>sanitize_text_field($descs[$i]).' ['.$unit.']','qty'=>$q,'unit_price'=>$pr,'tva_rate'=>$tv,'tva_amount'=>round($ln*$tv/100,2),'line_total'=>round($ln,2)]);}
        wp_send_json_success(['id'=>$id,'message'=>'تم حفظ الفاتورة']);
    }
    public static function dzqcod_acc_del_inv():void{check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$id=absint($_POST['invoice_id']??0);$wpdb->delete($wpdb->prefix.self::DB_ITEMS,['invoice_id'=>$id]);$wpdb->delete($wpdb->prefix.self::DB_INV,['id'=>$id]);wp_send_json_success();}
    public static function dzqcod_acc_inv_status():void{check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$t=$wpdb->prefix.self::DB_INV;$id=absint($_POST['invoice_id']??0);$st=sanitize_text_field($_POST['status']??'');$d=['status'=>$st];if($st==='paid'){$d['paid_amount']=(float)$wpdb->get_var($wpdb->prepare("SELECT total FROM {$t} WHERE id=%d",$id));$d['paid_date']=current_time('Y-m-d');}$wpdb->update($t,$d,['id'=>$id]);wp_send_json_success();}
    public static function dzqcod_acc_dup_inv():void{check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$t=$wpdb->prefix.self::DB_INV;$id=absint($_POST['invoice_id']??0);$inv=$wpdb->get_row($wpdb->prepare("SELECT * FROM {$t} WHERE id=%d",$id),ARRAY_A);if(!$inv)wp_send_json_error();unset($inv['id']);$inv['inv_num']=self::next_num($inv['inv_type']);$inv['status']='draft';$inv['paid_amount']=0;$wpdb->insert($t,$inv);$nid=$wpdb->insert_id;foreach($wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}".self::DB_ITEMS." WHERE invoice_id=%d",$id),ARRAY_A) as $item){unset($item['id']);$item['invoice_id']=$nid;$wpdb->insert($wpdb->prefix.self::DB_ITEMS,$item);}wp_send_json_success(['id'=>$nid]);}

    // ═══ AJAX — EXPENSES ═══
    public static function dzqcod_acc_save_exp():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$t=$wpdb->prefix.self::DB_EXP;$id=absint($_POST['expense_id']??0);
        $cat=sanitize_text_field($_POST['category']??'other');$acc=self::EXP_CATS[$cat]['a']??'65';$amt=(float)($_POST['amount']??0);$tvr=(float)($_POST['tva_rate']??0);
        $data=['category'=>$cat,'description'=>sanitize_text_field($_POST['description']??''),'amount'=>$amt,'tva_amount'=>round($amt*$tvr/100,2),'tva_rate'=>$tvr,'pay_method'=>sanitize_text_field($_POST['pay_method']??'cash'),'reference'=>sanitize_text_field($_POST['reference']??''),'supplier'=>sanitize_text_field($_POST['supplier']??''),'account_code'=>$acc,'expense_date'=>sanitize_text_field($_POST['expense_date']??current_time('Y-m-d')),'is_recurring'=>(int)(!empty($_POST['is_recurring']))];
        if($id){$wpdb->update($t,$data,['id'=>$id]);}else{$wpdb->insert($t,$data);$id=$wpdb->insert_id;$pay=$data['pay_method']==='bank'?'512':'53';self::jrn('EXP-'.$id,$data['description'],$acc,$pay,$amt,'expense',$id);if($data['tva_amount']>0)self::jrn('EXP-'.$id,'TVA مسترجعة','4456',$pay,$data['tva_amount'],'expense',$id);}
        wp_send_json_success(['id'=>$id]);
    }
    public static function dzqcod_acc_del_exp():void{check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$wpdb->delete($wpdb->prefix.self::DB_EXP,['id'=>absint($_POST['expense_id']??0)]);wp_send_json_success();}

    // ═══ AJAX — JOURNAL ═══
    public static function dzqcod_acc_jrn_add():void{check_ajax_referer('dzqcod_admin','nonce');self::jrn(sanitize_text_field($_POST['reference']??''),sanitize_text_field($_POST['description']??''),sanitize_text_field($_POST['debit_acc']??''),sanitize_text_field($_POST['credit_acc']??''),(float)($_POST['amount']??0),'manual',0);wp_send_json_success();}
    public static function dzqcod_acc_jrn_del():void{check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$wpdb->delete($wpdb->prefix.self::DB_JRN,['id'=>absint($_POST['entry_id']??0)]);wp_send_json_success();}

    // ═══ AJAX — G50 TAX ═══
    public static function dzqcod_acc_g50():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$m=absint($_POST['month']??(int)gmdate('m'));$y=absint($_POST['year']??(int)gmdate('Y'));
        $from=sprintf('%04d-%02d-01',$y,$m);$to=gmdate('Y-m-t',strtotime($from));$cc=\DZQCOD\Core::opt('country','DZ');$tax=self::TAX[$cc]??self::TAX['DZ'];
        $it=$wpdb->prefix.self::DB_INV;$et=$wpdb->prefix.self::DB_EXP;
        $rev=(float)$wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(subtotal),0) FROM {$it} WHERE inv_type='sale' AND status IN('sent','paid','partial') AND created_at BETWEEN %s AND %s",$from,$to.' 23:59:59'));
        $tva_c=(float)$wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(tax_tva),0) FROM {$it} WHERE inv_type='sale' AND status IN('sent','paid','partial') AND created_at BETWEEN %s AND %s",$from,$to.' 23:59:59'));
        $tva_d=(float)$wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(tva_amount),0) FROM {$et} WHERE expense_date BETWEEN %s AND %s",$from,$to));
        $tva_due=max(0,$tva_c-$tva_d);$tap_r=$tax['tap']??0;$irg_r=$tax['irg']??0;$tap=round($rev*$tap_r/100,2);$irg=round($rev*$irg_r/100,2);
        $tim=(float)$wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(tax_timbre),0) FROM {$it} WHERE inv_type='sale' AND created_at BETWEEN %s AND %s",$from,$to.' 23:59:59'));
        $total=$tva_due+$tap+$irg+$tim;
        $wpdb->replace($wpdb->prefix.self::DB_TAX,['period_month'=>$m,'period_year'=>$y,'return_type'=>'G50','revenue'=>$rev,'tva_collected'=>$tva_c,'tva_deductible'=>$tva_d,'tva_due'=>$tva_due,'tap'=>$tap,'irg'=>$irg,'timbre'=>$tim,'total_due'=>$total,'status'=>'draft']);
        wp_send_json_success(compact('rev','tva_c','tva_d','tva_due','tap','irg','tim','total','m','y'));
    }

    // ═══ AJAX — DASHBOARD ═══
    public static function dzqcod_acc_dash():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$days=absint($_POST['days']??30);$from=gmdate('Y-m-d',strtotime("-{$days} days"));
        $it=$wpdb->prefix.self::DB_INV;$et=$wpdb->prefix.self::DB_EXP;
        $revenue=(float)$wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(total),0) FROM {$it} WHERE inv_type='sale' AND status IN('sent','paid','partial') AND created_at>=%s",$from));
        $expenses=(float)$wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(amount),0) FROM {$et} WHERE expense_date>=%s",$from));
        $paid=(float)$wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(paid_amount),0) FROM {$it} WHERE status='paid' AND paid_date>=%s",$from));
        $unpaid=(float)$wpdb->get_var("SELECT COALESCE(SUM(total-paid_amount),0) FROM {$it} WHERE status IN('sent','partial','overdue')");
        $tax_total=(float)$wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(tax_tva+tax_tap+tax_timbre),0) FROM {$it} WHERE inv_type='sale' AND created_at>=%s",$from));
        $inv_count=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$it} WHERE created_at>=%s",$from));
        $exp_count=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$et} WHERE expense_date>=%s",$from));
        $profit=$revenue-$expenses;
        $exp_cats=$wpdb->get_results($wpdb->prepare("SELECT category,SUM(amount) as total FROM {$et} WHERE expense_date>=%s GROUP BY category ORDER BY total DESC",$from),ARRAY_A);
        wp_send_json_success(compact('revenue','expenses','paid','unpaid','tax_total','inv_count','exp_count','profit','exp_cats'));
    }

    // ═══ AJAX — REPORTS ═══
    public static function dzqcod_acc_report():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$type=sanitize_text_field($_POST['report_type']??'trial_balance');
        $from=sanitize_text_field($_POST['from']??gmdate('Y-01-01'));$to=sanitize_text_field($_POST['to']??gmdate('Y-m-d'));$jt=$wpdb->prefix.self::DB_JRN;
        if($type==='trial_balance'){
            $debits=$wpdb->get_results($wpdb->prepare("SELECT debit_acc as acc,SUM(amount) as total FROM {$jt} WHERE entry_date BETWEEN %s AND %s GROUP BY debit_acc",$from,$to),ARRAY_A);
            $credits=$wpdb->get_results($wpdb->prepare("SELECT credit_acc as acc,SUM(amount) as total FROM {$jt} WHERE entry_date BETWEEN %s AND %s GROUP BY credit_acc",$from,$to),ARRAY_A);
            $accounts=[];foreach($debits as $d)$accounts[$d['acc']]['debit']=(float)$d['total'];foreach($credits as $c)$accounts[$c['acc']]['credit']=(float)$c['total'];
            foreach($accounts as $k=>&$v){$v['name']=self::COA[$k]??$k;$v['debit']=$v['debit']??0;$v['credit']=$v['credit']??0;$v['balance']=$v['debit']-$v['credit'];}
            ksort($accounts);wp_send_json_success(['type'=>'trial_balance','data'=>$accounts]);
        }
        if($type==='pnl'){
            $rev=(float)$wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(amount),0) FROM {$jt} WHERE credit_acc LIKE '7%%' AND entry_date BETWEEN %s AND %s",$from,$to));
            $exp=(float)$wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(amount),0) FROM {$jt} WHERE debit_acc LIKE '6%%' AND entry_date BETWEEN %s AND %s",$from,$to));
            $rev_det=$wpdb->get_results($wpdb->prepare("SELECT credit_acc as acc,SUM(amount) as total FROM {$jt} WHERE credit_acc LIKE '7%%' AND entry_date BETWEEN %s AND %s GROUP BY credit_acc",$from,$to),ARRAY_A);
            $exp_det=$wpdb->get_results($wpdb->prepare("SELECT debit_acc as acc,SUM(amount) as total FROM {$jt} WHERE debit_acc LIKE '6%%' AND entry_date BETWEEN %s AND %s GROUP BY debit_acc",$from,$to),ARRAY_A);
            wp_send_json_success(['type'=>'pnl','revenue'=>$rev,'expenses'=>$exp,'profit'=>$rev-$exp,'rev_detail'=>$rev_det,'exp_detail'=>$exp_det]);
        }
        wp_send_json_error();
    }
    public static function dzqcod_acc_export():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$what=sanitize_text_field($_POST['export_type']??'invoices');$from=sanitize_text_field($_POST['from']??gmdate('Y-01-01'));$to=sanitize_text_field($_POST['to']??gmdate('Y-m-d'));
        if($what==='invoices')$rows=$wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}".self::DB_INV." WHERE created_at BETWEEN %s AND %s ORDER BY id",$from,$to.' 23:59:59'),ARRAY_A);
        elseif($what==='expenses')$rows=$wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}".self::DB_EXP." WHERE expense_date BETWEEN %s AND %s ORDER BY id",$from,$to),ARRAY_A);
        else $rows=$wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}".self::DB_JRN." WHERE entry_date BETWEEN %s AND %s ORDER BY id",$from,$to),ARRAY_A);
        wp_send_json_success(['data'=>$rows,'type'=>$what]);
    }
    public static function dzqcod_acc_sync():void{check_ajax_referer('dzqcod_admin','nonce');$orders=wc_get_orders(['status'=>['wc-processing','wc-confirmed','wc-delivered','wc-shipped'],'limit'=>100,'orderby'=>'date','order'=>'DESC']);$synced=0;global $wpdb;$t=$wpdb->prefix.self::DB_INV;foreach($orders as $o){if(!$wpdb->get_var($wpdb->prepare("SELECT id FROM {$t} WHERE order_id=%d",$o->get_id()))){self::auto_invoice($o->get_id(),$o);$synced++;}}wp_send_json_success(['synced'=>$synced]);}
    public static function dzqcod_acc_settings():void{check_ajax_referer('dzqcod_admin','nonce');foreach(['acc_auto_invoice','acc_company_name','acc_company_address','acc_company_nif','acc_company_nis','acc_company_ai','acc_company_rc','acc_company_phone','acc_default_tva','acc_timbre'] as $f)if(isset($_POST[$f]))\DZQCOD\Core::set_opt($f,sanitize_text_field($_POST[$f]));wp_send_json_success();}

    // ═══════════════════════════════════════════
    //  ADMIN PAGE
    // ═══════════════════════════════════════════
    // ═══ AJAX — PRODUCT SEARCH (WooCommerce) ═══
    public static function dzqcod_acc_search_products():void{
        check_ajax_referer('dzqcod_admin','nonce');
        $q=sanitize_text_field($_POST['q']??'');$results=[];
        $args=['status'=>'publish','limit'=>20,'orderby'=>'title','order'=>'ASC'];
        if($q) $args['s']=$q;
        $products=wc_get_products($args);
        foreach($products as $p){
            $price=(float)$p->get_price();
            $results[]=['id'=>$p->get_id(),'name'=>$p->get_name(),'sku'=>$p->get_sku(),'price'=>$price,
                'img'=>wp_get_attachment_thumb_url($p->get_image_id())?:''];
        }
        wp_send_json_success($results);
    }

    // ═══ NUMBER TO ARABIC WORDS ═══
    public static function amount_words(float $n,string $cur='دينار جزائري'):string{
        if($n<=0)return 'صفر '.$cur;
        $ones=['','واحد','اثنان','ثلاثة','أربعة','خمسة','ستة','سبعة','ثمانية','تسعة','عشرة','أحد عشر','اثنا عشر','ثلاثة عشر','أربعة عشر','خمسة عشر','ستة عشر','سبعة عشر','ثمانية عشر','تسعة عشر'];
        $tens=['','','عشرون','ثلاثون','أربعون','خمسون','ستون','سبعون','ثمانون','تسعون'];
        $hundreds=['','مائة','مائتان','ثلاثمائة','أربعمائة','خمسمائة','ستمائة','سبعمائة','ثمانمائة','تسعمائة'];
        $int=(int)floor($n);$parts=[];
        if($int>=1000000){$m=(int)floor($int/1000000);$parts[]=($m===1?'مليون':($m===2?'مليونان':self::_small($m,$ones,$tens,$hundreds).' ملايين'));$int%=1000000;}
        if($int>=1000){$k=(int)floor($int/1000);$parts[]=($k===1?'ألف':($k===2?'ألفان':self::_small($k,$ones,$tens,$hundreds).' آلاف'));$int%=1000;}
        if($int>0)$parts[]=self::_small($int,$ones,$tens,$hundreds);
        $text=implode(' و',$parts).' '.$cur;
        $cents=round(($n-floor($n))*100);
        if($cents>0)$text.=' و'.self::_small((int)$cents,$ones,$tens,$hundreds).' سنتيم';
        return $text;
    }
    private static function _small(int $n,array $o,array $t,array $h):string{
        if($n<=0)return '';if($n<20)return $o[$n];
        $parts=[];if($n>=100){$parts[]=$h[(int)floor($n/100)];$n%=100;}
        if($n>=20){$r=$n%10;$parts[]=$t[(int)floor($n/10)];if($r>0)$parts[]=$o[$r];}
        elseif($n>0)$parts[]=$o[$n];
        return implode(' و',$parts);
    }

    // ═══ AJAX — CUSTOMERS ═══
    public static function dzqcod_acc_save_cust():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$t=$wpdb->prefix.self::DB_CUST;$id=absint($_POST['cust_id']??0);
        $data=['name'=>sanitize_text_field($_POST['name']??''),'phone'=>sanitize_text_field($_POST['phone']??''),
            'email'=>sanitize_email($_POST['email']??''),'address'=>sanitize_textarea_field($_POST['address']??''),
            'wilaya'=>sanitize_text_field($_POST['wilaya']??''),'nif'=>sanitize_text_field($_POST['nif']??''),
            'nis'=>sanitize_text_field($_POST['nis']??''),'ai'=>sanitize_text_field($_POST['ai_field']??''),
            'rc'=>sanitize_text_field($_POST['rc']??''),'notes'=>sanitize_textarea_field($_POST['notes']??'')];
        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_acc_search_cust():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$t=$wpdb->prefix.self::DB_CUST;
        $q=sanitize_text_field($_POST['q']??'');
        if($q){$like='%'.$wpdb->esc_like($q).'%';$rows=$wpdb->get_results($wpdb->prepare("SELECT * FROM {$t} WHERE name LIKE %s OR phone LIKE %s OR nif LIKE %s ORDER BY name LIMIT 20",$like,$like,$like),ARRAY_A);}
        else{$rows=$wpdb->get_results("SELECT * FROM {$t} ORDER BY id DESC LIMIT 30",ARRAY_A);}
        wp_send_json_success($rows);
    }
    public static function dzqcod_acc_del_cust():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;
        $wpdb->delete($wpdb->prefix.self::DB_CUST,['id'=>absint($_POST['cust_id']??0)]);wp_send_json_success();
    }

    // ═══ AJAX — Save customer from invoice ═══
    private static function save_customer_from_invoice(array $post):int{
        $name=sanitize_text_field($post['cust_name']??'');if(!$name)return 0;
        global $wpdb;$t=$wpdb->prefix.self::DB_CUST;$phone=sanitize_text_field($post['cust_phone']??'');
        // Find existing by phone or name
        $existing=null;
        if($phone)$existing=$wpdb->get_row($wpdb->prepare("SELECT id FROM {$t} WHERE phone=%s",$phone));
        if(!$existing)$existing=$wpdb->get_row($wpdb->prepare("SELECT id FROM {$t} WHERE name=%s",$name));
        $data=['name'=>$name,'phone'=>$phone,'email'=>sanitize_email($post['cust_email']??''),
            'address'=>sanitize_textarea_field($post['cust_address']??''),'wilaya'=>sanitize_text_field($post['cust_wilaya']??''),
            'nif'=>sanitize_text_field($post['cust_nif']??''),'nis'=>sanitize_text_field($post['cust_nis']??''),
            'ai'=>sanitize_text_field($post['cust_ai']??''),'rc'=>sanitize_text_field($post['cust_rc']??'')];
        if($existing){$wpdb->update($t,$data,['id'=>$existing->id]);return $existing->id;}
        else{$wpdb->insert($t,$data);return $wpdb->insert_id;}
    }

    public static function admin_page(): void {
        global $wpdb;$cur=\DZQCOD\Core::opt('currency_symbol','دج');
        $it=$wpdb->prefix.self::DB_INV;$et=$wpdb->prefix.self::DB_EXP;$jt=$wpdb->prefix.self::DB_JRN;
        $tab=sanitize_text_field($_GET['acc_tab']??'dashboard');
        $invoices=$wpdb->get_results("SELECT * FROM {$it} ORDER BY id DESC LIMIT 100",ARRAY_A);
        // Load items for each invoice (for printing)
        $inv_items_map=[];
        foreach($invoices as $inv){$inv_items_map[$inv['id']]=$wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}".self::DB_ITEMS." WHERE invoice_id=%d ORDER BY id",$inv['id']),ARRAY_A);}
        // Store info for print
        $store_info=['name'=>\DZQCOD\Core::opt('acc_company_name',get_bloginfo('name')),'address'=>\DZQCOD\Core::opt('acc_company_address',''),'phone'=>\DZQCOD\Core::opt('acc_company_phone',''),'nif'=>\DZQCOD\Core::opt('acc_company_nif',''),'nis'=>\DZQCOD\Core::opt('acc_company_nis',''),'ai'=>\DZQCOD\Core::opt('acc_company_ai',''),'rc'=>\DZQCOD\Core::opt('acc_company_rc','')];
        $expenses=$wpdb->get_results("SELECT * FROM {$et} ORDER BY expense_date DESC LIMIT 100",ARRAY_A);
        $journal=$wpdb->get_results("SELECT * FROM {$jt} ORDER BY entry_date DESC,id DESC LIMIT 200",ARRAY_A);
        $tax_returns=$wpdb->get_results("SELECT * FROM {$wpdb->prefix}".self::DB_TAX." ORDER BY period_year DESC,period_month DESC",ARRAY_A);
        ?>
<div class="dza-wrap" style="direction:rtl;font-family:Tajawal,sans-serif">
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:20px">
    <div><h2 style="margin:0;font-size:24px">🧾 النظام المحاسبي</h2><p style="color:#666;margin:4px 0 0">فواتير، مصاريف، ضرائب، سجل يومي، تقارير مالية</p></div>
</div>
<div style="display:flex;gap:4px;margin-bottom:20px;flex-wrap:wrap">
<?php foreach(['dashboard'=>'📊 لوحة التحكم','invoices'=>'🧾 الفواتير','customers'=>'👥 الزبائن','expenses'=>'💸 المصاريف','journal'=>'📒 السجل اليومي','tax'=>'🏛️ الضرائب','reports'=>'📈 التقارير','settings'=>'⚙️ الإعدادات'] as $k=>$v): ?>
<a href="<?php echo esc_url(add_query_arg('acc_tab',$k)); ?>" style="padding:8px 16px;border-radius:8px;text-decoration:none;font-weight:700;font-size:13px;<?php echo $tab===$k?'background:#6366F1;color:#fff':'background:#f1f5f9;color:#475569'; ?>"><?php echo $v; ?></a>
<?php endforeach; ?>
</div>

<?php if($tab==='dashboard'): ?>
<div id="acc-dash"><div style="text-align:center;padding:40px;color:#888">⏳ جاري التحميل...</div></div>
<script>jQuery(function($){$.post(dza.ajax,{action:'dzqcod_acc_dash',nonce:dza.nonce,days:30},function(r){if(!r.success)return;var d=r.data,c='<?php echo esc_js($cur); ?>';
var h='<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px">';
[{l:'💰 الإيرادات',v:d.revenue,co:'#10B981'},{l:'💸 المصاريف',v:d.expenses,co:'#EF4444'},{l:'📈 الربح',v:d.profit,co:d.profit>=0?'#10B981':'#EF4444'},{l:'⏳ غير محصّل',v:d.unpaid,co:'#F59E0B'},{l:'🏛️ ضرائب',v:d.tax_total,co:'#8B5CF6'},{l:'✅ محصّل',v:d.paid,co:'#3B82F6'},{l:'🧾 فواتير',v:d.inv_count,co:'#6366F1',n:1},{l:'💸 عدد مصاريف',v:d.exp_count,co:'#F97316',n:1}].forEach(function(s){h+='<div style="background:#fff;border-radius:12px;padding:16px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,.06)"><div style="font-size:11px;color:#888">'+s.l+'</div><div style="font-size:24px;font-weight:800;color:'+s.co+';margin-top:4px">'+(s.n?s.v:Number(s.v).toLocaleString()+' '+c)+'</div></div>'});
h+='</div><div style="display:grid;grid-template-columns:1fr 1fr;gap:16px"><div style="background:#fff;border-radius:12px;padding:20px;box-shadow:0 2px 8px rgba(0,0,0,.06)"><h4 style="margin:0 0 12px">💸 توزيع المصاريف</h4>';
var cats=<?php echo wp_json_encode(self::EXP_CATS); ?>;(d.exp_cats||[]).forEach(function(e){var ct=cats[e.category]||{l:e.category};h+='<div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #f0f0f0"><span>'+ct.l+'</span><strong>'+Number(e.total).toLocaleString()+' '+c+'</strong></div>'});
h+='</div><div style="background:#fff;border-radius:12px;padding:20px;box-shadow:0 2px 8px rgba(0,0,0,.06)"><h4 style="margin:0 0 12px">📊 نسب</h4>';
h+='<div style="padding:8px 0;border-bottom:1px solid #f0f0f0">هامش الربح: <strong style="color:'+(d.revenue>0?'#10B981':'#888')+'">'+(d.revenue>0?Math.round(d.profit/d.revenue*100):0)+'%</strong></div>';
h+='<div style="padding:8px 0;border-bottom:1px solid #f0f0f0">معدل التحصيل: <strong style="color:#3B82F6">'+(d.revenue>0?Math.round(d.paid/d.revenue*100):0)+'%</strong></div>';
h+='<div style="padding:8px 0">نسبة الضرائب: <strong style="color:#8B5CF6">'+(d.revenue>0?Math.round(d.tax_total/d.revenue*100):0)+'%</strong></div></div></div>';
$('#acc-dash').html(h)})});</script>

<?php elseif($tab==='invoices'): ?>
<div style="display:flex;gap:8px;margin-bottom:16px">
    <button onclick="accInvForm(0)" class="dza-btn" style="background:#6366F1;color:#fff;padding:8px 20px;border-radius:8px;border:none;cursor:pointer;font-weight:700">➕ فاتورة جديدة</button>
    <button onclick="accSync()" class="dza-btn" style="background:#10B981;color:#fff;padding:8px 20px;border-radius:8px;border:none;cursor:pointer;font-weight:700">🔄 مزامنة الطلبات</button>
</div>
<div style="background:#fff;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.06);overflow-x:auto">
<table style="width:100%;border-collapse:collapse;font-size:12px"><thead><tr style="background:#f8f9fa;font-weight:700">
<th style="padding:8px;text-align:right">الرقم</th><th style="padding:8px;text-align:right">النوع</th><th style="padding:8px;text-align:right">الزبون</th><th style="padding:8px;text-align:center">HT</th><th style="padding:8px;text-align:center">TVA</th><th style="padding:8px;text-align:center">TTC</th><th style="padding:8px;text-align:center">الحالة</th><th style="padding:8px;text-align:center">التاريخ</th><th style="padding:8px;text-align:center">إجراءات</th>
</tr></thead><tbody>
<?php foreach($invoices as $inv):$st=self::INV_ST[$inv['status']]??['l'=>$inv['status'],'c'=>'#888'];$tp=self::INV_TYPES[$inv['inv_type']]??$inv['inv_type']; ?>
<tr style="border-bottom:1px solid #f0f0f0">
<td style="padding:8px;font-weight:700;color:#6366F1"><?php echo esc_html($inv['inv_num']); ?></td>
<td style="padding:8px;font-size:11px"><?php echo esc_html($tp); ?></td>
<td style="padding:8px"><?php echo esc_html($inv['cust_name']); ?><?php if($inv['order_id']): ?><span style="color:#888;font-size:10px"> #<?php echo $inv['order_id']; ?></span><?php endif; ?></td>
<td style="padding:8px;text-align:center"><?php echo number_format($inv['subtotal'],0); ?></td>
<td style="padding:8px;text-align:center"><?php echo number_format($inv['tax_tva'],0); ?></td>
<td style="padding:8px;text-align:center;font-weight:700"><?php echo number_format($inv['total'],0); ?> <?php echo esc_html($cur); ?></td>
<td style="padding:8px;text-align:center"><span style="background:<?php echo $st['c']; ?>20;color:<?php echo $st['c']; ?>;padding:2px 8px;border-radius:4px;font-size:10px;font-weight:700"><?php echo $st['l']; ?></span></td>
<td style="padding:8px;text-align:center;font-size:11px"><?php echo date_i18n('Y/m/d',strtotime($inv['created_at'])); ?></td>
<td style="padding:8px;text-align:center;white-space:nowrap">
<button onclick="accInvForm(<?php echo $inv['id']; ?>)" class="dza-btn ghost" style="padding:3px 6px;font-size:10px">✏️</button>
<button onclick="accDup(<?php echo $inv['id']; ?>)" class="dza-btn ghost" style="padding:3px 6px;font-size:10px">📋</button>
<button onclick="accPrint(<?php echo $inv['id']; ?>)" class="dza-btn ghost" style="padding:3px 6px;font-size:10px" title="طباعة الفاتورة">🖨️</button>
<button onclick="accBL(<?php echo $inv['id']; ?>)" class="dza-btn ghost" style="padding:3px 6px;font-size:10px;color:#3B82F6" title="وصل تسليم">📄</button>
<?php if($inv['status']!=='paid'): ?><button onclick="accInvSt(<?php echo $inv['id']; ?>,'paid')" class="dza-btn ghost" style="padding:3px 6px;font-size:10px;color:#10B981">✅</button><?php endif; ?>
<button onclick="accInvDel(<?php echo $inv['id']; ?>)" class="dza-btn ghost" style="padding:3px 6px;font-size:10px;color:#ef4444">🗑️</button>
</td></tr>
<?php endforeach;if(empty($invoices)):?><tr><td colspan="9" style="padding:30px;text-align:center;color:#aaa">لا توجد فواتير</td></tr><?php endif;?>
</tbody></table></div>

<?php elseif($tab==='customers'): ?>
<!-- CUSTOMERS -->
<button onclick="accCustForm(0)" class="dza-btn" style="background:#6366F1;color:#fff;padding:8px 20px;border-radius:8px;border:none;cursor:pointer;font-weight:700;margin-bottom:16px">➕ زبون جديد</button>
<div style="background:#fff;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.06);overflow-x:auto">
<table style="width:100%;border-collapse:collapse;font-size:12px"><thead><tr style="background:#f8f9fa;font-weight:700"><th style="padding:8px">#</th><th style="padding:8px;text-align:right">الاسم</th><th style="padding:8px;text-align:right">الهاتف</th><th style="padding:8px;text-align:right">الولاية</th><th style="padding:8px;text-align:center">NIF</th><th style="padding:8px;text-align:center">RC</th><th style="padding:8px;text-align:center">إجراءات</th></tr></thead><tbody id="cust-tbody">
<tr><td colspan="7" style="padding:30px;text-align:center;color:#aaa">⏳ تحميل...</td></tr>
</tbody></table></div>
<script>
jQuery(function($){$.post(dza.ajax,{action:'dzqcod_acc_search_cust',nonce:dza.nonce,q:''},function(r){
    if(!r.success)return;var h='';(r.data||[]).forEach(function(c){
        h+='<tr style="border-bottom:1px solid #f0f0f0"><td style="padding:8px;color:#888">#'+c.id+'</td><td style="padding:8px;font-weight:700">'+c.name+'</td><td style="padding:8px">'+c.phone+'</td><td style="padding:8px">'+c.wilaya+'</td><td style="padding:8px;text-align:center;font-size:11px">'+c.nif+'</td><td style="padding:8px;text-align:center;font-size:11px">'+c.rc+'</td><td style="padding:8px;text-align:center"><button onclick="accCustForm('+c.id+')" style="padding:3px 6px;background:#f1f5f9;border:none;border-radius:4px;cursor:pointer;font-size:10px">✏️</button> <button onclick="if(confirm(\'حذف؟\'))jQuery.post(dza.ajax,{action:\'dzqcod_acc_del_cust\',nonce:dza.nonce,cust_id:'+c.id+'},function(){location.reload()})" style="padding:3px 6px;background:none;border:none;color:#ef4444;cursor:pointer;font-size:10px">🗑️</button></td></tr>'});
    if(!h)h='<tr><td colspan="7" style="padding:30px;text-align:center;color:#aaa">لا يوجد زبائن</td></tr>';
    $('#cust-tbody').html(h)})});
</script>

<?php elseif($tab==='expenses'): ?>
<button onclick="accExpForm()" class="dza-btn" style="background:#F59E0B;color:#fff;padding:8px 20px;border-radius:8px;border:none;cursor:pointer;font-weight:700;margin-bottom:16px">➕ مصروف جديد</button>
<div style="background:#fff;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.06);overflow-x:auto">
<table style="width:100%;border-collapse:collapse;font-size:12px"><thead><tr style="background:#f8f9fa;font-weight:700"><th style="padding:8px">#</th><th style="padding:8px;text-align:right">الفئة</th><th style="padding:8px;text-align:right">الوصف</th><th style="padding:8px;text-align:right">المورد</th><th style="padding:8px;text-align:center">المبلغ</th><th style="padding:8px;text-align:center">TVA</th><th style="padding:8px;text-align:center">التاريخ</th><th style="padding:8px;text-align:center">🗑️</th></tr></thead><tbody>
<?php foreach($expenses as $exp):$cat=self::EXP_CATS[$exp['category']]??['l'=>$exp['category']];?>
<tr style="border-bottom:1px solid #f0f0f0"><td style="padding:8px;color:#888">#<?php echo $exp['id'];?></td><td style="padding:8px"><?php echo $cat['l'];?></td><td style="padding:8px"><?php echo esc_html($exp['description']);?></td><td style="padding:8px;font-size:11px"><?php echo esc_html($exp['supplier']);?></td><td style="padding:8px;text-align:center;font-weight:700"><?php echo number_format($exp['amount'],0);?> <?php echo esc_html($cur);?></td><td style="padding:8px;text-align:center"><?php echo number_format($exp['tva_amount'],0);?></td><td style="padding:8px;text-align:center;font-size:11px"><?php echo esc_html($exp['expense_date']);?></td><td style="padding:8px;text-align:center"><button onclick="accExpDel(<?php echo $exp['id'];?>)" style="background:none;border:none;color:#ef4444;cursor:pointer">🗑️</button></td></tr>
<?php endforeach;if(empty($expenses)):?><tr><td colspan="8" style="padding:30px;text-align:center;color:#aaa">لا توجد مصاريف</td></tr><?php endif;?>
</tbody></table></div>

<?php elseif($tab==='journal'): ?>
<button onclick="accJrnForm()" class="dza-btn" style="background:#3B82F6;color:#fff;padding:8px 20px;border-radius:8px;border:none;cursor:pointer;font-weight:700;margin-bottom:16px">➕ قيد يدوي</button>
<div style="background:#fff;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.06);overflow-x:auto">
<table style="width:100%;border-collapse:collapse;font-size:12px"><thead><tr style="background:#f8f9fa;font-weight:700"><th style="padding:8px">#</th><th style="padding:8px;text-align:right">التاريخ</th><th style="padding:8px;text-align:right">المرجع</th><th style="padding:8px;text-align:right">البيان</th><th style="padding:8px;text-align:center">مدين</th><th style="padding:8px;text-align:center">دائن</th><th style="padding:8px;text-align:center">المبلغ</th><th style="padding:8px">🗑️</th></tr></thead><tbody>
<?php $coa=self::COA;foreach($journal as $j):?>
<tr style="border-bottom:1px solid #f0f0f0"><td style="padding:6px;color:#888;font-size:11px"><?php echo $j['id'];?></td><td style="padding:6px;font-size:11px"><?php echo esc_html($j['entry_date']);?></td><td style="padding:6px;font-size:11px;color:#6366F1"><?php echo esc_html($j['reference']);?></td><td style="padding:6px"><?php echo esc_html($j['description']);?></td><td style="padding:6px;text-align:center;font-size:11px"><?php echo esc_html($j['debit_acc'].' '.($coa[$j['debit_acc']]??''));?></td><td style="padding:6px;text-align:center;font-size:11px"><?php echo esc_html($j['credit_acc'].' '.($coa[$j['credit_acc']]??''));?></td><td style="padding:6px;text-align:center;font-weight:700"><?php echo number_format($j['amount'],0);?></td><td style="padding:6px"><button onclick="accJrnDel(<?php echo $j['id'];?>)" style="background:none;border:none;color:#ef4444;cursor:pointer;font-size:11px">🗑️</button></td></tr>
<?php endforeach;?>
</tbody></table></div>

<?php elseif($tab==='tax'): ?>
<div style="display:flex;gap:8px;margin-bottom:16px;align-items:center">
    <select id="g50-m" style="padding:8px;border:1px solid #ddd;border-radius:6px"><?php for($i=1;$i<=12;$i++):?><option value="<?php echo $i;?>" <?php selected($i,(int)gmdate('m'));?>><?php echo $i;?></option><?php endfor;?></select>
    <input type="number" id="g50-y" value="<?php echo gmdate('Y');?>" style="padding:8px;border:1px solid #ddd;border-radius:6px;width:100px">
    <button onclick="accG50()" class="dza-btn" style="background:#8B5CF6;color:#fff;padding:8px 20px;border-radius:8px;border:none;cursor:pointer;font-weight:700">🏛️ إنشاء G50</button>
</div>
<div id="g50-res"></div>
<?php if(!empty($tax_returns)):?>
<div style="background:#fff;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.06);overflow-x:auto;margin-top:16px">
<table style="width:100%;border-collapse:collapse;font-size:12px"><thead><tr style="background:#f8f9fa;font-weight:700"><th style="padding:8px">الفترة</th><th style="padding:8px;text-align:center">الإيرادات</th><th style="padding:8px;text-align:center">TVA مستحقة</th><th style="padding:8px;text-align:center">TVA مسترجعة</th><th style="padding:8px;text-align:center">TVA واجبة</th><th style="padding:8px;text-align:center">TAP</th><th style="padding:8px;text-align:center">IRG</th><th style="padding:8px;text-align:center;font-weight:800">المجموع</th></tr></thead><tbody>
<?php foreach($tax_returns as $tr):?>
<tr style="border-bottom:1px solid #f0f0f0"><td style="padding:8px;font-weight:700"><?php echo $tr['period_month'].'/'.$tr['period_year'];?></td><td style="padding:8px;text-align:center"><?php echo number_format($tr['revenue'],0);?></td><td style="padding:8px;text-align:center"><?php echo number_format($tr['tva_collected'],0);?></td><td style="padding:8px;text-align:center;color:#10B981"><?php echo number_format($tr['tva_deductible'],0);?></td><td style="padding:8px;text-align:center"><?php echo number_format($tr['tva_due'],0);?></td><td style="padding:8px;text-align:center"><?php echo number_format($tr['tap'],0);?></td><td style="padding:8px;text-align:center"><?php echo number_format($tr['irg'],0);?></td><td style="padding:8px;text-align:center;font-weight:800;color:#EF4444"><?php echo number_format($tr['total_due'],0);?> <?php echo esc_html($cur);?></td></tr>
<?php endforeach;?></tbody></table></div>
<?php endif;?>

<?php elseif($tab==='reports'): ?>
<div style="display:flex;gap:8px;margin-bottom:16px;align-items:center;flex-wrap:wrap">
    <input type="date" id="rpt-from" value="<?php echo gmdate('Y-01-01');?>" style="padding:8px;border:1px solid #ddd;border-radius:6px">
    <input type="date" id="rpt-to" value="<?php echo gmdate('Y-m-d');?>" style="padding:8px;border:1px solid #ddd;border-radius:6px">
    <button onclick="accRpt('trial_balance')" class="dza-btn" style="background:#3B82F6;color:#fff;padding:8px 16px;border-radius:8px;border:none;cursor:pointer;font-weight:700">📊 ميزان المراجعة</button>
    <button onclick="accRpt('pnl')" class="dza-btn" style="background:#10B981;color:#fff;padding:8px 16px;border-radius:8px;border:none;cursor:pointer;font-weight:700">📈 حساب النتائج</button>
    <button onclick="accExp('invoices')" class="dza-btn" style="background:#F59E0B;color:#fff;padding:8px 16px;border-radius:8px;border:none;cursor:pointer;font-weight:700">📥 تصدير فواتير CSV</button>
    <button onclick="accExp('expenses')" class="dza-btn" style="background:#EF4444;color:#fff;padding:8px 16px;border-radius:8px;border:none;cursor:pointer;font-weight:700">📥 تصدير مصاريف</button>
</div>
<div id="rpt-res"></div>

<?php elseif($tab==='settings'): ?>
<div style="background:#fff;border-radius:12px;padding:24px;max-width:600px;box-shadow:0 2px 8px rgba(0,0,0,.06)">
<h3 style="margin:0 0 16px">⚙️ إعدادات المحاسبة</h3>
<?php foreach(['acc_auto_invoice'=>['l'=>'إنشاء فواتير تلقائية','t'=>'toggle','d'=>'yes'],'acc_company_name'=>['l'=>'اسم الشركة','t'=>'text','d'=>''],'acc_company_address'=>['l'=>'العنوان','t'=>'text','d'=>''],'acc_company_nif'=>['l'=>'NIF','t'=>'text','d'=>''],'acc_company_nis'=>['l'=>'NIS','t'=>'text','d'=>''],'acc_company_ai'=>['l'=>'AI','t'=>'text','d'=>''],'acc_company_rc'=>['l'=>'RC','t'=>'text','d'=>''],'acc_company_phone'=>['l'=>'الهاتف','t'=>'text','d'=>''],'acc_default_tva'=>['l'=>'TVA % الافتراضية','t'=>'number','d'=>'19'],'acc_timbre'=>['l'=>'الطابع الجبائي','t'=>'number','d'=>'50']] as $k=>$f):$v=\DZQCOD\Core::opt($k,$f['d']);?>
<div style="margin-bottom:12px"><label style="font-weight:700;font-size:12px;display:block;margin-bottom:4px"><?php echo $f['l'];?></label>
<?php if($f['t']==='toggle'):?><label><input type="checkbox" class="acc-set" data-key="<?php echo esc_attr($k);?>" <?php checked($v,'yes');?>> تفعيل</label>
<?php else:?><input type="<?php echo $f['t'];?>" class="acc-set" data-key="<?php echo esc_attr($k);?>" value="<?php echo esc_attr($v);?>" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"><?php endif;?>
</div><?php endforeach;?>
<button onclick="accSaveSet()" class="dza-btn" style="background:#6366F1;color:#fff;padding:10px 30px;border-radius:8px;border:none;cursor:pointer;font-weight:700">💾 حفظ</button>
</div>
<?php endif; ?>

<!-- MODAL -->
<div id="acc-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="acc-mbody" style="max-width:800px;margin:30px auto;background:#fff;border-radius:16px;padding:32px;direction:rtl;position:relative"></div></div>
<script>
var accCOA=<?php echo wp_json_encode(self::COA);?>,accCats=<?php echo wp_json_encode(self::EXP_CATS);?>,accSts=<?php echo wp_json_encode(self::INV_ST);?>,accTypes=<?php echo wp_json_encode(self::INV_TYPES);?>,accInvs=<?php echo wp_json_encode($invoices);?>,accItems=<?php echo wp_json_encode($inv_items_map);?>,accStore=<?php echo wp_json_encode($store_info);?>,cs='<?php echo esc_js($cur);?>';
function accM(h){jQuery('#acc-mbody').html(h+'<button onclick="jQuery(\'#acc-modal\').hide()" style="position:absolute;top:12px;left:12px;background:none;border:none;font-size:20px;cursor:pointer">✕</button>');jQuery('#acc-modal').show()}
function accInvForm(id){var inv=id?accInvs.find(function(i){return parseInt(i.id)===id}):null;var tO='',sO='';for(var k in accTypes)tO+='<option value="'+k+'"'+(inv&&inv.inv_type===k?' selected':'')+'>'+accTypes[k]+'</option>';for(var k in accSts)sO+='<option value="'+k+'"'+(inv&&inv.status===k?' selected':'')+'>'+accSts[k].l+'</option>';
var h='<h3>'+(id?'✏️ تعديل فاتورة':'➕ فاتورة جديدة')+'</h3><input type="hidden" id="inv-id" value="'+(id||0)+'"><div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">';
h+='<div><label style="font-weight:700;font-size:12px">النوع</label><select id="inv-type" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px">'+tO+'</select></div>';
h+='<div><label style="font-weight:700;font-size:12px">الحالة</label><select id="inv-st" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px">'+sO+'</select></div>';
h+='<div><label style="font-weight:700;font-size:12px">الزبون</label><div style="position:relative"><input id="inv-name" value="'+(inv?inv.cust_name:'')+'" placeholder="ابحث أو اكتب اسم الزبون" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px" oninput="accCustSearch(this.value)"><div id="cust-suggest" style="display:none;position:absolute;top:100%;left:0;right:0;background:#fff;border:1px solid #ddd;border-radius:0 0 8px 8px;max-height:200px;overflow-y:auto;z-index:100;box-shadow:0 4px 12px rgba(0,0,0,.1)"></div></div></div>';
h+='<div><label style="font-weight:700;font-size:12px">الهاتف</label><input id="inv-phone" value="'+(inv?inv.cust_phone:'')+'" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div><label style="font-weight:700;font-size:12px">البريد</label><input id="inv-email" type="email" value="'+(inv?inv.cust_email||'':'')+'" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div><label style="font-weight:700;font-size:12px">الولاية</label><input id="inv-wilaya" value="'+(inv?inv.cust_wilaya||'':'')+'" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div style="grid-column:span 2"><label style="font-weight:700;font-size:12px">العنوان</label><input id="inv-addr" value="'+(inv?inv.cust_address:'')+'" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div><label style="font-weight:700;font-size:12px">NIF</label><input id="inv-nif" value="'+(inv?inv.cust_nif:'')+'" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div><label style="font-weight:700;font-size:12px">NIS</label><input id="inv-nis" value="'+(inv?inv.cust_nis||'':'')+'" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div><label style="font-weight:700;font-size:12px">AI (المادة)</label><input id="inv-ai" value="'+(inv?inv.cust_ai:'')+'" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div><label style="font-weight:700;font-size:12px">RC</label><input id="inv-rc" value="'+(inv?inv.cust_rc:'')+'" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='</div><h4 style="margin:16px 0 8px">📋 بنود الفاتورة</h4>';
h+='<div style="display:grid;grid-template-columns:30px 3fr 80px 80px 80px 70px 80px 30px;gap:4px;margin-bottom:4px;font-size:10px;font-weight:700;color:#64748b;text-align:center"><div></div><div style="text-align:right">البيان</div><div>الوحدة</div><div>الكمية</div><div>السعر</div><div>TVA%</div><div>المجموع</div><div></div></div>';
h+='<div id="inv-items"></div><button type="button" onclick="accAddI()" style="margin:8px 0;padding:6px 16px;border:1px dashed #6366F1;background:none;color:#6366F1;border-radius:6px;cursor:pointer;font-weight:700">➕ إضافة بند</button>';
h+='<div style="background:#f8fafc;border-radius:8px;padding:12px;margin-top:12px"><div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:8px">';
h+='<div><label style="font-size:11px;font-weight:700">المجموع HT</label><input type="number" id="inv-sub" value="'+(inv?inv.subtotal:0)+'" style="width:100%;padding:6px;border:1px solid #ddd;border-radius:6px;font-weight:700" readonly></div>';
h+='<div><label style="font-size:11px;font-weight:700">TVA %</label><input type="number" id="inv-tvr" value="'+(inv?inv.tva_rate:19)+'" style="width:100%;padding:6px;border:1px solid #ddd;border-radius:6px" oninput="accCalc()"></div>';
h+='<div><label style="font-size:11px;font-weight:700">مبلغ TVA</label><div id="inv-tva-amt" style="padding:8px;font-weight:700;color:#F59E0B">0</div></div>';
h+='<div><label style="font-size:11px;font-weight:700;color:#10B981">الإجمالي TTC</label><input type="number" id="inv-tot" value="'+(inv?inv.total:0)+'" style="width:100%;padding:6px;border:2px solid #10B981;border-radius:6px;font-weight:800;font-size:16px;color:#10B981" readonly></div>';
h+='</div></div>';
h+='<div style="background:#eff6ff;border-radius:8px;padding:10px;margin-top:8px;font-size:12px"><strong>توقفت هذه الفاتورة عند مبلغ:</strong> <span id="inv-words" style="color:#1e40af;font-weight:700">—</span></div>';
h+='<div style="margin-top:8px"><label style="font-size:11px">ملاحظات</label><textarea id="inv-notes" rows="2" style="width:100%;padding:6px;border:1px solid #ddd;border-radius:6px">'+(inv?inv.notes||'':'')+'</textarea></div>';
h+='<div style="text-align:center;margin-top:16px"><button onclick="accSaveInv()" style="padding:10px 40px;background:#6366F1;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700">💾 حفظ</button></div>';accM(h);if(!id)accAddI()}
function accAddI(d,q,p,t,u){
var idx=jQuery('.ii').length+1;
jQuery('#inv-items').append('<div class="ii" style="display:grid;grid-template-columns:30px 3fr 80px 80px 80px 70px 80px 30px;gap:4px;margin-bottom:4px;align-items:center">'
+'<button type="button" onclick="accSearchProd(this)" style="background:#6366F1;color:#fff;border:none;border-radius:4px;padding:4px 6px;cursor:pointer;font-size:10px" title="🔍 بحث منتج">🔍</button>'
+'<input class="ii-d" placeholder="اسم المنتج / الوصف" value="'+(d||'')+'" style="padding:6px;border:1px solid #ddd;border-radius:4px;font-size:12px">'
+'<select class="ii-u" style="padding:6px;border:1px solid #ddd;border-radius:4px;font-size:11px"><option value="وحدة"'+(u==='وحدة'||!u?' selected':'')+'>وحدة</option><option value="قطعة"'+(u==='قطعة'?' selected':'')+'>قطعة</option><option value="كغ"'+(u==='كغ'?' selected':'')+'>كغ</option><option value="لتر"'+(u==='لتر'?' selected':'')+'>لتر</option><option value="متر"'+(u==='متر'?' selected':'')+'>متر</option><option value="علبة"'+(u==='علبة'?' selected':'')+'>علبة</option><option value="ساعة"'+(u==='ساعة'?' selected':'')+'>ساعة</option><option value="خدمة"'+(u==='خدمة'?' selected':'')+'>خدمة</option></select>'
+'<input type="number" class="ii-q" value="'+(q||1)+'" min="0.01" step="any" style="padding:6px;border:1px solid #ddd;border-radius:4px;text-align:center;font-size:12px" oninput="accCalc()">'
+'<input type="number" class="ii-p" value="'+(p||0)+'" min="0" step="any" style="padding:6px;border:1px solid #ddd;border-radius:4px;text-align:center;font-size:12px" oninput="accCalc()">'
+'<input type="number" class="ii-t" value="'+(t||19)+'" min="0" step="any" style="padding:6px;border:1px solid #ddd;border-radius:4px;text-align:center;font-size:11px" oninput="accCalc()">'
+'<div class="ii-total" style="text-align:center;font-weight:700;font-size:12px;color:#10B981">0</div>'
+'<button onclick="jQuery(this).closest(\'.ii\').remove();accCalc()" style="background:#ef4444;color:#fff;border:none;border-radius:4px;padding:4px 6px;cursor:pointer;font-size:10px">✕</button>'
+'</div>');accCalc()}
function accSearchProd(btn){var $row=jQuery(btn).closest('.ii');
// Use a separate overlay on top of the invoice modal
jQuery('#acc-prod-overlay').remove();
var h='<div id="acc-prod-overlay" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.6);z-index:100000;display:flex;align-items:center;justify-content:center">';
h+='<div style="background:#fff;border-radius:16px;padding:24px;width:90%;max-width:500px;direction:rtl;position:relative;max-height:80vh;overflow-y:auto">';
h+='<button onclick="jQuery(\'#acc-prod-overlay\').remove()" style="position:absolute;top:10px;left:10px;background:none;border:none;font-size:20px;cursor:pointer">✕</button>';
h+='<h3 style="margin:0 0 12px">🔍 اختيار منتج من المتجر</h3>';
h+='<input id="prod-q" placeholder="ابحث باسم المنتج..." style="width:100%;padding:10px;border:1px solid #ddd;border-radius:8px;margin-bottom:12px;font-size:14px" autofocus>';
h+='<div id="prod-results" style="max-height:400px;overflow-y:auto"></div></div></div>';
jQuery('body').append(h);
jQuery('#prod-q').on('input',function(){var v=jQuery(this).val();clearTimeout(window._pTimer);window._pTimer=setTimeout(function(){
jQuery.post(dza.ajax,{action:'dzqcod_acc_search_products',nonce:dza.nonce,q:v},function(r){if(!r.success)return;var h='';(r.data||[]).forEach(function(p){h+='<div class="prod-pick" data-name="'+p.name+'" data-price="'+p.price+'" style="display:flex;align-items:center;gap:10px;padding:10px;border-bottom:1px solid #f0f0f0;cursor:pointer;transition:.15s" onmouseover="this.style.background=\'#f0f9ff\'" onmouseout="this.style.background=\'none\'">'+(p.img?'<img src="'+p.img+'" style="width:40px;height:40px;border-radius:6px;object-fit:cover">':'<div style="width:40px;height:40px;background:#f1f5f9;border-radius:6px;display:flex;align-items:center;justify-content:center">📦</div>')+'<div style="flex:1"><div style="font-weight:700;font-size:13px">'+p.name+'</div>'+(p.sku?'<div style="font-size:10px;color:#94a3b8">SKU: '+p.sku+'</div>':'')+'</div><div style="font-weight:800;color:#10B981;font-size:15px">'+Number(p.price).toLocaleString()+' '+cs+'</div></div>'});
if(!h)h='<div style="text-align:center;padding:20px;color:#aaa">لا توجد نتائج</div>';jQuery('#prod-results').html(h)})},300)});
jQuery('#prod-q').trigger('input');
jQuery(document).off('click.prodpick').on('click.prodpick','.prod-pick',function(){
    var n=jQuery(this).data('name'),p=jQuery(this).data('price');
    $row.find('.ii-d').val(n);$row.find('.ii-p').val(p);accCalc();
    jQuery('#acc-prod-overlay').remove();
    jQuery(document).off('click.prodpick');
})}
function accCalc(){var s=0;jQuery('.ii').each(function(){var q=parseFloat(jQuery(this).find('.ii-q').val())||0,p=parseFloat(jQuery(this).find('.ii-p').val())||0,lt=q*p;jQuery(this).find('.ii-total').text(Number(lt.toFixed(0)).toLocaleString());s+=lt});var t=parseFloat(jQuery('#inv-tvr').val())||0;var tva=s*t/100;var total=s+tva;jQuery('#inv-sub').val(s.toFixed(2));jQuery('#inv-tot').val(total.toFixed(2));if(jQuery('#inv-tva-amt').length)jQuery('#inv-tva-amt').text(Number(tva.toFixed(0)).toLocaleString());if(jQuery('#inv-words').length)jQuery('#inv-words').text(accNumWords(total))}
function accNumWords(n){if(n<=0)return'صفر دينار جزائري';var o=['','واحد','اثنان','ثلاثة','أربعة','خمسة','ستة','سبعة','ثمانية','تسعة','عشرة','أحد عشر','اثنا عشر','ثلاثة عشر','أربعة عشر','خمسة عشر','ستة عشر','سبعة عشر','ثمانية عشر','تسعة عشر'];var t=['','','عشرون','ثلاثون','أربعون','خمسون','ستون','سبعون','ثمانون','تسعون'];var h=['','مائة','مائتان','ثلاثمائة','أربعمائة','خمسمائة','ستمائة','سبعمائة','ثمانمائة','تسعمائة'];function sm(x){if(x<=0)return'';if(x<20)return o[x];var p=[];if(x>=100){p.push(h[Math.floor(x/100)]);x%=100}if(x>=20){p.push(t[Math.floor(x/10)]);if(x%10>0)p.push(o[x%10])}else if(x>0)p.push(o[x]);return p.join(' و')}var i=Math.floor(n),p=[];if(i>=1000000){var m=Math.floor(i/1000000);p.push(m===1?'مليون':m===2?'مليونان':sm(m)+' ملايين');i%=1000000}if(i>=1000){var k=Math.floor(i/1000);p.push(k===1?'ألف':k===2?'ألفان':sm(k)+' آلاف');i%=1000}if(i>0)p.push(sm(i));var txt=p.join(' و')+' دينار جزائري';var cents=Math.round((n-Math.floor(n))*100);if(cents>0)txt+=' و'+sm(cents)+' سنتيم';return txt}
function accCustSearch(q){clearTimeout(window._csT);window._csT=setTimeout(function(){if(q.length<2){jQuery('#cust-suggest').hide();return}jQuery.post(dza.ajax,{action:'dzqcod_acc_search_cust',nonce:dza.nonce,q:q},function(r){if(!r.success||!r.data.length){jQuery('#cust-suggest').hide();return}var h='';(r.data).forEach(function(c){h+='<div onclick="accFillCust('+JSON.stringify(c).replace(/"/g,'&quot;')+')" style="padding:8px 12px;cursor:pointer;border-bottom:1px solid #f0f0f0;font-size:12px" onmouseover="this.style.background=\'#f0f9ff\'" onmouseout="this.style.background=\'none\'"><strong>'+c.name+'</strong> <span style="color:#888">'+c.phone+'</span>'+(c.wilaya?' <span style="color:#6366F1">'+c.wilaya+'</span>':'')+'</div>'});jQuery('#cust-suggest').html(h).show()})},250)}
function accFillCust(c){jQuery('#inv-name').val(c.name||'');jQuery('#inv-phone').val(c.phone||'');jQuery('#inv-email').val(c.email||'');jQuery('#inv-wilaya').val(c.wilaya||'');jQuery('#inv-addr').val(c.address||'');jQuery('#inv-nif').val(c.nif||'');jQuery('#inv-nis').val(c.nis||'');jQuery('#inv-ai').val(c.ai||'');jQuery('#inv-rc').val(c.rc||'');jQuery('#cust-suggest').hide()}
function accCustForm(id){var h='<h3>'+(id?'✏️ تعديل زبون':'➕ زبون جديد')+'</h3><input type="hidden" id="cf-id" value="'+(id||0)+'">';
h+='<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">';
h+='<div><label style="font-weight:700;font-size:12px">الاسم *</label><input id="cf-name" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div><label style="font-weight:700;font-size:12px">الهاتف</label><input id="cf-phone" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div><label style="font-weight:700;font-size:12px">البريد</label><input id="cf-email" type="email" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div><label style="font-weight:700;font-size:12px">الولاية</label><input id="cf-wilaya" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div style="grid-column:span 2"><label style="font-weight:700;font-size:12px">العنوان</label><input id="cf-addr" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div><label style="font-weight:700;font-size:12px">NIF</label><input id="cf-nif" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div><label style="font-weight:700;font-size:12px">NIS</label><input id="cf-nis" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div><label style="font-weight:700;font-size:12px">AI</label><input id="cf-ai" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div><label style="font-weight:700;font-size:12px">RC</label><input id="cf-rc" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div>';
h+='<div style="grid-column:span 2"><label style="font-weight:700;font-size:12px">ملاحظات</label><textarea id="cf-notes" rows="2" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></textarea></div>';
h+='</div><div style="text-align:center;margin-top:16px"><button onclick="accSaveCust()" style="padding:10px 40px;background:#6366F1;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700">💾 حفظ الزبون</button></div>';
accM(h)}
function accSaveCust(){jQuery.post(dza.ajax,{action:'dzqcod_acc_save_cust',nonce:dza.nonce,cust_id:jQuery('#cf-id').val(),name:jQuery('#cf-name').val(),phone:jQuery('#cf-phone').val(),email:jQuery('#cf-email').val(),wilaya:jQuery('#cf-wilaya').val(),address:jQuery('#cf-addr').val(),nif:jQuery('#cf-nif').val(),nis:jQuery('#cf-nis').val(),ai_field:jQuery('#cf-ai').val(),rc:jQuery('#cf-rc').val(),notes:jQuery('#cf-notes').val()},function(r){if(r.success){jQuery('#acc-modal').hide();location.reload()}else alert('خطأ')})}
function accSaveInv(){var sub=parseFloat(jQuery('#inv-sub').val())||0,tvr=parseFloat(jQuery('#inv-tvr').val())||0;
var d={action:'dzqcod_acc_save_inv',nonce:dza.nonce,invoice_id:jQuery('#inv-id').val(),inv_type:jQuery('#inv-type').val(),status:jQuery('#inv-st').val(),
    cust_name:jQuery('#inv-name').val(),cust_phone:jQuery('#inv-phone').val(),cust_email:jQuery('#inv-email').val(),cust_wilaya:jQuery('#inv-wilaya').val(),cust_address:jQuery('#inv-addr').val(),cust_nif:jQuery('#inv-nif').val(),cust_nis:jQuery('#inv-nis').val(),cust_ai:jQuery('#inv-ai').val(),cust_rc:jQuery('#inv-rc').val(),
    subtotal:sub.toFixed(2),tax_tva:(sub*tvr/100).toFixed(2),tva_rate:tvr,total:jQuery('#inv-tot').val(),notes:jQuery('#inv-notes').val(),
    item_desc:[],item_unit:[],item_qty:[],item_price:[],item_tva:[]};
jQuery('.ii').each(function(){d.item_desc.push(jQuery(this).find('.ii-d').val());d.item_unit.push(jQuery(this).find('.ii-u').val());d.item_qty.push(jQuery(this).find('.ii-q').val());d.item_price.push(jQuery(this).find('.ii-p').val());d.item_tva.push(jQuery(this).find('.ii-t').val())});
jQuery.post(dza.ajax,d,function(r){if(r.success){jQuery('#acc-modal').hide();location.reload()}else alert(r.data&&r.data.message?r.data.message:'خطأ')})}
function accInvDel(id){if(!confirm('حذف؟'))return;jQuery.post(dza.ajax,{action:'dzqcod_acc_del_inv',nonce:dza.nonce,invoice_id:id},function(){location.reload()})}
function accDup(id){jQuery.post(dza.ajax,{action:'dzqcod_acc_dup_inv',nonce:dza.nonce,invoice_id:id},function(){location.reload()})}
function accInvSt(id,st){jQuery.post(dza.ajax,{action:'dzqcod_acc_inv_status',nonce:dza.nonce,invoice_id:id,status:st},function(){location.reload()})}
function accSync(){jQuery.post(dza.ajax,{action:'dzqcod_acc_sync',nonce:dza.nonce},function(r){alert(r.success?'✅ مزامنة '+r.data.synced+' طلب':'خطأ');if(r.data&&r.data.synced>0)location.reload()})}
function accExpForm(){var cO='';for(var k in accCats)cO+='<option value="'+k+'">'+accCats[k].l+'</option>';var h='<h3>➕ مصروف جديد</h3><div style="display:grid;grid-template-columns:1fr 1fr;gap:12px"><div><label style="font-weight:700;font-size:12px">الفئة</label><select id="exp-cat" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px">'+cO+'</select></div><div><label style="font-weight:700;font-size:12px">المبلغ</label><input type="number" id="exp-amt" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div><div style="grid-column:span 2"><label style="font-weight:700;font-size:12px">الوصف</label><input id="exp-desc" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div><div><label style="font-weight:700;font-size:12px">المورد</label><input id="exp-sup" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div><div><label style="font-weight:700;font-size:12px">التاريخ</label><input type="date" id="exp-dt" value="'+new Date().toISOString().slice(0,10)+'" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div><div><label style="font-weight:700;font-size:12px">TVA %</label><input type="number" id="exp-tva" value="0" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div><div><label style="font-weight:700;font-size:12px">الدفع</label><select id="exp-pay" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"><option value="cash">كاش</option><option value="bank">بنك</option><option value="cib">CIB</option></select></div></div><div style="text-align:center;margin-top:16px"><button onclick="accSaveExp()" style="padding:10px 40px;background:#F59E0B;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700">💾 حفظ</button></div>';accM(h)}
function accSaveExp(){jQuery.post(dza.ajax,{action:'dzqcod_acc_save_exp',nonce:dza.nonce,category:jQuery('#exp-cat').val(),amount:jQuery('#exp-amt').val(),description:jQuery('#exp-desc').val(),supplier:jQuery('#exp-sup').val(),expense_date:jQuery('#exp-dt').val(),tva_rate:jQuery('#exp-tva').val(),pay_method:jQuery('#exp-pay').val()},function(r){if(r.success){jQuery('#acc-modal').hide();location.reload()}else alert('خطأ')})}
function accExpDel(id){if(!confirm('حذف؟'))return;jQuery.post(dza.ajax,{action:'dzqcod_acc_del_exp',nonce:dza.nonce,expense_id:id},function(){location.reload()})}
function accJrnForm(){var aO='';for(var k in accCOA)aO+='<option value="'+k+'">'+k+' — '+accCOA[k]+'</option>';var h='<h3>➕ قيد محاسبي</h3><div style="display:grid;grid-template-columns:1fr 1fr;gap:12px"><div><label style="font-weight:700;font-size:12px">المرجع</label><input id="jrn-ref" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div><div><label style="font-weight:700;font-size:12px">المبلغ</label><input type="number" id="jrn-amt" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div><div style="grid-column:span 2"><label style="font-weight:700;font-size:12px">البيان</label><input id="jrn-desc" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px"></div><div><label style="font-weight:700;font-size:12px">حساب مدين</label><select id="jrn-dr" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px">'+aO+'</select></div><div><label style="font-weight:700;font-size:12px">حساب دائن</label><select id="jrn-cr" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px">'+aO+'</select></div></div><div style="text-align:center;margin-top:16px"><button onclick="accSaveJrn()" style="padding:10px 40px;background:#3B82F6;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700">💾 حفظ</button></div>';accM(h)}
function accSaveJrn(){jQuery.post(dza.ajax,{action:'dzqcod_acc_jrn_add',nonce:dza.nonce,reference:jQuery('#jrn-ref').val(),description:jQuery('#jrn-desc').val(),debit_acc:jQuery('#jrn-dr').val(),credit_acc:jQuery('#jrn-cr').val(),amount:jQuery('#jrn-amt').val()},function(r){if(r.success){jQuery('#acc-modal').hide();location.reload()}})}
function accJrnDel(id){if(!confirm('حذف؟'))return;jQuery.post(dza.ajax,{action:'dzqcod_acc_jrn_del',nonce:dza.nonce,entry_id:id},function(){location.reload()})}
function accG50(){jQuery.post(dza.ajax,{action:'dzqcod_acc_g50',nonce:dza.nonce,month:jQuery('#g50-m').val(),year:jQuery('#g50-y').val()},function(r){if(!r.success)return;var d=r.data;jQuery('#g50-res').html('<div style="background:#fff;border-radius:12px;padding:20px;box-shadow:0 2px 8px rgba(0,0,0,.06)"><h4 style="margin:0 0 12px">🏛️ G50 — '+d.m+'/'+d.y+'</h4><div style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px">'+'<div style="padding:12px;background:#f0fdf4;border-radius:8px;text-align:center"><div style="font-size:11px;color:#888">الإيرادات</div><div style="font-size:20px;font-weight:800;color:#10B981">'+Number(d.rev).toLocaleString()+'</div></div>'+'<div style="padding:12px;background:#eff6ff;border-radius:8px;text-align:center"><div style="font-size:11px;color:#888">TVA محصّلة</div><div style="font-size:20px;font-weight:800;color:#3B82F6">'+Number(d.tva_c).toLocaleString()+'</div></div>'+'<div style="padding:12px;background:#fef3c7;border-radius:8px;text-align:center"><div style="font-size:11px;color:#888">TVA مسترجعة</div><div style="font-size:20px;font-weight:800;color:#F59E0B">'+Number(d.tva_d).toLocaleString()+'</div></div>'+'<div style="padding:12px;background:#fef2f2;border-radius:8px;text-align:center"><div style="font-size:11px;color:#888">TVA واجبة</div><div style="font-size:20px;font-weight:800;color:#EF4444">'+Number(d.tva_due).toLocaleString()+'</div></div>'+'<div style="padding:12px;background:#f5f3ff;border-radius:8px;text-align:center"><div style="font-size:11px;color:#888">TAP</div><div style="font-size:20px;font-weight:800;color:#8B5CF6">'+Number(d.tap).toLocaleString()+'</div></div>'+'<div style="padding:12px;background:#fff7ed;border-radius:8px;text-align:center"><div style="font-size:11px;color:#888">IRG</div><div style="font-size:20px;font-weight:800;color:#F97316">'+Number(d.irg).toLocaleString()+'</div></div>'+'</div><div style="margin-top:12px;padding:16px;background:linear-gradient(135deg,#EF4444,#DC2626);border-radius:8px;text-align:center;color:#fff"><div style="font-size:12px;opacity:.8">المبلغ الإجمالي المستحق</div><div style="font-size:28px;font-weight:900">'+Number(d.total).toLocaleString()+' '+cs+'</div></div></div>')})}
function accRpt(type){jQuery.post(dza.ajax,{action:'dzqcod_acc_report',nonce:dza.nonce,report_type:type,from:jQuery('#rpt-from').val(),to:jQuery('#rpt-to').val()},function(r){if(!r.success)return;var d=r.data,h='';
    if(d.type==='trial_balance'){h='<div style="background:#fff;border-radius:12px;padding:20px;box-shadow:0 2px 8px rgba(0,0,0,.06)"><h4>📊 ميزان المراجعة</h4><table style="width:100%;border-collapse:collapse;font-size:12px"><thead><tr style="background:#f8f9fa"><th style="padding:8px;text-align:right">الحساب</th><th style="padding:8px;text-align:right">البيان</th><th style="padding:8px;text-align:center">مدين</th><th style="padding:8px;text-align:center">دائن</th><th style="padding:8px;text-align:center">الرصيد</th></tr></thead><tbody>';var td=0,tc=0;for(var k in d.data){var a=d.data[k];td+=a.debit;tc+=a.credit;h+='<tr style="border-bottom:1px solid #f0f0f0"><td style="padding:6px;font-weight:700;color:#6366F1">'+k+'</td><td style="padding:6px">'+a.name+'</td><td style="padding:6px;text-align:center">'+Number(a.debit).toLocaleString()+'</td><td style="padding:6px;text-align:center">'+Number(a.credit).toLocaleString()+'</td><td style="padding:6px;text-align:center;font-weight:700;color:'+(a.balance>=0?'#10B981':'#EF4444')+'">'+Number(a.balance).toLocaleString()+'</td></tr>'}
    h+='<tr style="background:#f8f9fa;font-weight:800"><td colspan="2" style="padding:8px">المجموع</td><td style="padding:8px;text-align:center">'+Number(td).toLocaleString()+'</td><td style="padding:8px;text-align:center">'+Number(tc).toLocaleString()+'</td><td style="padding:8px;text-align:center;color:'+(Math.abs(td-tc)<1?'#10B981':'#EF4444')+'">'+Number(td-tc).toLocaleString()+'</td></tr></tbody></table></div>'}
    if(d.type==='pnl'){h='<div style="background:#fff;border-radius:12px;padding:20px;box-shadow:0 2px 8px rgba(0,0,0,.06)"><h4>📈 حساب الأرباح والخسائر</h4><div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;margin-bottom:16px"><div style="padding:16px;background:#f0fdf4;border-radius:8px;text-align:center"><div style="font-size:11px">الإيرادات</div><div style="font-size:24px;font-weight:800;color:#10B981">'+Number(d.revenue).toLocaleString()+'</div></div><div style="padding:16px;background:#fef2f2;border-radius:8px;text-align:center"><div style="font-size:11px">المصاريف</div><div style="font-size:24px;font-weight:800;color:#EF4444">'+Number(d.expenses).toLocaleString()+'</div></div><div style="padding:16px;background:'+(d.profit>=0?'#f0fdf4':'#fef2f2')+';border-radius:8px;text-align:center"><div style="font-size:11px">النتيجة</div><div style="font-size:24px;font-weight:800;color:'+(d.profit>=0?'#10B981':'#EF4444')+'">'+Number(d.profit).toLocaleString()+' '+cs+'</div></div></div></div>'}
    jQuery('#rpt-res').html(h)})}
function accExp(type){jQuery.post(dza.ajax,{action:'dzqcod_acc_export',nonce:dza.nonce,export_type:type,from:jQuery('#rpt-from').val(),to:jQuery('#rpt-to').val()},function(r){if(!r.success||!r.data.data.length){alert('لا توجد بيانات');return}var rows=r.data.data,cols=Object.keys(rows[0]),csv=cols.join(',')+'\n';rows.forEach(function(row){csv+=cols.map(function(c){return '"'+(row[c]||'')+'"'}).join(',')+'\n'});var blob=new Blob(['\uFEFF'+csv],{type:'text/csv;charset=utf-8'});var a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=type+'_'+new Date().toISOString().slice(0,10)+'.csv';a.click()})}
function accSaveSet(){var d={action:'dzqcod_acc_settings',nonce:dza.nonce};jQuery('.acc-set').each(function(){var k=jQuery(this).data('key');d[k]=this.type==='checkbox'?(this.checked?'yes':'no'):jQuery(this).val()});jQuery.post(dza.ajax,d,function(r){alert(r.success?'✅ تم الحفظ':'خطأ')})}
// ═══ PRINT INVOICE ═══
function accPrint(id){var inv=accInvs.find(function(i){return parseInt(i.id)===id});if(!inv)return;
var items=accItems[id]||[];var tp=accTypes[inv.inv_type]||inv.inv_type;var st=accSts[inv.status]||{l:inv.status};
var total=parseFloat(inv.total)||0;var w=window.open('','_blank','width=800,height=900');
w.document.write('<!DOCTYPE html><html dir="rtl"><head><meta charset="UTF-8"><title>'+inv.inv_num+'</title><style>*{margin:0;padding:0;box-sizing:border-box}body{font-family:Tajawal,Arial,sans-serif;padding:30px;color:#1a1a1a;font-size:13px}table{width:100%;border-collapse:collapse;margin:16px 0}th{background:#f1f5f9;padding:8px;text-align:right;font-weight:700;border:1px solid #ddd;font-size:12px}td{padding:7px 8px;border:1px solid #ddd;font-size:12px}.total-box{background:#f8fafc;padding:12px;border-radius:8px;margin-top:12px}.words{background:#eff6ff;padding:10px;border-radius:6px;margin-top:10px;font-size:12px;color:#1e40af}@media print{body{padding:15px}}</style></head><body>');
w.document.write('<div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:20px;padding-bottom:16px;border-bottom:3px solid #6366F1"><div><h2 style="color:#6366F1;margin-bottom:4px">'+accStore.name+'</h2>');
if(accStore.address)w.document.write('<div>'+accStore.address+'</div>');if(accStore.phone)w.document.write('<div>📞 '+accStore.phone+'</div>');if(accStore.nif)w.document.write('<div>NIF: '+accStore.nif+'</div>');if(accStore.rc)w.document.write('<div>RC: '+accStore.rc+'</div>');
w.document.write('</div><div style="text-align:left"><h1 style="color:#6366F1;font-size:22px">'+tp+'</h1><div style="font-size:18px;font-weight:800">'+inv.inv_num+'</div><div>التاريخ: '+inv.created_at.substring(0,10)+'</div><div>الحالة: '+st.l+'</div></div></div>');
w.document.write('<div style="background:#f8fafc;padding:12px;border-radius:8px;margin-bottom:16px"><strong>الزبون:</strong> <strong>'+inv.cust_name+'</strong>');
if(inv.cust_phone)w.document.write(' | 📞 '+inv.cust_phone);if(inv.cust_address)w.document.write('<br>العنوان: '+inv.cust_address);
if(inv.cust_nif)w.document.write('<br>NIF: '+inv.cust_nif);if(inv.cust_rc)w.document.write(' | RC: '+inv.cust_rc);w.document.write('</div>');
w.document.write('<table><thead><tr><th>#</th><th>البيان</th><th>الوحدة</th><th>الكمية</th><th>السعر الفردي</th><th>TVA%</th><th>المجموع</th></tr></thead><tbody>');
items.forEach(function(it,i){var desc=it.description||'';var unit='وحدة';var m=desc.match(/\[([^\]]+)\]$/);if(m){unit=m[1];desc=desc.replace(/\s*\[[^\]]+\]$/,'');}
w.document.write('<tr><td style="text-align:center">'+(i+1)+'</td><td>'+desc+'</td><td style="text-align:center">'+unit+'</td><td style="text-align:center">'+it.qty+'</td><td style="text-align:center">'+Number(parseFloat(it.unit_price)).toLocaleString()+' '+cs+'</td><td style="text-align:center">'+it.tva_rate+'%</td><td style="text-align:center;font-weight:700">'+Number(parseFloat(it.line_total)).toLocaleString()+' '+cs+'</td></tr>')});
w.document.write('</tbody></table>');
var sub=parseFloat(inv.subtotal)||0,tva=parseFloat(inv.tax_tva)||0;
w.document.write('<div class="total-box"><table style="width:300px;margin-right:auto;border:none"><tr><td style="border:none">المجموع HT</td><td style="border:none;text-align:left;font-weight:700">'+Number(sub).toLocaleString()+' '+cs+'</td></tr><tr><td style="border:none">TVA ('+inv.tva_rate+'%)</td><td style="border:none;text-align:left">'+Number(tva).toLocaleString()+' '+cs+'</td></tr>');
if(parseFloat(inv.tax_timbre)>0)w.document.write('<tr><td style="border:none">طابع جبائي</td><td style="border:none;text-align:left">'+Number(parseFloat(inv.tax_timbre)).toLocaleString()+' '+cs+'</td></tr>');
w.document.write('<tr style="font-size:18px;font-weight:900;color:#6366F1"><td style="border:none">الإجمالي TTC</td><td style="border:none;text-align:left">'+Number(total).toLocaleString()+' '+cs+'</td></tr></table></div>');
w.document.write('<div class="words"><strong>توقفت هذه الفاتورة عند مبلغ:</strong> '+accNumWords(total)+'</div>');
w.document.write('<div style="margin-top:30px;display:flex;justify-content:space-between"><div style="text-align:center;width:200px"><div style="border-top:1px solid #999;padding-top:4px;margin-top:60px">ختم وتوقيع المورد</div></div><div style="text-align:center;width:200px"><div style="border-top:1px solid #999;padding-top:4px;margin-top:60px">ختم وتوقيع الزبون</div></div></div>');
w.document.write('</body></html>');w.document.close();setTimeout(function(){w.print()},500)}
// ═══ DELIVERY NOTE (وصل تسليم) ═══
function accBL(id){var inv=accInvs.find(function(i){return parseInt(i.id)===id});if(!inv)return;
var items=accItems[id]||[];var blNum='BL-'+inv.inv_num.split('-').slice(1).join('-');
var w=window.open('','_blank','width=800,height=700');
w.document.write('<!DOCTYPE html><html dir="rtl"><head><meta charset="UTF-8"><title>وصل تسليم '+blNum+'</title><style>*{margin:0;padding:0;box-sizing:border-box}body{font-family:Tajawal,Arial,sans-serif;padding:30px;color:#1a1a1a;font-size:13px}table{width:100%;border-collapse:collapse;margin:16px 0}th{background:#f1f5f9;padding:8px;text-align:right;font-weight:700;border:1px solid #ddd;font-size:12px}td{padding:7px 8px;border:1px solid #ddd;font-size:12px}@media print{body{padding:15px}}</style></head><body>');
w.document.write('<div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:20px;padding-bottom:16px;border-bottom:3px solid #10B981"><div><h2 style="color:#10B981;margin-bottom:4px">'+accStore.name+'</h2>');
if(accStore.address)w.document.write('<div>'+accStore.address+'</div>');if(accStore.phone)w.document.write('<div>📞 '+accStore.phone+'</div>');if(accStore.nif)w.document.write('<div>NIF: '+accStore.nif+'</div>');
w.document.write('</div><div style="text-align:left"><h1 style="color:#10B981;font-size:22px">وصل تسليم</h1><div style="font-size:18px;font-weight:800">'+blNum+'</div><div>التاريخ: <span style="border-bottom:1px dotted #999;padding:0 60px">&nbsp;</span></div></div></div>');
w.document.write('<div style="background:#f0fdf4;padding:12px;border-radius:8px;margin-bottom:16px"><strong>المستلم:</strong> <strong>'+inv.cust_name+'</strong>');
if(inv.cust_phone)w.document.write(' | 📞 '+inv.cust_phone);if(inv.cust_address)w.document.write('<br>العنوان: '+inv.cust_address);w.document.write('</div>');
w.document.write('<table><thead><tr><th style="width:40px">#</th><th>المنتج</th><th style="width:100px;text-align:center">الوحدة</th><th style="width:80px;text-align:center">الكمية</th></tr></thead><tbody>');
items.forEach(function(it,i){var desc=it.description||'';var unit='وحدة';var m=desc.match(/\[([^\]]+)\]$/);if(m){unit=m[1];desc=desc.replace(/\s*\[[^\]]+\]$/,'');}
w.document.write('<tr><td style="text-align:center">'+(i+1)+'</td><td>'+desc+'</td><td style="text-align:center">'+unit+'</td><td style="text-align:center;font-weight:700">'+it.qty+'</td></tr>')});
w.document.write('</tbody></table>');
w.document.write('<div style="margin-top:40px;display:flex;justify-content:space-between"><div style="text-align:center;width:220px"><div style="border-top:1px solid #999;padding-top:4px;margin-top:60px">توقيع وختم المورد</div></div><div style="text-align:center;width:220px"><div style="border-top:1px solid #999;padding-top:4px;margin-top:60px">توقيع المستلم</div><div style="font-size:11px;color:#888;margin-top:4px">أستلمت البضاعة بحالة جيدة</div></div></div>');
w.document.write('</body></html>');w.document.close();setTimeout(function(){w.print()},500)}
</script>
</div>
        <?php
    }
}
AccountingPro::init();
