<?php
namespace DZQCOD;

defined('ABSPATH') || exit;

class CustomerAccount {

    public function __construct() {
        // Shortcode for customer dashboard
        add_shortcode('dzqcod_account', [$this, 'render_account']);
        add_shortcode('dzqcod_tracking', [$this, 'render_tracking']);

        // Auto-create account after first order
        add_action('dzqcod_order_created', [$this, 'auto_create_account'], 20, 2);

        // AJAX: Phone lookup for returning customers (no login required)
        add_action('wp_ajax_nopriv_dzqcod_phone_lookup', [$this, 'phone_lookup']);
        add_action('wp_ajax_dzqcod_phone_lookup', [$this, 'phone_lookup']);

        // AJAX endpoints
        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)]);
        }

        // Auto-create account page
        add_action('init', [$this, 'maybe_create_page']);

        // Add to WooCommerce my-account
        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); });
    }

    /**
     * Auto-create WP account after first order using phone as username
     */
    public function auto_create_account(int $oid, $order): void {
        if (!$order || is_user_logged_in()) return;
        $phone = $order->get_billing_phone();
        if (!$phone) return;

        // Check if account already exists
        $clean_phone = preg_replace('/[^0-9]/', '', $phone);
        $existing = get_users(['meta_key' => 'billing_phone', 'meta_value' => $phone, 'number' => 1]);
        if (!empty($existing)) {
            // Link order to existing customer
            $order->set_customer_id($existing[0]->ID);
            $order->save();
            return;
        }

        // Create account
        $name = $order->get_billing_first_name() ?: $order->get_billing_last_name() ?: 'عميل';
        $email = $order->get_billing_email();
        if (!$email || strpos($email, '@dzqcod.local') !== false) {
            $email = $clean_phone . '@dzqcod.auto';
        }

        // Generate simple password from phone
        $pass = substr(md5($clean_phone . 'dzqcod'), 0, 8);

        $uid = wp_create_user($clean_phone, $pass, $email);
        if (is_wp_error($uid)) return;

        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', $order->get_billing_state());
        update_user_meta($uid, 'billing_city', $order->get_billing_city());
        update_user_meta($uid, 'billing_address_1', $order->get_billing_address_1());
        update_user_meta($uid, 'dzqcod_auto_account', 'yes');

        // Set customer role
        $u = new \WP_User($uid);
        $u->set_role('customer');

        // Link order
        $order->set_customer_id($uid);
        $order->save();
    }

    /**
     * AJAX: Phone lookup — check if phone is registered, return name for form auto-fill
     */
    public function phone_lookup(): void {
        $phone = sanitize_text_field($_POST['phone'] ?? '');
        if (strlen($phone) < 8) wp_send_json_error();

        $users = get_users(['meta_key' => 'billing_phone', 'meta_value' => $phone, 'number' => 1]);
        if (empty($users)) {
            // Try normalized
            $clean = preg_replace('/[^0-9]/', '', $phone);
            $users = get_users(['meta_key' => 'billing_phone', 'meta_value' => $clean, 'number' => 1]);
        }

        if (!empty($users)) {
            $u = $users[0];
            wp_send_json_success([
                'found'   => true,
                'name'    => $u->display_name,
                'email'   => $u->user_email,
                'wilaya'  => get_user_meta($u->ID, 'billing_state', true),
                'commune' => get_user_meta($u->ID, 'billing_city', true),
                'address' => get_user_meta($u->ID, 'billing_address_1', true),
                'orders'  => (int)wc_get_customer_order_count($u->ID),
            ]);
        } else {
            wp_send_json_success(['found' => false]);
        }
    }

    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) update_option('dzqcod_account_page_id', $pid);
    }

    public function add_menu_items($items) {
        $new = [];
        foreach ($items as $k => $v) {
            $new[$k] = $v;
            if ($k === 'dashboard') $new['dzqcod-dashboard'] = '📊 لوحة DZQCOD';
        }
        return $new;
    }

    public function endpoint_content() { echo wp_kses_post(do_shortcode('[dzqcod_account]')); }

    // ═══ RENDER FULL ACCOUNT ═══
    public function render_account($atts = []): string {
        $sym = Core::opt('currency_symbol', 'دج');
        $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 : '';

        ob_start();
        ?>
        <div id="dz-account" dir="rtl" style="max-width:900px;margin:0 auto;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif">
        <style>
        #dz-account *{box-sizing:border-box}
        .dza-acc-card{background:#fff;border-radius:16px;padding:20px;margin-bottom:16px;box-shadow:0 1px 3px rgba(0,0,0,.08);border:1px solid #f0f0f0}
        .dza-acc-tabs{display:flex;gap:4px;margin-bottom:20px;border-bottom:2px solid #f0f0f0;overflow-x:auto;-webkit-overflow-scrolling:touch}
        .dza-acc-tab{padding:12px 18px;font-size:13px;font-weight:700;color:#64748b;cursor:pointer;border-bottom:3px solid transparent;white-space:nowrap;transition:.2s}
        .dza-acc-tab.active{color:#667eea;border-color:#667eea}
        .dza-acc-tab:hover{color:#667eea}
        .dza-acc-section{display:none}.dza-acc-section.active{display:block}
        .dza-acc-btn{padding:10px 20px;border:none;border-radius:10px;font-size:14px;font-weight:700;cursor:pointer;transition:.2s}
        .dza-acc-btn.primary{background:linear-gradient(135deg,#667eea,#764ba2);color:#fff}
        .dza-acc-btn.ghost{background:#f1f5f9;color:#475569}
        .dza-acc-input{width:100%;padding:12px;border:2px solid #e2e8f0;border-radius:10px;font-size:14px;transition:.2s}
        .dza-acc-input:focus{border-color:#667eea;outline:none}
        .dza-order-card{border:1px solid #e2e8f0;border-radius:12px;padding:14px;margin-bottom:10px;cursor:pointer;transition:.2s}
        .dza-order-card:hover{border-color:#667eea;box-shadow:0 2px 8px rgba(102,126,234,.15)}
        .dza-stat{text-align:center;padding:16px;background:linear-gradient(135deg,#f8fafc,#f1f5f9);border-radius:12px}
        .dza-stat .n{font-size:28px;font-weight:900;color:#667eea;display:block}
        .dza-stat .l{font-size:11px;color:#94a3b8;margin-top:2px}
        @media(max-width:600px){.dza-acc-tabs{gap:0}.dza-acc-tab{padding:10px 12px;font-size:12px}}
        </style>

        <?php if(!$logged_in): ?>
        <!-- ═══ LOGIN / REGISTER ═══ -->
        <div class="dza-acc-card" id="dz-auth">
        <div style="text-align:center;margin-bottom:24px">
            <div style="font-size:48px;margin-bottom:8px">👤</div>
            <h2 style="margin:0;font-size:22px;font-weight:900">حسابي</h2>
            <p style="color:#94a3b8;margin:4px 0 0;font-size:13px">سجّل الدخول أو أنشئ حساباً لمتابعة طلباتك</p>
        </div>
        <div class="dza-acc-tabs" style="justify-content:center">
            <div class="dza-acc-tab active" onclick="authTab('login',this)">🔑 تسجيل الدخول</div>
            <div class="dza-acc-tab" onclick="authTab('register',this)">✨ حساب جديد</div>
        </div>
        <!-- Login Form -->
        <div id="auth-login">
        <div style="margin-bottom:12px"><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">📱 رقم الهاتف</label>
        <input type="tel" class="dza-acc-input" id="login-phone" placeholder="0555123456" style="direction:ltr"></div>
        <div style="margin-bottom:12px"><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">🔒 كلمة المرور</label>
        <input type="password" class="dza-acc-input" id="login-pass" placeholder="••••••••"></div>
        <button class="dza-acc-btn primary" style="width:100%" onclick="dzLogin()">🔑 دخول</button>
        <div id="login-msg" style="margin-top:8px;font-size:13px;text-align:center"></div>
        </div>
        <!-- Register Form -->
        <div id="auth-register" style="display:none">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px">
        <div><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">👤 الاسم</label>
        <input type="text" class="dza-acc-input" id="reg-name" placeholder="الاسم الكامل"></div>
        <div><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">📱 الهاتف</label>
        <input type="tel" class="dza-acc-input" id="reg-phone" placeholder="0555123456" style="direction:ltr"></div>
        </div>
        <div style="margin-bottom:10px"><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">📧 البريد الإلكتروني</label>
        <input type="email" class="dza-acc-input" id="reg-email" placeholder="example@mail.com" style="direction:ltr"></div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px">
        <div><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">📍 الولاية</label>
        <input type="text" class="dza-acc-input" id="reg-wilaya" placeholder="الجزائر العاصمة"></div>
        <div><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">🏘️ البلدية</label>
        <input type="text" class="dza-acc-input" id="reg-commune" placeholder="باب الزوار"></div>
        </div>
        <div style="margin-bottom:12px"><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">🔒 كلمة المرور</label>
        <input type="password" class="dza-acc-input" id="reg-pass" placeholder="6 أحرف على الأقل"></div>
        <button class="dza-acc-btn primary" style="width:100%" onclick="dzRegister()">✨ إنشاء حساب</button>
        <div id="reg-msg" style="margin-top:8px;font-size:13px;text-align:center"></div>
        </div>
        </div>

        <?php else: ?>
        <!-- ═══ LOGGED IN DASHBOARD ═══ -->
        <div style="display:flex;align-items:center;gap:14px;margin-bottom:20px">
            <div style="width:56px;height:56px;border-radius:50%;background:linear-gradient(135deg,#667eea,#764ba2);display:flex;align-items:center;justify-content:center;color:#fff;font-size:24px;font-weight:900"><?php echo esc_html(mb_substr($name,0,1)); ?></div>
            <div><div style="font-size:18px;font-weight:900"><?php echo esc_html($name); ?></div>
            <div style="font-size:13px;color:#94a3b8"><?php echo esc_html($phone); ?> • <?php echo esc_html($user->user_email); ?></div></div>
            <a href="<?php echo esc_html(wp_logout_url(home_url())); ?>" style="margin-right:auto;font-size:12px;color:#ef4444;text-decoration:none">🚪 خروج</a>
        </div>

        <div class="dza-acc-tabs">
            <div class="dza-acc-tab active" onclick="accTab('orders',this)">📦 طلباتي</div>
            <div class="dza-acc-tab" onclick="accTab('tracking',this)">🔍 تتبع</div>
            <div class="dza-acc-tab" onclick="accTab('downloads',this)">💾 تحميلات</div>
            <div class="dza-acc-tab" onclick="accTab('profile',this)">👤 ملفي</div>
            <div class="dza-acc-tab" onclick="accTab('addresses',this)">📍 عناويني</div>
        </div>

        <!-- Orders Section -->
        <div class="dza-acc-section active" id="sec-orders">
        <?php
        $orders = wc_get_orders(['customer_id' => $user->ID, 'limit' => 20, 'orderby' => 'date', 'order' => 'DESC']);
        $total_spent = 0; $total_orders = count($orders); $delivered = 0;
        foreach($orders as $o) { $total_spent += (float)$o->get_total(); if(in_array($o->get_status(),['wc-delivered','delivered'])) $delivered++; }
        ?>
        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:16px">
        <div class="dza-stat"><span class="n"><?php echo esc_html($total_orders); ?></span><span class="l">إجمالي الطلبات</span></div>
        <div class="dza-stat"><span class="n"><?php echo number_format($total_spent,0); ?></span><span class="l"><?php echo esc_html($sym); ?> إجمالي المشتريات</span></div>
        <div class="dza-stat"><span class="n"><?php echo esc_html($delivered); ?></span><span class="l">تم التسليم</span></div>
        </div>

        <?php if(empty($orders)): ?>
        <div class="dza-acc-card" style="text-align:center;padding:40px"><div style="font-size:48px;margin-bottom:8px">📦</div>
        <p style="color:#94a3b8">لا توجد طلبات بعد</p>
        <a href="<?php echo esc_html(get_permalink(wc_get_page_id('shop'))); ?>" class="dza-acc-btn primary">🛒 تسوّق الآن</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 $i) $items[] = $i->get_name().' ×'.$i->get_quantity();
        $tk = $o->get_meta('_dzqcod_tracking_number');
        ?>
        <div class="dza-order-card" onclick="this.querySelector('.dza-order-detail').style.display=this.querySelector('.dza-order-detail').style.display==='none'?'block':'none'">
        <div style="display:flex;justify-content:space-between;align-items:center">
        <div><span style="font-weight:900;font-size:15px">#<?php echo (int)$o->get_id(); ?></span>
        <span style="font-size:11px;color:#94a3b8;margin-right:8px"><?php echo esc_html($o->get_date_created()?$o->get_date_created()->format('Y-m-d'):'-'); ?></span></div>
        <span style="background:<?php echo esc_html($ws['c']); ?>;color:#fff;padding:3px 12px;border-radius:8px;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:6px"><?php echo esc_html(implode(' | ', $items)); ?></div>
        <div style="display:flex;justify-content:space-between;align-items:center;margin-top:8px">
        <span style="font-size:18px;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:2px 8px;border-radius:6px;font-family:monospace"><?php echo esc_html($tk); ?></span><?php endif; ?>
        </div>
        <div class="dza-order-detail" style="display:none;margin-top:12px;padding-top:12px;border-top:1px solid #f0f0f0">
        <table style="width:100%;font-size:12px;border-collapse:collapse"><thead><tr style="background:#f8fafc"><th style="padding:6px;text-align:right">المنتج</th><th style="text-align:center;padding:6px">الكمية</th><th style="padding:6px">المبلغ</th></tr></thead><tbody>
        <?php foreach($o->get_items() as $it): ?>
        <tr><td style="padding:6px"><?php echo esc_html($it->get_name()); ?></td><td style="text-align:center;padding:6px"><?php echo esc_html($it->get_quantity()); ?></td><td style="padding:6px;font-weight:700"><?php echo number_format((float)$it->get_total(),0); ?> <?php echo esc_html($sym); ?></td></tr>
        <?php endforeach; ?>
        </tbody></table>
        <?php if($tk): ?><button class="dza-acc-btn ghost" style="width:100%;margin-top:8px;font-size:12px" onclick="event.stopPropagation();trackPkg('<?php echo esc_html(esc_js($tk)); ?>',this)">🔍 تتبع الشحنة</button><?php endif; ?>
        <div class="track-result" style="margin-top:6px"></div>
        </div></div>
        <?php endforeach; endif; ?>
        </div>

        <!-- Tracking Section -->
        <div class="dza-acc-section" id="sec-tracking">
        <div class="dza-acc-card">
        <h3 style="font-size:16px;font-weight:900;margin:0 0 12px">🔍 تتبع شحنتك</h3>
        <div style="display:flex;gap:8px"><input type="text" class="dza-acc-input" id="track-input" placeholder="أدخل رقم التتبع" style="direction:ltr;flex:1">
        <button class="dza-acc-btn primary" onclick="trackManual()">تتبع</button></div>
        <div id="track-result-main" style="margin-top:12px"></div>
        </div></div>

        <!-- Downloads Section -->
        <div class="dza-acc-section" id="sec-downloads">
        <div class="dza-acc-card">
        <h3 style="font-size:16px;font-weight:900;margin:0 0 12px">💾 ملفاتي القابلة للتحميل</h3>
        <?php
        $downloads = wc_get_customer_available_downloads($user->ID);
        if(empty($downloads)): ?>
        <p style="text-align:center;color:#94a3b8;padding:20px">لا توجد ملفات للتحميل</p>
        <?php else: foreach($downloads as $dl): ?>
        <div style="display:flex;align-items:center;gap:10px;padding:10px;border:1px solid #e2e8f0;border-radius:10px;margin-bottom:6px">
        <span style="font-size:24px">📄</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 esc_html($dl['file']['name']??'ملف'); ?> • <?php echo esc_html($dl['downloads_remaining']===''?'∞':$dl['downloads_remaining']); ?> تحميلات متبقية</div></div>
        <a href="<?php echo esc_url($dl['download_url']); ?>" class="dza-acc-btn primary" style="font-size:12px;padding:8px 16px">⬇️ تحميل</a>
        </div>
        <?php endforeach; endif; ?>
        </div></div>

        <!-- Profile Section -->
        <div class="dza-acc-section" id="sec-profile">
        <div class="dza-acc-card">
        <h3 style="font-size:16px;font-weight:900;margin:0 0 12px">👤 الملف الشخصي</h3>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
        <div><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">الاسم</label>
        <input type="text" class="dza-acc-input prof-field" data-key="display_name" value="<?php echo esc_attr($name); ?>"></div>
        <div><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">البريد</label>
        <input type="email" class="dza-acc-input prof-field" data-key="email" value="<?php echo esc_attr($user->user_email); ?>" style="direction:ltr"></div>
        <div><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">الهاتف</label>
        <input type="tel" class="dza-acc-input prof-field" data-key="phone" value="<?php echo esc_attr($phone); ?>" style="direction:ltr"></div>
        <div><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">هاتف 2</label>
        <input type="tel" class="dza-acc-input prof-field" data-key="phone2" value="<?php echo esc_attr(get_user_meta($user->ID,'billing_phone_2',true)); ?>" style="direction:ltr"></div>
        </div>
        <div style="margin-top:12px"><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">🔒 كلمة مرور جديدة (اتركها فارغة للإبقاء)</label>
        <input type="password" class="dza-acc-input prof-field" data-key="password" placeholder="••••••••"></div>
        <button class="dza-acc-btn primary" style="width:100%;margin-top:12px" onclick="saveProfile()">💾 حفظ التغييرات</button>
        <div id="profile-msg" style="margin-top:8px;font-size:13px;text-align:center"></div>
        </div></div>

        <!-- Addresses Section -->
        <div class="dza-acc-section" id="sec-addresses">
        <div class="dza-acc-card">
        <h3 style="font-size:16px;font-weight:900;margin:0 0 12px">📍 عنوان التوصيل</h3>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
        <div><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">الولاية</label>
        <input type="text" class="dza-acc-input prof-field" data-key="billing_state" value="<?php echo esc_attr(get_user_meta($user->ID,'billing_state',true)); ?>"></div>
        <div><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">البلدية</label>
        <input type="text" class="dza-acc-input prof-field" data-key="billing_city" value="<?php echo esc_attr(get_user_meta($user->ID,'billing_city',true)); ?>"></div>
        </div>
        <div style="margin-top:10px"><label style="font-size:12px;font-weight:700;display:block;margin-bottom:4px">العنوان التفصيلي</label>
        <input type="text" class="dza-acc-input prof-field" data-key="billing_address_1" value="<?php echo esc_attr(get_user_meta($user->ID,'billing_address_1',true)); ?>"></div>
        <button class="dza-acc-btn primary" style="width:100%;margin-top:12px" onclick="saveProfile()">💾 حفظ العنوان</button>
        </div></div>

        <?php endif; // end logged_in ?>
        </div>

        <script>
        function authTab(t,el){document.querySelectorAll('#dz-auth .dza-acc-tab').forEach(function(e){e.classList.remove('active')});el.classList.add('active');document.getElementById('auth-login').style.display=t==='login'?'block':'none';document.getElementById('auth-register').style.display=t==='register'?'block':'none'}
        function accTab(t,el){document.querySelectorAll('.dza-acc-tab').forEach(function(e){e.classList.remove('active')});el.classList.add('active');document.querySelectorAll('.dza-acc-section').forEach(function(e){e.classList.remove('active')});document.getElementById('sec-'+t).classList.add('active')}

        function dzLogin(){
            var phone=document.getElementById('login-phone').value,pass=document.getElementById('login-pass').value;
            if(!phone||!pass){document.getElementById('login-msg').innerHTML='<span style="color:#ef4444">أدخل الهاتف وكلمة المرور</span>';return}
            document.getElementById('login-msg').innerHTML='<span style="color:#667eea">⏳ جاري التحقق...</span>';
            var fd=new FormData();fd.append('action','dzqcod_customer_login');fd.append('phone',phone);fd.append('pass',pass);
            <?php if(function_exists('wp_create_nonce')): ?>fd.append('nonce','<?php echo esc_html(wp_create_nonce('dzqcod_public')); ?>');<?php endif; ?>
            fetch('<?php echo esc_url(admin_url("admin-ajax.php")); ?>',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){
                if(d.success){document.getElementById('login-msg').innerHTML='<span style="color:#22c55e">✅ تم الدخول!</span>';setTimeout(function(){location.reload()},800)}
                else document.getElementById('login-msg').innerHTML='<span style="color:#ef4444">❌ '+(d.data?d.data.message:'خطأ')+'</span>'
            }).catch(function(){document.getElementById('login-msg').innerHTML='<span style="color:#ef4444">❌ خطأ في الاتصال</span>'})
        }
        function dzRegister(){
            var n=document.getElementById('reg-name').value,p=document.getElementById('reg-phone').value,
                e=document.getElementById('reg-email').value,pw=document.getElementById('reg-pass').value,
                w=document.getElementById('reg-wilaya').value,c=document.getElementById('reg-commune').value;
            if(!n||!p||!pw){document.getElementById('reg-msg').innerHTML='<span style="color:#ef4444">الاسم والهاتف وكلمة المرور مطلوبة</span>';return}
            document.getElementById('reg-msg').innerHTML='<span style="color:#667eea">⏳...</span>';
            var fd=new FormData();fd.append('action','dzqcod_customer_register');fd.append('name',n);fd.append('phone',p);fd.append('email',e);fd.append('pass',pw);fd.append('wilaya',w);fd.append('commune',c);
            <?php if(function_exists('wp_create_nonce')): ?>fd.append('nonce','<?php echo esc_html(wp_create_nonce('dzqcod_public')); ?>');<?php endif; ?>
            fetch('<?php echo esc_url(admin_url("admin-ajax.php")); ?>',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){
                if(d.success){document.getElementById('reg-msg').innerHTML='<span style="color:#22c55e">✅ تم إنشاء حسابك!</span>';setTimeout(function(){location.reload()},800)}
                else document.getElementById('reg-msg').innerHTML='<span style="color:#ef4444">❌ '+(d.data?d.data.message:'خطأ')+'</span>'
            })
        }
        function saveProfile(){
            var fd=new FormData();fd.append('action','dzqcod_customer_profile_save');
            <?php if(function_exists('wp_create_nonce')): ?>fd.append('nonce','<?php echo esc_html(wp_create_nonce('dzqcod_public')); ?>');<?php endif; ?>
            document.querySelectorAll('.prof-field').forEach(function(el){fd.append(el.dataset.key,el.value)});
            document.getElementById('profile-msg').innerHTML='<span style="color:#667eea">⏳...</span>';
            fetch('<?php echo esc_url(admin_url("admin-ajax.php")); ?>',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){
                document.getElementById('profile-msg').innerHTML=d.success?'<span style="color:#22c55e">✅ تم الحفظ!</span>':'<span style="color:#ef4444">❌</span>'
            })
        }
        function trackPkg(n,btn){
            var r=btn.parentElement.querySelector('.track-result');r.innerHTML='<span style="color:#667eea;font-size:12px">⏳ جاري التتبع...</span>';
            var fd=new FormData();fd.append('action','dzqcod_customer_track');fd.append('tracking',n);
            fetch('<?php echo esc_url(admin_url("admin-ajax.php")); ?>',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){
                if(d.success&&d.data.events){var h='';d.data.events.forEach(function(e){h+='<div style="padding:4px 0;border-right:2px solid #667eea;padding-right:8px;margin-bottom:4px;font-size:11px"><strong>'+e.status+'</strong><br><span style="color:#94a3b8">'+e.date+'</span></div>'});r.innerHTML=h}
                else r.innerHTML='<span style="font-size:12px;color:#94a3b8">لا توجد بيانات تتبع</span>'
            })
        }
        function trackManual(){var n=document.getElementById('track-input').value;if(!n)return;trackPkg(n,{parentElement:document.getElementById('sec-tracking').querySelector('.dza-acc-card')})}
        </script>
        <?php
        return ob_get_clean();
    }

    // ═══ Tracking shortcode ═══
    public function render_tracking($atts = []): string {
        ob_start(); ?>
        <div dir="rtl" style="max-width:500px;margin:0 auto;padding:20px">
        <div style="background:#fff;border-radius:16px;padding:24px;box-shadow:0 2px 8px rgba(0,0,0,.08)">
        <h2 style="text-align:center;font-size:20px;margin:0 0 16px">🔍 تتبع شحنتك</h2>
        <div style="display:flex;gap:8px"><input type="text" id="dz-track-num" placeholder="أدخل رقم التتبع" style="flex:1;padding:12px;border:2px solid #e2e8f0;border-radius:10px;direction:ltr;font-size:14px">
        <button onclick="dzTrack()" style="padding:12px 20px;background:#667eea;color:#fff;border:none;border-radius:10px;font-weight:700;cursor:pointer">تتبع</button></div>
        <div id="dz-track-out" style="margin-top:16px"></div>
        </div></div>
        <script>function dzTrack(){var n=document.getElementById('dz-track-num').value;if(!n)return;var o=document.getElementById('dz-track-out');o.innerHTML='⏳';
        var fd=new FormData();fd.append('action','dzqcod_customer_track');fd.append('tracking',n);
        fetch('<?php echo esc_url(admin_url("admin-ajax.php")); ?>',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){
        if(d.success&&d.data.events){var h='';d.data.events.forEach(function(e){h+='<div style="padding:8px;border-right:3px solid #667eea;padding-right:12px;margin-bottom:8px"><div style="font-weight:700">'+e.status+'</div><div style="font-size:12px;color:#94a3b8">'+e.date+'</div></div>'});o.innerHTML=h}
        else o.innerHTML='<p style="color:#94a3b8;text-align:center">لا توجد بيانات</p>'})}</script>
        <?php return ob_get_clean();
    }

    // ═══ AJAX: Login ═══
    public function customer_login(): void {
        $phone = sanitize_text_field($_POST['phone'] ?? '');
        $pass  = sanitize_text_field($_POST['pass'] ?? '');
        if (!$phone || !$pass) wp_send_json_error(['message' => 'أدخل البيانات']);

        // Find user by phone
        $users = get_users(['meta_key' => 'billing_phone', 'meta_value' => $phone, 'number' => 1]);
        if (empty($users)) {
            // Try with username = phone
            $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' => 'تم الدخول']);
    }

    // ═══ AJAX: Register ═══
    public function customer_register(): void {
        $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+ مطلوبة']);
        }

        // Check if phone exists
        $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);
        (new \WC_Customer($uid))->set_role('customer');

        wp_set_current_user($uid);
        wp_set_auth_cookie($uid, true);
        wp_send_json_success(['message' => 'تم إنشاء الحساب']);
    }

    // ═══ AJAX: Save Profile ═══
    public function customer_profile_save(): void {
        if (!is_user_logged_in()) wp_send_json_error();
        $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'])) wp_update_user(['ID' => $uid, 'user_email' => sanitize_email($d['email'])]);
        if (!empty($d['password'])) 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' => 'تم الحفظ']);
    }

    // ═══ AJAX: Track ═══
    public function customer_track(): void {
        $tracking = sanitize_text_field($_POST['tracking'] ?? '');
        if (!$tracking) wp_send_json_error();

        $provider = Core::opt('shipping_provider', 'yalidine');
        // Try to find order by tracking
        $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;
        }

        // Fetch tracking from API via Shipping class
        $ship = new Shipping();
        $result = $ship->track_package($tracking, $provider);
        if ($result) wp_send_json_success($result);

        // Fallback — return order notes as events
        if (!empty($orders)) {
            $events = [];
            foreach (wc_get_order_notes(['order_id' => $o->get_id(), 'limit' => 10]) as $n) {
                $events[] = ['date' => $n->date_created->format('Y-m-d H:i'), 'status' => wp_strip_all_tags($n->content)];
            }
            wp_send_json_success(['events' => $events]);
        }

        wp_send_json_error(['message' => 'لا توجد بيانات']);
    }

    // ═══ AJAX: Reorder ═══
    public function customer_reorder(): void {
        if (!is_user_logged_in()) wp_send_json_error();
        $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();

        foreach ($o->get_items() as $item) {
            WC()->cart->add_to_cart($item->get_product_id(), $item->get_quantity());
        }
        wp_send_json_success(['cart_url' => wc_get_cart_url()]);
    }
}
