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

class CustomerAccount {
    public function __construct() {
        add_shortcode('dzqcod_account', [$this, 'render_account']);
        add_shortcode('dzqcod_tracking', [$this, 'render_tracking']);
        add_action('dzqcod_order_created', [$this, 'auto_create_account'], 20, 2);
        add_action('wp_ajax_nopriv_dzqcod_phone_lookup', [$this, 'phone_lookup']);
        add_action('wp_ajax_dzqcod_phone_lookup', [$this, 'phone_lookup']);
        foreach (['dzqcod_customer_login','dzqcod_customer_register','dzqcod_customer_orders','dzqcod_customer_track','dzqcod_customer_profile_save','dzqcod_customer_reorder'] as $a) {
            add_action('wp_ajax_'.$a, [$this, str_replace('dzqcod_','',$a)]);
            add_action('wp_ajax_nopriv_'.$a, [$this, str_replace('dzqcod_','',$a)]);
        }
        add_action('init', [$this, 'maybe_create_page']);
        add_filter('woocommerce_account_menu_items', [$this, 'add_menu_items']);
        add_action('woocommerce_account_dzqcod-dashboard_endpoint', [$this, 'endpoint_content']);
        add_action('init', function(){ add_rewrite_endpoint('dzqcod-dashboard', EP_ROOT | EP_PAGES); });
        // Enqueue CSS/JS on front-end pages that use the shortcode
        add_action('wp_enqueue_scripts', [$this, 'enqueue_assets']);
    }

    public function enqueue_assets(): void {
        // Only enqueue on pages that have the shortcode or WC account page
        global $post;
        $dominated = is_account_page() || (is_a($post,'WP_Post') && (has_shortcode($post->post_content,'dzqcod_account') || has_shortcode($post->post_content,'dzqcod_tracking')));
        if (!$dominated) return;
        wp_register_style('dzqcod-account','',[],'3.1.0');
        wp_enqueue_style('dzqcod-account');
        wp_add_inline_style('dzqcod-account', self::get_css());
    }

    private static function get_css(): string {
        return '#dz-acc{max-width:960px;margin:0 auto;font-family:"Segoe UI",Tahoma,sans-serif;color:#1e293b;-webkit-font-smoothing:antialiased}#dz-acc *{box-sizing:border-box}.da-card{background:#fff;border-radius:20px;padding:24px;margin-bottom:16px;box-shadow:0 4px 24px rgba(0,0,0,.06);border:1px solid rgba(0,0,0,.04);transition:all .3s}.da-card:hover{box-shadow:0 8px 32px rgba(0,0,0,.1)}.da-hero{background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);border-radius:24px;padding:32px;color:#fff;margin-bottom:20px;position:relative;overflow:hidden}.da-hero::before{content:"";position:absolute;top:-50%;right:-30%;width:300px;height:300px;background:rgba(255,255,255,.08);border-radius:50%}.da-avatar{width:68px;height:68px;border-radius:50%;background:rgba(255,255,255,.2);backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;font-size:28px;font-weight:900;border:3px solid rgba(255,255,255,.3)}.da-tabs{display:flex;background:#f1f5f9;border-radius:14px;padding:4px;margin-bottom:20px;overflow-x:auto;gap:2px}.da-tab{flex:1;padding:12px 8px;text-align:center;border-radius:10px;font-size:12px;font-weight:700;color:#64748b;cursor:pointer;transition:.3s;white-space:nowrap}.da-tab.active{background:#fff;color:#667eea;box-shadow:0 2px 8px rgba(0,0,0,.08)}.da-tab:hover:not(.active){color:#667eea;background:rgba(255,255,255,.5)}.da-sec{display:none;animation:daFade .4s}.da-sec.active{display:block}@keyframes daFade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}.da-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px}.da-stat{background:linear-gradient(135deg,#f8fafc,#eef2ff);border-radius:16px;padding:16px;text-align:center;border:1px solid #e2e8f0;transition:.3s}.da-stat:hover{transform:translateY(-3px);box-shadow:0 6px 20px rgba(102,126,234,.12)}.da-stat .v{font-size:28px;font-weight:900;background:linear-gradient(135deg,#667eea,#764ba2);-webkit-background-clip:text;-webkit-text-fill-color:transparent;display:block}.da-stat .l{font-size:11px;color:#94a3b8;margin-top:2px}.da-order{border:1px solid #e2e8f0;border-radius:16px;padding:16px;margin-bottom:12px;transition:.3s;cursor:pointer;background:#fff}.da-order:hover{border-color:#667eea;box-shadow:0 4px 16px rgba(102,126,234,.12);transform:translateY(-2px)}.da-btn{padding:12px 24px;border:none;border-radius:12px;font-size:14px;font-weight:700;cursor:pointer;transition:all .3s;font-family:inherit}.da-btn:active{transform:scale(.97)}.da-btn-p{background:linear-gradient(135deg,#667eea,#764ba2);color:#fff;box-shadow:0 4px 16px rgba(102,126,234,.3)}.da-btn-p:hover{box-shadow:0 6px 24px rgba(102,126,234,.4);transform:translateY(-2px)}.da-btn-g{background:#f1f5f9;color:#475569}.da-btn-g:hover{background:#e2e8f0}.da-btn-s{background:linear-gradient(135deg,#10b981,#059669);color:#fff}.da-input{width:100%;padding:14px 16px;border:2px solid #e2e8f0;border-radius:12px;font-size:14px;transition:.3s;background:#fafbfc;font-family:inherit}.da-input:focus{border-color:#667eea;outline:none;background:#fff;box-shadow:0 0 0 4px rgba(102,126,234,.1)}.da-label{display:block;font-size:12px;font-weight:700;color:#374151;margin-bottom:6px}.da-msg{margin-top:10px;padding:10px 14px;border-radius:10px;font-size:13px;font-weight:600;text-align:center;display:none}.da-msg.ok{display:block;background:#f0fdf4;color:#166534;border:1px solid #86efac}.da-msg.err{display:block;background:#fef2f2;color:#991b1b;border:1px solid #fca5a5}.da-msg.load{display:block;background:#eff6ff;color:#1e40af;border:1px solid #bfdbfe}.da-timeline{position:relative;padding-right:24px}.da-timeline::before{content:"";position:absolute;right:8px;top:0;bottom:0;width:3px;background:linear-gradient(180deg,#667eea,#e2e8f0);border-radius:2px}.da-tl-item{position:relative;padding:8px 0;padding-right:20px;margin-bottom:4px}.da-tl-item::before{content:"";position:absolute;right:-20px;top:12px;width:12px;height:12px;border-radius:50%;background:#667eea;border:3px solid #fff;box-shadow:0 0 0 2px #667eea}.da-tl-item.latest::before{background:#10b981;box-shadow:0 0 0 2px #10b981}.da-empty{text-align:center;padding:48px 20px;color:#94a3b8}.da-empty .icon{font-size:56px;margin-bottom:12px;display:block}@media(max-width:640px){.da-stats{grid-template-columns:repeat(2,1fr)}.da-hero{padding:20px}.da-avatar{width:52px;height:52px;font-size:22px}}';
    }

    public function auto_create_account(int $oid, $order): void {
        if(!$order)return;$phone=$order->get_billing_phone();$email=$order->get_billing_email();$name=trim($order->get_billing_first_name().' '.$order->get_billing_last_name());
        if(!$phone)return;
        $existing=get_users(['meta_key'=>'billing_phone','meta_value'=>$phone,'number'=>1]);
        if(!empty($existing)){$order->set_customer_id($existing[0]->ID);$order->save();return;}
        if($email&&strpos($email,'@dzqcod')===false){$by_email=get_user_by('email',$email);if($by_email){update_user_meta($by_email->ID,'billing_phone',$phone);$order->set_customer_id($by_email->ID);$order->save();return;}}
        if(!$email)$email=$phone.'@dzqcod.local';$pass=wp_generate_password(8,false);$uid=wp_create_user($phone,$pass,$email);if(is_wp_error($uid))return;
        wp_update_user(['ID'=>$uid,'display_name'=>$name,'first_name'=>$order->get_billing_first_name(),'last_name'=>$order->get_billing_last_name()]);
        update_user_meta($uid,'billing_phone',$phone);update_user_meta($uid,'billing_first_name',$order->get_billing_first_name());
        update_user_meta($uid,'billing_state',$order->get_shipping_state()?:$order->get_billing_state());
        update_user_meta($uid,'billing_city',$order->get_shipping_city()?:$order->get_billing_city());
        update_user_meta($uid,'billing_address_1',$order->get_shipping_address_1()?:$order->get_billing_address_1());
        $wc=new \WC_Customer($uid);$wc->set_role('customer');$wc->save();$order->set_customer_id($uid);$order->save();
    }

    public function phone_lookup(): void {
        // Security: require order form nonce
        if (!check_ajax_referer('dzqcod_order', '_n', false)) wp_send_json_error();
        $phone = sanitize_text_field($_POST['phone'] ?? '');
        if (!$phone || strlen($phone) < 9) wp_send_json_error();
        // Rate limit: max 10 lookups per IP per hour
        $ip = sanitize_text_field($_SERVER['REMOTE_ADDR'] ?? '');
        $rate_key = 'dzqcod_lookup_' . md5($ip);
        $count = (int) get_transient($rate_key);
        if ($count >= 10) wp_send_json_error(['message' => 'تجاوزت الحد المسموح']);
        set_transient($rate_key, $count + 1, HOUR_IN_SECONDS);
        $users = get_users(['meta_key' => 'billing_phone', 'meta_value' => $phone, 'number' => 1]);
        if (empty($users)) wp_send_json_error();
        $u = $users[0];
        // Return ONLY name and wilaya (no address, no commune — privacy)
        wp_send_json_success([
            'name'   => $u->display_name,
            'wilaya' => get_user_meta($u->ID, 'billing_state', true),
        ]);
    }

    public function maybe_create_page(): void {
        if(get_option('dzqcod_account_page_id'))return;
        $pid=wp_insert_post(['post_title'=>'حسابي','post_content'=>'[dzqcod_account]','post_status'=>'publish','post_type'=>'page']);
        if($pid&&!is_wp_error($pid))update_option('dzqcod_account_page_id',$pid);
    }
    public function add_menu_items($items){$items['dzqcod-dashboard']='لوحة DZQCOD';return $items;}
    public function endpoint_content(){echo do_shortcode('[dzqcod_account]');} // phpcs:ignore -- shortcode output contains safe inline CSS/JS

    public function render_account($atts=[]): string {
        $sym=Core::opt('currency_symbol','دج');$store=get_bloginfo('name');$user=wp_get_current_user();$logged_in=is_user_logged_in();
        $phone=$logged_in?get_user_meta($user->ID,'billing_phone',true):'';$name=$logged_in?$user->display_name:'';
        $nonce=wp_create_nonce('dzqcod_public');$ajax=admin_url('admin-ajax.php');$shop_url=get_permalink(wc_get_page_id('shop'));
        ob_start();
        ?>
<div id="dz-acc" dir="rtl">

<?php if(!$logged_in): ?>
<div class="da-card" style="max-width:440px;margin:0 auto">
<div style="text-align:center;margin-bottom:28px"><div style="width:80px;height:80px;margin:0 auto 12px;border-radius:50%;background:linear-gradient(135deg,#667eea,#764ba2);display:flex;align-items:center;justify-content:center;font-size:36px;box-shadow:0 8px 24px rgba(102,126,234,.3)">👤</div>
<h2 style="font-size:22px;font-weight:900;margin:8px 0 0"><?php echo esc_html($store);?></h2><p style="color:#94a3b8;font-size:13px;margin-top:4px">سجّل الدخول لمتابعة طلباتك</p></div>
<div style="display:flex;background:#f1f5f9;border-radius:12px;padding:4px;margin-bottom:24px"><div class="da-auth-t active" onclick="daAT('login',this)" style="flex:1;padding:12px;text-align:center;border-radius:8px;font-size:13px;font-weight:700;color:#667eea;cursor:pointer;background:#fff;box-shadow:0 2px 8px rgba(0,0,0,.08);transition:.3s">تسجيل الدخول</div><div class="da-auth-t" onclick="daAT('register',this)" style="flex:1;padding:12px;text-align:center;border-radius:8px;font-size:13px;font-weight:700;color:#64748b;cursor:pointer;transition:.3s">حساب جديد</div></div>
<div id="da-login"><div style="margin-bottom:14px"><label class="da-label">📱 رقم الهاتف</label><input type="tel" class="da-input" id="da-l-phone" placeholder="0555 12 34 56" dir="ltr"></div><div style="margin-bottom:14px"><label class="da-label">🔒 كلمة المرور</label><input type="password" class="da-input" id="da-l-pass" placeholder="أدخل كلمة المرور"></div><button class="da-btn da-btn-p" style="width:100%" onclick="daLogin()">تسجيل الدخول</button><div id="da-l-msg" class="da-msg"></div></div>
<div id="da-register" style="display:none"><div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:14px"><div><label class="da-label">👤 الاسم</label><input type="text" class="da-input" id="da-r-name" placeholder="محمد أحمد"></div><div><label class="da-label">📱 الهاتف</label><input type="tel" class="da-input" id="da-r-phone" placeholder="0555123456" dir="ltr"></div></div><div style="margin-bottom:14px"><label class="da-label">📧 البريد (اختياري)</label><input type="email" class="da-input" id="da-r-email" placeholder="email@example.com" dir="ltr"></div><div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:14px"><div><label class="da-label">📍 الولاية</label><input type="text" class="da-input" id="da-r-wilaya" placeholder="الجزائر العاصمة"></div><div><label class="da-label">🏘️ البلدية</label><input type="text" class="da-input" id="da-r-commune" placeholder="باب الزوار"></div></div><div style="margin-bottom:14px"><label class="da-label">🔒 كلمة المرور (6+)</label><input type="password" class="da-input" id="da-r-pass" placeholder="كلمة مرور قوية"></div><button class="da-btn da-btn-s" style="width:100%" onclick="daReg()">إنشاء حساب</button><div id="da-r-msg" class="da-msg"></div></div>
</div>
<?php else:
$orders=wc_get_orders(['customer_id'=>$user->ID,'limit'=>30,'orderby'=>'date','order'=>'DESC']);$total_spent=0;$total_orders=count($orders);$delivered=0;$pending=0;
foreach($orders as $o){$total_spent+=(float)$o->get_total();$st=$o->get_status();if(in_array($st,['delivered','wc-delivered']))$delivered++;if(in_array($st,['pending-call','wc-pending-call','processing','wc-processing','confirmed','wc-confirmed']))$pending++;}
?>
<div class="da-hero"><div style="display:flex;align-items:center;gap:16px;position:relative;z-index:1"><div class="da-avatar"><?php echo esc_html(mb_substr($name,0,1));?></div><div style="flex:1"><div style="font-size:22px;font-weight:900"><?php echo esc_html($name);?></div><div style="opacity:.8;font-size:13px;margin-top:2px"><?php echo esc_html($phone);?><?php if($user->user_email&&strpos($user->user_email,'@dzqcod')===false):?> • <?php echo esc_html($user->user_email);?><?php endif;?></div></div><a href="<?php echo esc_url(wp_logout_url(home_url()));?>" style="background:rgba(255,255,255,.15);backdrop-filter:blur(8px);color:#fff;text-decoration:none;padding:8px 16px;border-radius:10px;font-size:12px;font-weight:700">خروج</a></div></div>
<div class="da-stats"><div class="da-stat"><span class="v"><?php echo $total_orders;?></span><span class="l">الطلبات</span></div><div class="da-stat"><span class="v"><?php echo number_format($total_spent,0);?></span><span class="l"><?php echo esc_html($sym);?></span></div><div class="da-stat"><span class="v"><?php echo $delivered;?></span><span class="l">تم التسليم</span></div><div class="da-stat"><span class="v"><?php echo $pending;?></span><span class="l">قيد المعالجة</span></div></div>
<div class="da-tabs"><div class="da-tab active" onclick="daTab('orders',this)">📦 طلباتي</div><div class="da-tab" onclick="daTab('tracking',this)">📍 تتبع</div><div class="da-tab" onclick="daTab('downloads',this)">💾 تحميلات</div><div class="da-tab" onclick="daTab('profile',this)">👤 ملفي</div><div class="da-tab" onclick="daTab('addresses',this)">📍 عناوين</div></div>

<div class="da-sec active" id="da-s-orders">
<?php if(empty($orders)):?><div class="da-card da-empty"><span class="icon">📦</span><p style="font-size:16px;font-weight:700;margin:0 0 8px">لا توجد طلبات بعد</p><p style="margin:0 0 16px">ابدأ التسوق الآن</p><a href="<?php echo esc_url($shop_url);?>" class="da-btn da-btn-p" style="text-decoration:none;display:inline-block">🛒 تسوّق الآن</a></div>
<?php else:foreach($orders as $o):$ost=str_replace('wc-','',$o->get_status());$ws=Core::ST[$ost]??['l'=>$ost,'c'=>'#64748b','i'=>'📋'];$items=[];foreach($o->get_items() as $it)$items[]=$it->get_name().' ×'.$it->get_quantity();$tk=$o->get_meta('_dzqcod_tracking_number');?>
<div class="da-order" onclick="var d=this.querySelector('.det');d.style.display=d.style.display==='none'?'block':'none'">
<div style="display:flex;justify-content:space-between;align-items:center"><div><span style="font-weight:900;font-size:16px">#<?php echo (int)$o->get_id();?></span><span style="font-size:11px;color:#94a3b8;margin-right:8px"><?php echo $o->get_date_created()?$o->get_date_created()->format('d/m/Y'):'-';?></span></div><span style="background:<?php echo esc_attr($ws['c']);?>;color:#fff;padding:4px 14px;border-radius:10px;font-size:11px;font-weight:700"><?php echo esc_html($ws['i'].' '.$ws['l']);?></span></div>
<div style="font-size:12px;color:#64748b;margin-top:8px"><?php echo esc_html(implode(' | ',$items));?></div>
<div style="display:flex;justify-content:space-between;align-items:center;margin-top:10px"><span style="font-size:20px;font-weight:900;color:#059669"><?php echo number_format((float)$o->get_total(),0);?> <?php echo esc_html($sym);?></span><?php if($tk):?><span style="font-size:11px;background:#f1f5f9;padding:4px 10px;border-radius:8px;font-family:monospace;color:#667eea;font-weight:700"><?php echo esc_html($tk);?></span><?php endif;?></div>
<div class="det" style="display:none;margin-top:14px;padding-top:14px;border-top:2px solid #f1f5f9">
<table style="width:100%;font-size:12px;border-collapse:collapse"><thead><tr style="background:#f8fafc"><th style="padding:8px;text-align:right;font-weight:700">المنتج</th><th style="text-align:center;padding:8px">الكمية</th><th style="padding:8px">المبلغ</th></tr></thead><tbody><?php foreach($o->get_items() as $it):?><tr style="border-bottom:1px solid #f0f0f0"><td style="padding:8px"><?php echo esc_html($it->get_name());?></td><td style="text-align:center;padding:8px"><?php echo $it->get_quantity();?></td><td style="padding:8px;font-weight:700"><?php echo number_format((float)$it->get_total(),0);?> <?php echo esc_html($sym);?></td></tr><?php endforeach;?></tbody></table>
<div style="display:flex;gap:8px;margin-top:10px"><?php if($tk):?><button class="da-btn da-btn-p" style="flex:1;font-size:12px;padding:10px" onclick="event.stopPropagation();daTrk('<?php echo esc_attr(esc_js($tk));?>',this)">📍 تتبع</button><?php endif;?><button class="da-btn da-btn-g" style="flex:1;font-size:12px;padding:10px" onclick="event.stopPropagation();daRO(<?php echo (int)$o->get_id();?>,this)">🔄 إعادة الطلب</button></div>
<div class="da-trk-r" style="margin-top:8px"></div></div></div>
<?php endforeach;endif;?></div>

<div class="da-sec" id="da-s-tracking"><div class="da-card"><h3 style="font-size:18px;font-weight:900;margin:0 0 14px">📍 تتبع شحنتك</h3><p style="font-size:13px;color:#94a3b8;margin:0 0 14px">أدخل رقم التتبع لمعرفة موقع طلبك</p><div style="display:flex;gap:8px"><input type="text" class="da-input" id="da-trk-num" placeholder="رقم التتبع" dir="ltr" style="flex:1"><button class="da-btn da-btn-p" onclick="daTrkM()">تتبع</button></div><div id="da-trk-main" style="margin-top:16px"></div></div></div>

<div class="da-sec" id="da-s-downloads"><div class="da-card"><h3 style="font-size:18px;font-weight:900;margin:0 0 14px">💾 ملفاتي</h3><?php $dls=wc_get_customer_available_downloads($user->ID);if(empty($dls)):?><div class="da-empty" style="padding:24px"><span class="icon">📄</span><p style="margin:0">لا توجد ملفات</p></div><?php else:foreach($dls as $dl):?><div style="display:flex;align-items:center;gap:12px;padding:12px;border:1px solid #e2e8f0;border-radius:12px;margin-bottom:8px"><span style="font-size:28px">📄</span><div style="flex:1"><div style="font-weight:700;font-size:13px"><?php echo esc_html($dl['product_name']);?></div><div style="font-size:11px;color:#94a3b8"><?php echo $dl['downloads_remaining']===''?'∞':esc_html($dl['downloads_remaining']);?> متبقية</div></div><a href="<?php echo esc_url($dl['download_url']);?>" class="da-btn da-btn-s" style="font-size:12px;padding:8px 16px;text-decoration:none">⬇️ تحميل</a></div><?php endforeach;endif;?></div></div>

<div class="da-sec" id="da-s-profile"><div class="da-card"><h3 style="font-size:18px;font-weight:900;margin:0 0 14px">👤 الملف الشخصي</h3><div style="display:grid;grid-template-columns:1fr 1fr;gap:14px"><div><label class="da-label">الاسم</label><input type="text" class="da-input da-pf" data-key="display_name" value="<?php echo esc_attr($name);?>"></div><div><label class="da-label">البريد</label><input type="email" class="da-input da-pf" data-key="email" value="<?php echo esc_attr($user->user_email);?>" dir="ltr"></div><div><label class="da-label">الهاتف</label><input type="tel" class="da-input da-pf" data-key="phone" value="<?php echo esc_attr($phone);?>" dir="ltr"></div><div><label class="da-label">هاتف 2</label><input type="tel" class="da-input da-pf" data-key="phone2" value="<?php echo esc_attr(get_user_meta($user->ID,'billing_phone_2',true));?>" dir="ltr"></div></div><div style="margin-top:14px"><label class="da-label">🔒 كلمة مرور جديدة</label><input type="password" class="da-input da-pf" data-key="password" placeholder="اتركها فارغة للإبقاء"></div><button class="da-btn da-btn-p" style="width:100%;margin-top:14px" onclick="daSP()">💾 حفظ</button><div id="da-pf-msg" class="da-msg"></div></div></div>

<div class="da-sec" id="da-s-addresses"><div class="da-card"><h3 style="font-size:18px;font-weight:900;margin:0 0 14px">📍 عنوان التوصيل</h3><div style="display:grid;grid-template-columns:1fr 1fr;gap:14px"><div><label class="da-label">الولاية</label><input type="text" class="da-input da-pf" data-key="billing_state" value="<?php echo esc_attr(get_user_meta($user->ID,'billing_state',true));?>"></div><div><label class="da-label">البلدية</label><input type="text" class="da-input da-pf" data-key="billing_city" value="<?php echo esc_attr(get_user_meta($user->ID,'billing_city',true));?>"></div></div><div style="margin-top:14px"><label class="da-label">العنوان التفصيلي</label><input type="text" class="da-input da-pf" data-key="billing_address_1" value="<?php echo esc_attr(get_user_meta($user->ID,'billing_address_1',true));?>"></div><button class="da-btn da-btn-p" style="width:100%;margin-top:14px" onclick="daSP()">💾 حفظ</button></div></div>
<?php endif;?>
</div>
<script>
var daA='<?php echo esc_url($ajax);?>',daN='<?php echo esc_attr($nonce);?>';
function daFD(d){var fd=new FormData();for(var k in d)fd.append(k,d[k]);fd.append('nonce',daN);return fd}
function daMsg(id,t,m){var e=document.getElementById(id);if(!e)return;e.className='da-msg '+t;e.textContent=m}
function daAT(t,el){document.querySelectorAll('.da-auth-t').forEach(function(e){e.style.background='none';e.style.color='#64748b';e.style.boxShadow='none'});el.style.background='#fff';el.style.color='#667eea';el.style.boxShadow='0 2px 8px rgba(0,0,0,.08)';document.getElementById('da-login').style.display=t==='login'?'block':'none';document.getElementById('da-register').style.display=t==='register'?'block':'none'}
function daTab(t,el){document.querySelectorAll('.da-tab').forEach(function(e){e.classList.remove('active')});el.classList.add('active');document.querySelectorAll('.da-sec').forEach(function(e){e.classList.remove('active')});document.getElementById('da-s-'+t).classList.add('active')}
function daLogin(){var p=document.getElementById('da-l-phone').value,pw=document.getElementById('da-l-pass').value;if(!p||!pw){daMsg('da-l-msg','err','أدخل الهاتف وكلمة المرور');return}daMsg('da-l-msg','load','جاري التحقق...');fetch(daA,{method:'POST',body:daFD({action:'dzqcod_customer_login',phone:p,pass:pw})}).then(function(r){return r.json()}).then(function(d){if(d.success){daMsg('da-l-msg','ok','تم الدخول!');setTimeout(function(){location.reload()},600)}else daMsg('da-l-msg','err',d.data&&d.data.message?d.data.message:'خطأ')}).catch(function(){daMsg('da-l-msg','err','خطأ اتصال')})}
function daReg(){var n=document.getElementById('da-r-name').value,p=document.getElementById('da-r-phone').value,e=document.getElementById('da-r-email').value,pw=document.getElementById('da-r-pass').value,w=document.getElementById('da-r-wilaya').value,c=document.getElementById('da-r-commune').value;if(!n||!p||!pw||pw.length<6){daMsg('da-r-msg','err','الاسم والهاتف وكلمة مرور 6+ مطلوبة');return}daMsg('da-r-msg','load','جاري إنشاء الحساب...');fetch(daA,{method:'POST',body:daFD({action:'dzqcod_customer_register',name:n,phone:p,email:e,pass:pw,wilaya:w,commune:c})}).then(function(r){return r.json()}).then(function(d){if(d.success){daMsg('da-r-msg','ok','تم إنشاء حسابك!');setTimeout(function(){location.reload()},600)}else daMsg('da-r-msg','err',d.data&&d.data.message?d.data.message:'خطأ')}).catch(function(){daMsg('da-r-msg','err','خطأ')})}
function daSP(){var fd=daFD({action:'dzqcod_customer_profile_save'});document.querySelectorAll('.da-pf').forEach(function(el){fd.append(el.dataset.key,el.value)});daMsg('da-pf-msg','load','جاري الحفظ...');fetch(daA,{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){daMsg('da-pf-msg',d.success?'ok':'err',d.success?'تم الحفظ!':'خطأ')}).catch(function(){daMsg('da-pf-msg','err','خطأ')})}
function daTrk(num,btn){var out=btn.closest('.da-order')?btn.closest('.da-order').querySelector('.da-trk-r'):document.getElementById('da-trk-main');if(!out)out=document.getElementById('da-trk-main');out.innerHTML='<div class="da-msg load">جاري التتبع...</div>';fetch(daA,{method:'POST',body:daFD({action:'dzqcod_customer_track',tracking:num})}).then(function(r){return r.json()}).then(function(d){if(d.success&&d.data&&d.data.events&&d.data.events.length){var h='<div class="da-timeline">';d.data.events.forEach(function(e,i){h+='<div class="da-tl-item'+(i===0?' latest':'')+'"><div style="font-weight:700;font-size:12px">'+e.status+'</div><div style="font-size:11px;color:#94a3b8">'+e.date+'</div></div>'});out.innerHTML=h+'</div>'}else if(d.success&&d.data&&d.data.status){out.innerHTML='<div class="da-msg ok">'+d.data.status+'</div>'}else out.innerHTML='<div style="padding:16px;background:#f8fafc;border-radius:12px;text-align:center;color:#94a3b8;font-size:13px">لا توجد بيانات تتبع</div>'}).catch(function(){out.innerHTML='<div class="da-msg err">خطأ في الاتصال</div>'})}
function daTrkM(){var n=document.getElementById('da-trk-num').value;if(!n)return;var fake={closest:function(){return null}};daTrk(n,fake)}
function daRO(oid,btn){btn.textContent='⏳';btn.disabled=true;fetch(daA,{method:'POST',body:daFD({action:'dzqcod_customer_reorder',order_id:oid})}).then(function(r){return r.json()}).then(function(d){if(d.success&&d.data.cart_url){btn.textContent='✅';location.href=d.data.cart_url}else{btn.textContent='❌';btn.disabled=false}}).catch(function(){btn.textContent='❌';btn.disabled=false})}
</script>
<?php return ob_get_clean();}

    public function render_tracking($atts=[]): string {$nonce=wp_create_nonce('dzqcod_public');$ajax=admin_url('admin-ajax.php');ob_start();?>
<div dir="rtl" style="max-width:520px;margin:40px auto;font-family:'Segoe UI',Tahoma,sans-serif"><div style="background:#fff;border-radius:20px;padding:32px;box-shadow:0 4px 24px rgba(0,0,0,.08)"><div style="text-align:center;margin-bottom:20px"><div style="font-size:48px;margin-bottom:8px">📍</div><h2 style="font-size:20px;font-weight:900;margin:0">تتبع شحنتك</h2><p style="color:#94a3b8;font-size:13px;margin-top:4px">أدخل رقم التتبع لمعرفة موقع طلبك</p></div><div style="display:flex;gap:8px"><input type="text" id="dz-trk-in" placeholder="رقم التتبع" style="flex:1;padding:14px;border:2px solid #e2e8f0;border-radius:12px;font-size:14px;direction:ltr" onfocus="this.style.borderColor='#667eea'" onblur="this.style.borderColor='#e2e8f0'"><button onclick="dzTrk()" style="padding:14px 24px;background:linear-gradient(135deg,#667eea,#764ba2);color:#fff;border:none;border-radius:12px;font-weight:700;cursor:pointer;font-size:14px">تتبع</button></div><div id="dz-trk-out" style="margin-top:16px"></div></div></div>
<script>function dzTrk(){var n=document.getElementById('dz-trk-in').value;if(!n)return;var o=document.getElementById('dz-trk-out');o.innerHTML='<div style="text-align:center;padding:16px;color:#667eea;font-weight:600">جاري التتبع...</div>';var fd=new FormData();fd.append('action','dzqcod_customer_track');fd.append('tracking',n);fd.append('nonce','<?php echo esc_attr($nonce);?>');fetch('<?php echo esc_url($ajax);?>',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){if(d.success&&d.data&&d.data.events&&d.data.events.length){var h='';d.data.events.forEach(function(e,i){h+='<div style="padding:10px 12px;border-right:3px solid '+(i===0?'#10b981':'#e2e8f0')+';margin-bottom:6px"><div style="font-weight:700;font-size:13px">'+e.status+'</div><div style="font-size:11px;color:#94a3b8">'+e.date+'</div></div>'});o.innerHTML=h}else o.innerHTML='<div style="padding:16px;background:#f8fafc;border-radius:12px;text-align:center;color:#94a3b8">لا توجد بيانات</div>'}).catch(function(){o.innerHTML='<div style="padding:16px;background:#fef2f2;border-radius:12px;text-align:center;color:#991b1b">خطأ في الاتصال</div>'})}</script>
<?php return ob_get_clean();}

    public function customer_login(): void {if(!check_ajax_referer("dzqcod_public","nonce",false))wp_send_json_error(["message"=>"جلسة منتهية"]);$ip=sanitize_text_field($_SERVER["REMOTE_ADDR"]??"");$rk="dzqcod_login_".md5($ip);if((int)get_transient($rk)>=10)wp_send_json_error(["message"=>"حاول لاحقاً"]);set_transient($rk,(int)get_transient($rk)+1,HOUR_IN_SECONDS);$phone=sanitize_text_field($_POST['phone']??'');$pass=sanitize_text_field($_POST['pass']??'');if(!$phone||!$pass)wp_send_json_error(['message'=>'أدخل البيانات']);$users=get_users(['meta_key'=>'billing_phone','meta_value'=>$phone,'number'=>1]);if(empty($users)){$user=get_user_by('login',$phone);if(!$user)wp_send_json_error(['message'=>'رقم الهاتف غير مسجل']);}else{$user=$users[0];}if(!wp_check_password($pass,$user->user_pass,$user->ID))wp_send_json_error(['message'=>'كلمة المرور خاطئة']);wp_set_current_user($user->ID);wp_set_auth_cookie($user->ID,true);wp_send_json_success(['message'=>'تم الدخول']);}

    public function customer_register(): void {if(!check_ajax_referer("dzqcod_public","nonce",false))wp_send_json_error(["message"=>"جلسة منتهية"]);$ip=sanitize_text_field($_SERVER["REMOTE_ADDR"]??"");$rk="dzqcod_reg_".md5($ip);if((int)get_transient($rk)>=5)wp_send_json_error(["message"=>"حاول لاحقاً"]);set_transient($rk,(int)get_transient($rk)+1,HOUR_IN_SECONDS);$name=sanitize_text_field($_POST['name']??'');$phone=sanitize_text_field($_POST['phone']??'');$email=sanitize_email($_POST['email']??'');$pass=$_POST['pass']??'';$wilaya=sanitize_text_field($_POST['wilaya']??'');$commune=sanitize_text_field($_POST['commune']??'');if(!$name||!$phone||strlen($pass)<6)wp_send_json_error(['message'=>'الاسم والهاتف وكلمة مرور 6+ مطلوبة']);$exists=get_users(['meta_key'=>'billing_phone','meta_value'=>$phone,'number'=>1]);if(!empty($exists))wp_send_json_error(['message'=>'رقم الهاتف مسجل مسبقاً']);if(!$email)$email=$phone.'@dzqcod.local';$uid=wp_create_user($phone,$pass,$email);if(is_wp_error($uid))wp_send_json_error(['message'=>$uid->get_error_message()]);wp_update_user(['ID'=>$uid,'display_name'=>$name,'first_name'=>$name]);update_user_meta($uid,'billing_phone',$phone);update_user_meta($uid,'billing_first_name',$name);update_user_meta($uid,'billing_state',$wilaya);update_user_meta($uid,'billing_city',$commune);$wc=new \WC_Customer($uid);$wc->set_role('customer');$wc->save();wp_set_current_user($uid);wp_set_auth_cookie($uid,true);wp_send_json_success(['message'=>'تم إنشاء الحساب']);}

    public function customer_profile_save(): void {if(!check_ajax_referer("dzqcod_public","nonce",false))wp_send_json_error(["message"=>"جلسة منتهية"]);if(!is_user_logged_in())wp_send_json_error(['message'=>'يجب تسجيل الدخول']);$uid=get_current_user_id();$d=$_POST;if(!empty($d['display_name']))wp_update_user(['ID'=>$uid,'display_name'=>sanitize_text_field($d['display_name'])]);if(!empty($d['email'])&&is_email($d['email']))wp_update_user(['ID'=>$uid,'user_email'=>sanitize_email($d['email'])]);if(!empty($d['password'])&&strlen($d['password'])>=6)wp_set_password($d['password'],$uid);if(isset($d['phone']))update_user_meta($uid,'billing_phone',sanitize_text_field($d['phone']));if(isset($d['phone2']))update_user_meta($uid,'billing_phone_2',sanitize_text_field($d['phone2']));if(isset($d['billing_state']))update_user_meta($uid,'billing_state',sanitize_text_field($d['billing_state']));if(isset($d['billing_city']))update_user_meta($uid,'billing_city',sanitize_text_field($d['billing_city']));if(isset($d['billing_address_1']))update_user_meta($uid,'billing_address_1',sanitize_text_field($d['billing_address_1']));wp_send_json_success(['message'=>'تم الحفظ']);}

    public function customer_track(): void {
        // Rate limit
        $ip = sanitize_text_field($_SERVER['REMOTE_ADDR'] ?? '');
        $rk = 'dzqcod_trk_' . md5($ip);
        if ((int)get_transient($rk) >= 20) wp_send_json_error(['message' => 'حاول لاحقاً']);
        set_transient($rk, (int)get_transient($rk) + 1, HOUR_IN_SECONDS);
        
        $tracking = sanitize_text_field($_POST['tracking'] ?? '');
        if (!$tracking || strlen($tracking) < 4) wp_send_json_error(['message' => 'رقم التتبع مطلوب']);
        
        $provider = Core::opt('shipping_provider', 'yalidine');
        $orders = wc_get_orders(['meta_key' => '_dzqcod_tracking_number', 'meta_value' => $tracking, 'limit' => 1]);
        if (!empty($orders)) {
            $o = $orders[0];
            $provider = $o->get_meta('_dzqcod_shipping_provider') ?: $provider;
        }
        
        // Try shipping API first
        if (class_exists('\\DZQCOD\\Shipping')) {
            $ship = new Shipping();
            $result = $ship->track_parcel($tracking, $provider);
            if (!empty($result) && !empty($result['status'])) {
                $events = [];
                if (!empty($result['history'])) {
                    foreach ($result['history'] as $h) {
                        $events[] = ['date' => $h['date'] ?? '', 'status' => $h['status'] ?? ''];
                    }
                }
                if (empty($events)) {
                    $events[] = ['date' => current_time('d/m/Y H:i'), 'status' => $result['status']];
                }
                wp_send_json_success(['events' => $events, 'status' => $result['status']]);
            }
        }
        
        // Fallback: order status only (NO raw order notes — privacy)
        if (!empty($orders)) {
            $o = $orders[0];
            $ost = str_replace('wc-', '', $o->get_status());
            $ws = Core::ST[$ost] ?? ['l' => $ost, 'i' => '📋'];
            $events = [['date' => $o->get_date_modified() ? $o->get_date_modified()->format('d/m/Y H:i') : '', 'status' => ($ws['i'] ?? '') . ' ' . ($ws['l'] ?? $ost)]];
            wp_send_json_success(['events' => $events]);
        }
        
        wp_send_json_error(['message' => 'لا توجد بيانات']);
    }

    public function customer_orders(): void {if(!is_user_logged_in())wp_send_json_error();$orders=wc_get_orders(['customer_id'=>get_current_user_id(),'limit'=>20]);$data=[];foreach($orders as $o){$items=[];foreach($o->get_items() as $i)$items[]=$i->get_name();$data[]=['id'=>$o->get_id(),'total'=>$o->get_total(),'status'=>$o->get_status(),'items'=>$items,'date'=>$o->get_date_created()?$o->get_date_created()->format('Y-m-d'):''];}wp_send_json_success($data);}

    public function customer_reorder(): void {if(!check_ajax_referer("dzqcod_public","nonce",false))wp_send_json_error(["message"=>"جلسة منتهية"]);if(!is_user_logged_in())wp_send_json_error(['message'=>'يجب تسجيل الدخول']);$oid=absint($_POST['order_id']??0);$o=wc_get_order($oid);if(!$o||(int)$o->get_customer_id()!==get_current_user_id())wp_send_json_error(['message'=>'طلب غير صالح']);if(!WC()->cart)wc_load_cart();foreach($o->get_items() as $item){$pid=$item->get_product_id();if($pid&&wc_get_product($pid))WC()->cart->add_to_cart($pid,$item->get_quantity());}wp_send_json_success(['cart_url'=>wc_get_cart_url()]);}
}
