<?php
date_default_timezone_set('Africa/Cairo'); // سطر مهم جداً
// Enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Create logs directory if it doesn't exist
if (!file_exists('logs')) {
    mkdir('logs', 0755, true);
}

if(isset($_POST['date']) && $_POST['date']){
    $data['followup_date'] = strtotime($_POST['date']); 
}
// ==== الحماية بكلمة سر (Basic Auth) ====
$thePassword = "smart0777"; // غيّرها بسرّ خاص بك
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="Protected Page"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'صفحة محمية. يرجى إدخال كلمة المرور.'; exit;
} else {
    if ($_SERVER['PHP_AUTH_PW'] !== $thePassword) {
        header('WWW-Authenticate: Basic realm="Protected Page"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'كلمة المرور غير صحيحة.'; exit;
    }
}

// ==== إعدادات الواتساب وغيرها ====
$config = [
      'whatsapp_token'      => "EAAKo9dWi7lsBPMppbheQYqcBlBStDx4noxqeLyXp5azaxZA1GYbbogHwRnfmf4p63RUFXZAfAd9wS3PYEBrjJ5baLyaRuaAZBl5pkVFNBzGe8P1haMEkv5HZAZB4C9F5kjYOcNfIJapnZCJHJ5qwoEFZAInfjadP4E8OdcAaJ01ZAuUnTaW9OWESTzCVMzzd2x0DZBgZDZD",
    'messenger_token'     => "EAAU3fZCXPBqkBPAcGFLOCC2t4vsi2pG7ZANV2Xanioql4gxgjvpMjwE9P7JT0l5JUsyQoox84NrdOBBtIS2YKv9wScQ9cFV7TWCMU4RW8VzOkZArm0ToaxmxNEgXSs4uhcRChU7orsn2iPiWO3mqE7pEMrQBxieWhrOEt9WjzOZAsZA1JlrM7hnbNJs52omt3QiwakwZDZD",
    'facebook_token'     => "EAAU3fZCXPBqkBPAcGFLOCC2t4vsi2pG7ZANV2Xanioql4gxgjvpMjwE9P7JT0l5JUsyQoox84NrdOBBtIS2YKv9wScQ9cFV7TWCMU4RW8VzOkZArm0ToaxmxNEgXSs4uhcRChU7orsn2iPiWO3mqE7pEMrQBxieWhrOEt9WjzOZAsZA1JlrM7hnbNJs52omt3QiwakwZDZD",
 'phone_number_id'  => '713668888490465',
    'whatsapp_timeout' => 25,
];
$status_list = [
    'new'             => 'جديد',
    'interested'      => 'مهتم',
    'negotiation'     => 'تفاوض',
    'scheduled'       => 'تم تحديد موعد',      // جديد: تم تحديد معاد أو اجتماع
    'followup'        => 'متابعة',             // جديد: يحتاج متابعة مستقبلية
    'recall'          => 'إعادة اتصال',        // جديد: مطلوب إعادة اتصال للعميل
    'callback'        => 'بانتظار اتصال',
    'closed'          => 'تم التعاقد',
    'not_interested'  => 'غير مهتم',
    'no_answer'       => 'لم يرد',
    'not_available'       => 'مغلق',

    'cancelled'       => 'ألغى الطلب',
    'friend'           => 'صديق',

    'other'           => 'أخرى'
];
// إضافة Facebook token للـ config 
$config['facebook_token'] = $config['messenger_token']; // استخدم نفس التوكن

// ===== معالجة تحميل ملفات البيانات الخارجية (مُصحح) =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['external_file'])) {
    // Log تفاصيل الطلب
    file_put_contents('logs/import_debug.log', 
        date('Y-m-d H:i:s') . " Import attempt started\n" .
        "File: " . json_encode($_FILES['external_file'], JSON_UNESCAPED_UNICODE) . "\n" .
        "POST: " . json_encode($_POST, JSON_UNESCAPED_UNICODE) . "\n\n", 
        FILE_APPEND
    );
    
    $uploadResult = handleFileUpload($_FILES['external_file']);
    
    if ($uploadResult['success']) {
        $phones = parseExternalFile($uploadResult['file_path'], $_POST['file_type']);
        
        if (!empty($phones)) {
            // حفظ البيانات المستوردة في جلسة مؤقتة
            session_start();
            $_SESSION['imported_contacts'] = $phones;
            
            echo json_encode([
                'success' => true, 
                'count' => count($phones),
                'contacts' => array_slice($phones, 0, 10) // عرض أول 10 للمعاينة
            ]);
        } else {
            echo json_encode(['success' => false, 'error' => 'لم يتم العثور على بيانات صالحة في الملف']);
        }
    } else {
        echo json_encode(['success' => false, 'error' => $uploadResult['error']]);
    }
    exit;
}



// إرسال جماعي للملفات المستوردة (مُصحح)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_to_imported'])) {
    session_start();
    $contacts = $_SESSION['imported_contacts'] ?? [];
    $message = $_POST['imported_message'] ?? '';
    $sendResults = [];
    $successCount = 0;
    
    foreach ($contacts as $contact) {
        $phone = $contact['phone'];
        $vars = [
            '{name}' => $contact['name'] ?? '',
            '{phone}' => $phone,
            '{company}' => $contact['company'] ?? '',
            '{business_type}' => $contact['business_type'] ?? '',
            '{city}' => $contact['city'] ?? '',
            '{email}' => $contact['email'] ?? ''
        ];
        $personalizedMsg = str_replace(array_keys($vars), array_values($vars), $message);
        
        $success = sendWhatsAppMessage($phone, $personalizedMsg);
        $sendResults[$phone] = $success ? 'تم الإرسال بنجاح' : 'فشل الإرسال';
        if ($success) $successCount++;
        
        // إنشاء ملف عميل جديد إذا لم يكن موجود (تصحيح المسار)
        if (!file_exists("customers/{$phone}.json")) {
            $customerData = [
                'phone' => $phone,
                'name' => $contact['name'] ?? '',
                'company' => $contact['company'] ?? '',
                'business_type' => $contact['business_type'] ?? '',
                'city' => $contact['city'] ?? '',
                'email' => $contact['email'] ?? '',
                'status' => 'new',
                'created_at' => time(),
                'last_contact' => time(),
                'source' => 'imported_file',
                'conversation_count' => 0,
                'interests' => [],
                'notes' => []
            ];
            file_put_contents("customers/{$phone}.json", json_encode($customerData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
        }
        
        // تأخير بسيط لتجنب الـ rate limiting
        usleep(500000); // 0.5 ثانية
    }
    
    unset($_SESSION['imported_contacts']); // مسح البيانات المؤقتة
    
    // إرجاع النتائج
    echo json_encode([
        'success' => true,
        'total' => count($contacts),
        'sent' => $successCount,
        'results' => $sendResults
    ]);
    exit;
}

// دوال مساعدة للملفات الخارجية (محسنة)
function handleFileUpload($file) {
    global $config;
    
    // التحقق من الأخطاء
    $errors = [
        UPLOAD_ERR_INI_SIZE => 'الملف كبير جداً (تجاوز حد الخادم)',
        UPLOAD_ERR_FORM_SIZE => 'الملف كبير جداً (تجاوز حد النموذج)', 
        UPLOAD_ERR_PARTIAL => 'تم تحميل جزء من الملف فقط',
        UPLOAD_ERR_NO_FILE => 'لم يتم تحميل أي ملف',
        UPLOAD_ERR_NO_TMP_DIR => 'مجلد مؤقت مفقود',
        UPLOAD_ERR_CANT_WRITE => 'فشل في كتابة الملف',
        UPLOAD_ERR_EXTENSION => 'إضافة PHP أوقفت التحميل'
    ];
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return ['success' => false, 'error' => $errors[$file['error']] ?? 'خطأ غير معروف في تحميل الملف'];
    }
    
    if ($file['size'] > $config['max_file_size']) {
        return ['success' => false, 'error' => 'حجم الملف كبير جداً (أقصى حد ' . round($config['max_file_size']/1024/1024) . 'MB)'];
    }
    
    if ($file['size'] == 0) {
        return ['success' => false, 'error' => 'الملف فارغ'];
    }
    
    $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($extension, $config['allowed_extensions'])) {
        return ['success' => false, 'error' => 'نوع الملف غير مدعوم. الأنواع المدعومة: ' . implode(', ', $config['allowed_extensions'])];
    }
    
    // إنشاء مجلد uploads إذا لم يكن موجود
    if (!file_exists($config['upload_dir'])) {
        mkdir($config['upload_dir'], 0755, true);
    }
    
    $filename = 'import_' . time() . '_' . mt_rand(1000, 9999) . '.' . $extension;
    $filepath = $config['upload_dir'] . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return ['success' => true, 'file_path' => $filepath];
    }
    
    return ['success' => false, 'error' => 'فشل في حفظ الملف على الخادم'];
}

function parseExternalFile($filepath, $fileType) {
    $contacts = [];
    
    switch ($fileType) {
        case 'excel':
            $contacts = parseExcelFile($filepath);
            break;
        case 'csv':
            $contacts = parseCSVFile($filepath);
            break;
        case 'txt':
            $contacts = parseTxtFile($filepath);
            break;
    }
    
    // تنظيف الملف بعد المعالجة
    if (file_exists($filepath)) {
        unlink($filepath);
    }
    
    return $contacts;
}

function parseExcelFile($filepath) {
    // تحويل Excel إلى CSV أولاً أو معالجة مباشرة
    $extension = strtolower(pathinfo($filepath, PATHINFO_EXTENSION));
    
    if (in_array($extension, ['xlsx', 'xls'])) {
        // محاولة قراءة Excel كـ CSV
        return parseCSVFile($filepath);
    } else {
        return parseCSVFile($filepath);
    }
}

function parseCSVFile($filepath) {
    $contacts = [];
    
    if (!file_exists($filepath)) {
        return [];
    }
    
    // محاولة قراءة الملف بترميزات مختلفة
    $content = file_get_contents($filepath);
    if (!$content) {
        return [];
    }
    
    // إزالة BOM إذا وجد
    $content = preg_replace('/^\xEF\xBB\xBF/', '', $content);
    
    // حفظ المحتوى المنظف
    file_put_contents($filepath, $content);
    
    if (($handle = fopen($filepath, "r")) !== FALSE) {
        // قراءة الهيدر
        $headers = fgetcsv($handle, 1000, ",");
        if (!$headers) {
            fclose($handle);
            return [];
        }
        
        $headers = array_map('trim', $headers);
        
        // تطبيع أسماء الأعمدة
        $normalizedHeaders = [];
        foreach ($headers as $header) {
            $key = strtolower(trim($header));
            $key = str_replace([' ', '-', '_'], '', $key);
            
            // ترجمة الأعمدة العربية والإنجليزية
            switch ($key) {
                case 'name':
                case 'اسم':
                case 'الاسم':
                    $normalizedHeaders[] = 'name';
                    break;
                case 'phone':
                case 'mobile':
                case 'telephone':
                case 'هاتف':
                case 'رقم':
                case 'موبايل':
                    $normalizedHeaders[] = 'phone';
                    break;
                case 'company':
                case 'شركة':
                case 'الشركة':
                    $normalizedHeaders[] = 'company';
                    break;
                case 'businesstype':
                case 'business':
                case 'نشاط':
                case 'النشاط':
                case 'عمل':
                    $normalizedHeaders[] = 'business_type';
                    break;
                case 'city':
                case 'مدينة':
                case 'المدينة':
                    $normalizedHeaders[] = 'city';
                    break;
                case 'email':
                case 'ايميل':
                case 'بريد':
                    $normalizedHeaders[] = 'email';
                    break;
                default:
                    $normalizedHeaders[] = $key;
                    break;
            }
        }
        
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            if (count($data) >= count($normalizedHeaders)) {
                $contact = [];
                for ($i = 0; $i < count($normalizedHeaders); $i++) {
                    if (isset($data[$i])) {
                        $contact[$normalizedHeaders[$i]] = trim($data[$i]);
                    }
                }
                
                // البحث عن رقم هاتف صالح
                $phone = '';
                $phoneFields = ['phone', 'mobile', 'telephone'];
                foreach ($phoneFields as $field) {
                    if (!empty($contact[$field])) {
                        $phone = preg_replace('/[^\d+]/', '', $contact[$field]);
                        break;
                    }
                }
                
                // التحقق من صحة الرقم
                if (strlen($phone) >= 10) {
                    $contact['phone'] = $phone;
                    $contacts[] = $contact;
                }
            }
        }
        fclose($handle);
    }
    
    return $contacts;
}

function parseTxtFile($filepath) {
    $contacts = [];
    
    if (!file_exists($filepath)) {
        return [];
    }
    
    $content = file_get_contents($filepath);
    if (!$content) {
        return [];
    }
    
    // إزالة BOM
    $content = preg_replace('/^\xEF\xBB\xBF/', '', $content);
    $lines = explode("\n", $content);
    
    foreach ($lines as $line) {
        $line = trim($line);
        if (empty($line)) continue;
        
        // إذا كان السطر يحتوي على فواصل، افترض تنسيق CSV
        if (strpos($line, ',') !== false) {
            $parts = array_map('trim', explode(',', $line));
            $phone = '';
            
            // البحث عن الرقم في أي موضع
            foreach ($parts as $part) {
                $cleanPhone = preg_replace('/[^\d+]/', '', $part);
                if (strlen($cleanPhone) >= 10) {
                    $phone = $cleanPhone;
                    break;
                }
            }
            
            if ($phone) {
                $contacts[] = [
                    'name' => $parts[0] ?? '',
                    'phone' => $phone,
                    'company' => $parts[2] ?? '',
                    'business_type' => $parts[3] ?? '',
                    'city' => $parts[4] ?? '',
                    'email' => $parts[5] ?? ''
                ];
            }
        } else {
            // إذا كان السطر يحتوي على رقم فقط
            $phone = preg_replace('/[^\d+]/', '', $line);
            if (strlen($phone) >= 10) {
                $contacts[] = [
                    'name' => '',
                    'phone' => $phone,
                    'company' => '',
                    'business_type' => '',
                    'city' => '',
                    'email' => ''
                ];
            }
        }
    }
    
    return $contacts;
}


// ==== العمليات AJAX والإجرائية =====
// تحديث حالة
if(isset($_POST['set_status']) && isset($_POST['phone']) && isset($_POST['status'])){
    $ph = preg_replace('/[^\d]/','',$_POST['phone']);
    $st = $_POST['status'];
    $f  = "../customers/$ph.json";
    if(file_exists($f) && array_key_exists($st, $status_list)){
        $data = json_decode(file_get_contents($f),true);
        $data['status'] = $st;
        if(isset($_POST['date']) && $_POST['date']){
            // تاريخ على صيغة "YYYY-MM-DD HH:MM"
            $data['followup_date'] = strtotime($_POST['date']);
        }
        if(isset($_POST['note']) && $_POST['note']){
            $data['note'] = $_POST['note'];
        }

        file_put_contents($f,json_encode($data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
        echo json_encode(['ok'=>1,'status'=>$status_list[$st],'val'=>$st]);
    } else echo json_encode(['ok'=>0]);
    exit;
}

// إرسال واتساب
function sendWhatsAppMessage(string $to, string $message): array {
    global $config;
    
    // Log attempt
    error_log("Attempting to send message to: $to");
    
    $payload = json_encode([
        'messaging_product' => 'whatsapp',
        'to' => $to,
        'type' => 'text',
        'text' => ['body' => mb_substr($message, 0, 1000, 'UTF-8')],
    ], JSON_UNESCAPED_UNICODE);
    
    $ch = curl_init("https://graph.facebook.com/v19.0/{$config['phone_number_id']}/messages");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $config['whatsapp_token'],
        ],
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => $config['whatsapp_timeout'],
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    
    $resp = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err = curl_error($ch);
    curl_close($ch);
    
    // Enhanced logging
    error_log("WhatsApp API Response - HTTP Code: $httpCode, cURL Error: $err, Response: $resp");
    
    if ($err || $httpCode < 200 || $httpCode >= 300) {
        return ['success' => false, 'error' => $resp ?: $err, 'http_code' => $httpCode];
    }
    
    $responseData = json_decode($resp, true);
    if (isset($responseData['error'])) {
        return ['success' => false, 'error' => $responseData['error']['message']];
    }
    
    return ['success' => true, 'response' => $resp];
}

// اختبار سريع للواتساب API
if (isset($_GET['test_whatsapp'])) {
    $testResult = sendWhatsAppMessage('201144470365', 'رسالة تجريبية من Smart Logic CRM 🚀');
    echo '<pre>';
    print_r($testResult);
    echo '</pre>';
    exit;
}


// دالة إرسال ماسنجر (أضفها بجانب دالة الواتساب)
function sendMessengerMessage(string $to, string $message): array {
    global $config;
    
    $payload = json_encode([
        'recipient' => ['id' => $to],
        'message'   => ['text' => mb_substr($message, 0, 1000, 'UTF-8')]
    ], JSON_UNESCAPED_UNICODE);
    
    $ch = curl_init("https://graph.facebook.com/v19.0/me/messages?access_token={$config['messenger_token']}");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 25,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    
    $resp = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err = curl_error($ch);
    curl_close($ch);
    
    if ($err || $httpCode < 200 || $httpCode >= 300) {
        return ['success' => false, 'error' => $resp ?: $err];
    }
    
    return ['success' => true, 'response' => $resp];
}


// تصدير بيانات CSV
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['export_phones'])) {
    $phones = json_decode($_POST['export_phones'],true);
    $rows[] = [
        'Platform','Platform ID','Phone',
        'Name','Email','City','Company','Business',
        'Interests','Intent','Conversations','Last Contact','Status',
        'Orders Count','Last Order ID','Last Order Status','Last Order Date','Last Order Summary'
    ];
    foreach ($phones as $ph){
        $data = file_exists("../customers/{$ph}.json") ? json_decode(file_get_contents("../customers/{$ph}.json"),true) : [];
        $platformId = (string)($data['platform_id'] ?? $ph);
        $platform = (string)($data['platform'] ?? '');
        $realPhone = (string)($data['phone_real'] ?? '');
        $phoneField = (string)($data['phone'] ?? '');
        if ($realPhone === '') {
            if ($platform === 'whatsapp' && $phoneField !== '') {
                $realPhone = $phoneField;
            } elseif ($phoneField !== '' && $phoneField !== $platformId) {
                $realPhone = $phoneField;
            }
        }
        $ordersCount = (int)($data['orders_count'] ?? (is_array($data['orders'] ?? null) ? count($data['orders']) : 0));
        $lastOrderAt = !empty($data['last_order_at']) ? date('Y-m-d H:i', $data['last_order_at']) : '';
        $rows[] = [
            $platform, $platformId, $realPhone,
            $data['name']??'',$data['email']??'',$data['city']??'',$data['company']??'',$data['business_type']??'',
            isset($data['interests']) && is_array($data['interests'])? implode(' , ',$data['interests']) : '',
            $data['last_intent']??'',$data['conversation_count']??0,
            !empty($data['last_contact'])? date('Y-m-d H:i',$data['last_contact']) : '',
            $status_list[$data['status']??'new'] ?? '',
            $ordersCount,
            $data['last_order_id'] ?? '',
            $data['last_order_status'] ?? '',
            $lastOrderAt,
            $data['last_order_summary'] ?? ''
        ];
    }
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="customers_'.date('Ymd_His').'.csv"');
    $out = fopen('php://output','w');
    fwrite($out, "\xEF\xBB\xBF");
    foreach($rows as $r) fputcsv($out,$r);
    fclose($out); exit;
}

// إرسال جماعي واتساب
// إرسال جماعي للملفات المستوردة (مُصحح)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_to_imported'])) {
    session_start();
    $contacts = $_SESSION['imported_contacts'] ?? [];
    $message = $_POST['imported_message'] ?? '';
    $sendResults = [];
    $successCount = 0;
    
    foreach ($contacts as $contact) {
        $phone = $contact['phone'];
        
        // تعريف المتغيرات هنا ✅
        $vars = [
            '{name}' => $contact['name'] ?? '',
            '{phone}' => $phone,
            '{company}' => $contact['company'] ?? '',
            '{business_type}' => $contact['business_type'] ?? '',
            '{city}' => $contact['city'] ?? '',
            '{email}' => $contact['email'] ?? ''
        ];
        
        $personalizedMsg = str_replace(array_keys($vars), array_values($vars), $message);
        
        $result = sendWhatsAppMessage($phone, $personalizedMsg);
        $sendResults[$phone] = $result['success'] ? 'تم الإرسال بنجاح' : 'فشل الإرسال: ' . ($result['error'] ?? 'خطأ غير معروف');
        if ($result['success']) $successCount++;
        
        // حفظ العميل في النظام
        if (!file_exists("customers/{$phone}.json")) {
            $customerData = [
                'phone' => $phone,
                'name' => $contact['name'] ?? '',
                'company' => $contact['company'] ?? '',
                'business_type' => $contact['business_type'] ?? '',
                'city' => $contact['city'] ?? '',
                'email' => $contact['email'] ?? '',
                'status' => 'new',
                'created_at' => time(),
                'last_contact' => time(),
                'source' => 'imported_file',
                'conversation_count' => 0,
                'interests' => [],
                'notes' => []
            ];
            file_put_contents("customers/{$phone}.json", json_encode($customerData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
        }
        
        usleep(500000); // تأخير 0.5 ثانية
    }
    
    unset($_SESSION['imported_contacts']);
    
    echo json_encode([
        'success' => true,
        'total' => count($contacts),
        'sent' => $successCount,
        'results' => $sendResults
    ]);
    exit;
}

// إصلاح الإرسال الجماعي العادي أيضًا
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['selected_phones'])) {
    $data = json_decode($_POST['selected_phones'], true);
    $phones = $data['phones'] ?? [];
    $platform = $data['platform'] ?? 'whatsapp';
    $message = $data['message'] ?? $_POST['message_content'];
    $sendResults = [];
    $successCount = 0;
    
    foreach ($phones as $ph) {
        $customerData = file_exists("customers/{$ph}.json") ? json_decode(file_get_contents("customers/{$ph}.json"), true) : [];
        
        // تعريف المتغيرات هنا أيضًا ✅
        $vars = [
            '{phone}' => $ph,
            '{business_type}' => $customerData['business_type'] ?? '',
            '{name}' => $customerData['name'] ?? '',
            '{company}' => $customerData['company'] ?? '',
        ];
        
        $personalizedMsg = str_replace(array_keys($vars), array_values($vars), $message);
        
        $success = false;
        $errorMsg = '';
        
        if ($platform === 'whatsapp' || $platform === 'both') {
            $result = sendWhatsAppMessage($ph, $personalizedMsg);
            $success = $result['success'];
            if (!$success) $errorMsg = $result['error'] ?? '';
        }
        
        if ($platform === 'messenger' || ($platform === 'both' && !$success)) {
            $result = sendMessengerMessage($ph, $personalizedMsg);
            if ($result['success']) {
                $success = true;
                $errorMsg = '';
            } else if (!$success) {
                $errorMsg = $result['error'] ?? '';
            }
        }
        
        $sendResults[$ph] = $success ? 'تم الإرسال بنجاح' : 'فشل الإرسال: ' . $errorMsg;
        if ($success) $successCount++;
        
        usleep(500000); // تأخير 0.5 ثانية
    }
    
    // عرض النتائج
    echo "<script>showNotif('تم إرسال {$successCount} رسالة من أصل " . count($phones) . "', 'success');</script>";
}


// تحميل بيانات العملاء/الشات
$customers = $biz = $interests = $intents = $statuses = [];
$customerMap = [];
foreach (glob(__DIR__.'/../customers/*.json') as $file){
    $phone = basename($file,'.json');
    $data  = json_decode(file_get_contents($file),true);
    if(!is_array($data)) continue;
    $customers[] = ['phone'=>$phone,'data'=>$data];
    $customerMap[$phone] = $data;
    if(!empty($data['business_type']) && !in_array($data['business_type'],$biz)) $biz[]=$data['business_type'];
    if(!empty($data['interests'])) foreach($data['interests'] as $i) if(!in_array($i,$interests)) $interests[]=$i;
    if(!empty($data['last_intent']) && !in_array($data['last_intent'],$intents)) $intents[]=$data['last_intent'];
    if(!empty($data['status']) && !in_array($data['status'],$statuses)) $statuses[]=$data['status'];
}
$chatFiles = [];
foreach(glob(__DIR__.'/../chats/*.json') as $file){
    $phone = basename($file,'.json');
    $data = json_decode(file_get_contents($file), true);
    if(is_array($data)) $chatFiles[$phone] = $data;
}

// ==== إحصائيات وتحليلات =====
$today = strtotime('today');
$stats = [
    'count'          => count($customers),
    'contactedToday' => 0,
    'quotes'         => 0,
    'hot'            => 0,
    'wEmail'         => 0,
    'wCity'          => 0,
    'wCompany'       => 0,
    'interested'     => 0,
    'scheduled'      => 0
];
foreach($customers as $c){
    $d=$c['data'];
    if(!empty($d['last_contact']) && $d['last_contact']>$today) $stats['contactedToday']++;
    if(($d['last_intent']??'')==='quote_request') $stats['quotes']++;
    if(in_array($d['last_intent']??'', ['quote_request','support_request'])) $stats['hot']++;
    if(!empty($d['email']))   $stats['wEmail']++;
    if(!empty($d['city']))    $stats['wCity']++;
    if(!empty($d['company'])) $stats['wCompany']++;
    if(($d['status']??'')=='interested') $stats['interested']++;
    if(!empty($d['scheduled_meeting'])) $stats['scheduled']++;
}
// اتجاهات إحصائية وهمية (يمكن تعديلها لتصبح واقعية مستقبلا)
$trends = [
    'totalCustomers' => 12,
    'contactedToday' => 8,
    'quotes' => 15,
    'scheduled' => 10
];
// إحصاء رسائل المحادثات
$chatStats = ['totalMessages'=>0,'userMessages'=>0,'botMessages'=>0,'avgLength'=>0];
$totalLength = 0;
foreach($chatFiles as $phone => $chat) {
    foreach($chat as $message) {
        if(!empty($message['content'])) {
            $chatStats['totalMessages']++;
            $totalLength += mb_strlen($message['content'], 'UTF-8');
            if($message['role'] === 'user') $chatStats['userMessages']++;
            elseif(in_array($message['role'], ['assistant', 'bot'])) $chatStats['botMessages']++;
        }
    }
}
$chatStats['avgLength'] = $chatStats['totalMessages'] > 0 ? round($totalLength / $chatStats['totalMessages']) : 0;

// ========== النوت والتفاصيل المخصصة =============
function getDefaultCustomerData($phone){
    return [
        'phone' => $phone,
        'platform_id' => $phone,
        'platform' => '',
        'phone_real' => '',
        'business_type' => '',
        'interests' => [],
        'conversation_count' => 0,
        'notes' => [],
        'qualification_status' => 'new',
        'lead_score' => 0,
        'created_at' => time(),
        'last_contact' => time(),
        'conversion_signals' => [],
        'orders' => [],
        'orders_count' => 0,
        'last_order_id' => null,
        'last_order_status' => '',
        'last_order_at' => null,
        'last_order_phone' => '',
        'last_order_platform' => '',
        'last_order_summary' => '',
        'note' => '',
        'custom_details' => '',
        'followup_date' => null,
    ];
}
if(isset($_POST['save_note'], $_POST['phone'], $_POST['note'])){
    $ph = preg_replace('/[^\d]/','',$_POST['phone']);
    $f  = "../customers/$ph.json";
    if(file_exists($f)){
        $defaults = getDefaultCustomerData($ph);
        $data = json_decode(file_get_contents($f),true);
        $data = array_merge($defaults, (array)$data);
        $data['note'] = $_POST['note'];
        file_put_contents($f, json_encode($data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
        echo json_encode(['ok'=>1]);
    } else {
        echo json_encode(['ok'=>0]);
    }
    exit;
}
if(isset($_POST['save_custom_details'], $_POST['phone'], $_POST['details'])){
    $ph = preg_replace('/[^\d]/','',$_POST['phone']);
    $f  = "../customers/$ph.json";
    if(file_exists($f)){
        $defaults = getDefaultCustomerData($ph);
        $data = file_exists($f) ? json_decode(file_get_contents($f),true) : [];
        $data = array_merge($defaults, (array)$data);
        $data['custom_details'] = $_POST['details'];
        file_put_contents($f, json_encode($data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
        echo json_encode(['ok'=>1]);
    } else echo json_encode(['ok'=>0]);
    exit;
}
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>Smart Logic CRM Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Tajawal:wght@400;600;700&display=swap" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
:root {
    --primary: #2fa17a;
    --accent: #0d6efd;
    --bg: #f4f5f7;
    --dark-bg: #1f1f1f;
    --dark-panel: #282b30;
    --border: #e1e4eb;
    --light: #e8f6ef;
    --text: #24292f;
    --text-dark: #eee;
    --danger: #ea5455;
    --success: #28a745;
    --info: #00b894;
    --warn: #ffbe76;
    --status-new: #e3f8ff;
    --status-interested: #fff7e0;
    --status-negotiation: #e6fff1;
    --status-closed: #d9f9c7;
    --status-not_interested: #ffd6d6;
    --status-waiting: #f1f0fd;
    --status-callback: #f3e9f6;
    --status-other: #f8f8f8;
    --panel-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    --transition: all 0.3s ease;
}

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

html, body {
    font-family: 'Tajawal', Arial, sans-serif;
    color: var(--text);
    background: var(--bg);
    height: 100%;
    font-size: 16px;
    line-height: 1.6;
}

a {
    color: var(--accent);
    text-decoration: none;
}

.btn {
    border: none;
    border-radius: 6px;
    padding: 10px 20px;
    font-weight: 600;
    cursor: pointer;
    transition: var(--transition);
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn:hover {
    opacity: 0.9;
    transform: translateY(-2px);
}

.btn-primary {
    background: var(--primary);
    color: #fff;
}

.btn-secondary {
    background: var(--accent);
    color: #fff;
}

.btn-danger {
    background: var(--danger);
    color: #fff;
}

.btn-dark {
    background: #2c2c2c;
    color: #fff;
}

.btn-outline {
    background: transparent;
    border: 2px solid var(--primary);
    color: var(--primary);
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 22px;
    background: #fff;
    border-bottom: 1px solid var(--border);
    position: sticky;
    top: 0;
    z-index: 100;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.header img {
    height: 36px;
    margin-left: 12px;
}

.header .actions {
    display: flex;
    gap: 12px;
}

.panel {
    background: #fff;
    border-radius: 16px;
    box-shadow: var(--panel-shadow);
    padding: 20px;
    margin-bottom: 20px;
    transition: var(--transition);
}

.stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.stat {
    background: var(--light);
    padding: 20px;
    border-radius: 12px;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    transition: var(--transition);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.stat:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.stat strong {
    font-size: 2rem;
    display: block;
    margin: 8px 0;
    color: var(--primary);
}

.stat span {
    font-size: 0.95rem;
    color: #555;
}

.stat.small strong {
    font-size: 1.5rem;
}

.stat.important {
    background: #fff8e6;
}

.stat.lead {
    background: #e6f9ff;
}

.stat.email {
    background: #eef8e7;
}

.stat.city {
    background: #f8edff;
}

.stat.company {
    background: #fff7e6;
}

.stat.interested {
    background: var(--status-interested);
}

.filters {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    margin-bottom: 20px;
    align-items: center;
}

.filters input, .filters select {
    padding: 10px 15px;
    border: 1px solid var(--border);
    border-radius: 8px;
    font-size: 1rem;
    flex: 1;
    min-width: 180px;
    background: #fff;
}

.filters input:focus, .filters select:focus {
    border-color: var(--primary);
    outline: none;
    box-shadow: 0 0 0 3px rgba(47, 161, 122, 0.1);
}

.tabs {
    display: flex;
    margin-bottom: 20px;
    border-bottom: 1px solid var(--border);
}

.tab {
    padding: 12px 24px;
    border-bottom: 3px solid transparent;
    cursor: pointer;
    font-size: 1.1rem;
    font-weight: 600;
    transition: var(--transition);
}

.tab:hover {
    color: var(--primary);
}

.tab.active {
    color: var(--primary);
    border-bottom-color: var(--primary);
    background: rgba(47, 161, 122, 0.05);
}

.table-wrap {
    overflow: auto;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

table {
    width: 100%;
    border-collapse: collapse;
    background: #fff;
    min-width: 1200px;
}

th, td {
    padding: 14px 10px;
    border: 1px solid var(--border);
    text-align: center;
    font-size: 0.95rem;
}

th {
    background: #f8f9fa;
    font-weight: 700;
    color: #444;
}

tr:nth-child(even) {
    background: #f8fafc;
}

tr:hover {
    background: #edf7f3 !important;
}

.quick-actions {
    display: flex;
    gap: 8px;
    justify-content: center;
}

.quick-actions button {
    padding: 8px;
    border-radius: 8px;
    background: #f0f7ff;
    border: none;
    color: var(--accent);
    cursor: pointer;
    transition: var(--transition);
    display: flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
}

.quick-actions button:hover {
    background: var(--accent);
    color: white;
}

.tag {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 0.85rem;
    background: #e9f0ea;
    margin-left: 4px;
    font-weight: 600;
}

.intent-quote {
    background: var(--warn);
    color: #333;
}

.intent-support {
    background: var(--info);
    color: white;
}

.hot-lead {
    color: var(--danger);
    font-weight: bold;
    font-size: 1.2rem;
}

.status-badge {
    display: inline-block;
    padding: 5px 14px;
    border-radius: 20px;
    font-size: 0.95em;
    margin: 0 2px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    transition: var(--transition);
}

.status-new {
    background: var(--status-new);
}

.status-interested {
    background: var(--status-interested);
}

.status-negotiation {
    background: var(--status-negotiation);
}

.status-closed {
    background: var(--status-closed);
}

.status-not_interested {
    background: var(--status-not_interested);
}

.status-waiting {
    background: var(--status-waiting);
}

.status-callback {
    background: var(--status-callback);
}

.status-other {
    background: var(--status-other);
}

.modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,.5);
    align-items: center;
    justify-content: center;
    z-index: 1000;
    backdrop-filter: blur(3px);
}

.modal.show {
    display: flex;
}

.modal-content {
    background: #fff;
    border-radius: 16px;
    max-width: 700px;
    width: 95vw;
    padding: 30px;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    position: relative;
}

.close-btn {
    cursor: pointer;
    font-size: 24px;
    position: absolute;
    top: 15px;
    left: 20px;
    color: #777;
    transition: var(--transition);
}

.close-btn:hover {
    color: var(--danger);
}

.chat-log {
    background: #ece5dd;
    border-radius: 12px;
    padding: 20px 15px;
    max-height: 50vh;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 15px;
    font-size: 1rem;
    margin-top: 20px;
}

.whatsapp-bubble {
    max-width: 85%;
    padding: 12px 18px;
    border-radius: 18px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    word-break: break-word;
    line-height: 1.6;
    position: relative;
}

.bubble-user {
    align-self: flex-end;
    background: linear-gradient(120deg, #dcf8c6 60%, #c8f0b9 100%);
    border-bottom-right-radius: 4px;
}

.bubble-bot {
    align-self: flex-start;
    background: linear-gradient(120deg, #fff 80%, #f1fdf6 100%);
    border-bottom-left-radius: 4px;
    color: #0b6b47;
}

.bubble-meta {
    font-size: 0.8rem;
    color: #777;
    margin-top: 5px;
    display: block;
    text-align: left;
    direction: ltr;
}

.bubble-meta-user {
    text-align: right;
}

.dashboard-container {
    max-width: 1600px;
    margin: 0 auto;
    padding: 20px;
}

.summary-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    padding: 15px 20px;
    border-radius: 12px;
    margin-bottom: 20px;
    box-shadow: var(--panel-shadow);
    font-weight: 600;
    color: #555;
}

.summary-bar .info {
    display: flex;
    gap: 20px;
}

.summary-bar .actions {
    display: flex;
    gap: 10px;
}

.export-btn {
    background: #28a745;
    color: white;
    padding: 8px 15px;
    border-radius: 6px;
    cursor: pointer;
    transition: var(--transition);
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
}

.export-btn:hover {
    background: #218838;
}

.variables-list {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    margin: 15px 0;
    font-size: 0.9rem;
}

.variables-list h4 {
    margin-bottom: 10px;
    color: #555;
    font-size: 1rem;
}

.variable-item {
    display: inline-block;
    background: #e9ecef;
    padding: 4px 10px;
    border-radius: 4px;
    margin: 0 5px 5px 0;
    font-family: monospace;
    font-size: 0.85rem;
}

.analytics-highlights {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.highlight-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: var(--panel-shadow);
    display: flex;
    flex-direction: column;
    position: relative;
    overflow: hidden;
}

.highlight-card h3 {
    color: #555;
    margin-bottom: 15px;
    font-size: 1.2rem;
    display: flex;
    align-items: center;
    gap: 10px;
}

.highlight-card .value {
    font-size: 2.5rem;
    font-weight: 700;
    color: var(--primary);
    margin: 10px 0;
}

.trend {
    display: flex;
    align-items: center;
    gap: 5px;
    color: var(--success);
    font-weight: 600;
    font-size: 0.9rem;
    padding: 4px 8px;
    background: rgba(40, 167, 69, 0.1);
    border-radius: 12px;
    margin-top: 5px;
    align-self: flex-start;
}

.trend.down {
    color: var(--danger);
    background: rgba(234, 84, 85, 0.1);
}

.chart-container {
    height: 300px;
    margin: 20px 0;
}

/* Chat Viewer Styles */
.chat-viewer {
    display: flex;
    height: 70vh;
    border-radius: 12px;
    overflow: hidden;
    background: #fff;
    box-shadow: var(--panel-shadow);
}

.chat-list {
    width: 300px;
    border-right: 1px solid var(--border);
    overflow-y: auto;
    background: #f8f9fa;
}

.chat-list-search {
    padding: 15px;
    background: #fff;
    border-bottom: 1px solid var(--border);
}

.chat-list-item {
    padding: 12px 15px;
    border-bottom: 1px solid var(--border);
    cursor: pointer;
    transition: background-color 0.2s;
}

.chat-list-item:hover {
    background: #edf7f3;
}

.chat-list-item.active {
    background: var(--light);
    border-left: 4px solid var(--primary);
}

.chat-list-item .phone {
    font-weight: bold;
    margin-bottom: 5px;
    color: var(--text);
}
.chat-list-item .chat-id {
    font-size: 0.85rem;
    color: #888;
    margin-bottom: 4px;
    direction: ltr;
    text-align: left;
}

.chat-list-item .name {
    color: #666;
    margin-bottom: 5px;
}

.chat-list-item .last-msg {
    font-size: 0.9rem;
    color: #777;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.chat-list-item .time {
    font-size: 0.8rem;
    color: #999;
    text-align: left;
    direction: ltr;
}

.chat-display {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.chat-header {
    padding: 15px 20px;
    background: #fff;
    border-bottom: 1px solid var(--border);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.chat-messages {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    background: #f0f2f5;
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.chat-input {
    padding: 15px;
    background: #fff;
    border-top: 1px solid var(--border);
}

.chat-msg-count {
    background: var(--primary);
    color: white;
    border-radius: 50%;
    width: 24px;
    height: 24px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 0.8rem;
    margin-left: 10px;
}

.chat-bubble {
    max-width: 80%;
    padding: 12px 16px;
    border-radius: 18px;
    position: relative;
    word-break: break-word;
    line-height: 1.5;
    box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.chat-bubble-user {
    background: #dcf8c6;
    align-self: flex-end;
    margin-left: auto;
    border-bottom-right-radius: 4px;
}

.chat-bubble-bot {
    background: white;
    align-self: flex-start;
    border-bottom-left-radius: 4px;
}

.chat-bubble-system {
    background: #e6f7ff;
    align-self: center;
    max-width: 90%;
    margin: 10px auto;
    font-size: 0.9rem;
    text-align: center;
}

.chat-bubble-time {
    font-size: 0.75rem;
    color: #777;
    margin-top: 5px;
    text-align: right;
}

/* Responsive */
@media (max-width: 992px) {
    .stats {
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    }
    
    .filters {
        flex-direction: column;
        align-items: stretch;
    }
    
    .tabs {
        overflow-x: auto;
        white-space: nowrap;
    }
    
    .chat-viewer {
        flex-direction: column;
        height: auto;
    }
    
    .chat-list {
        width: 100%;
        height: 300px;
        border-right: none;
        border-bottom: 1px solid var(--border);
    }
}

@media (max-width: 768px) {
    .header {
        flex-direction: column;
        gap: 15px;
        padding: 15px;
    }
    
    .header .actions {
        width: 100%;
        justify-content: center;
    }
    
    .panel {
        padding: 15px;
    }
    
    .highlight-card .value {
        font-size: 2rem;
    }
}

body.dark {
    background: var(--dark-bg);
    color: var(--text-dark);
}

body.dark .panel,
body.dark table,
body.dark .modal-content,
body.dark .chat-viewer,
body.dark .chat-list {
    background: var(--dark-panel);
    color: var(--text-dark);
}

body.dark .header {
    background: #2b2e34;
    color: #fff;
}

body.dark .filter input,
body.dark .filter select {
    background: #32353b;
    color: var(--text-dark);
    border-color: #444;
}

body.dark .whatsapp-bubble {
    box-shadow: none;
}

body.dark .bubble-bot {
    background: #353c37;
}

body.dark .bubble-user {
    background: #256f46;
}

body.dark .stat {
    background: #2a2d32;
    color: var(--text-dark);
}

body.dark .stat span {
    color: #bbb;
}

body.dark .variables-list {
    background: #2a2d32;
    color: var(--text-dark);
}

body.dark .variable-item {
    background: #3a3d44;
    color: #eee;
}

body.dark .chat-list {
    background: #2a2d32;
    border-right: 1px solid #444;
}

body.dark .chat-list-item {
    border-bottom: 1px solid #444;
}

body.dark .chat-list-item:hover {
    background: #353c37;
}

body.dark .chat-list-item.active {
    background: #2c3e33;
    border-left: 4px solid var(--primary);
}

body.dark .chat-messages {
    background: #1e1e1e;
}

body.dark .chat-bubble-bot {
    background: #353c37;
    color: #eee;
}

body.dark .chat-bubble-user {
    background: #2c3e33;
    color: #eee;
}

body.dark .chat-bubble-system {
    background: #2a3d4e;
    color: #eee;
}
/* Modal Base */
.modal {
    display: none; /* Hidden by default */
    position: fixed; 
    z-index: 1000; 
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0,0,0,0.5); /* Black w/ opacity */
}

/* Modal Content Box */
.modal-content {
    background-color: #fefefe;
    margin: 10% auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
    max-width: 500px;
    border-radius: 8px;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    animation: fadeIn 0.3s;
}

@keyframes fadeIn {
    from {opacity: 0; transform: translateY(-20px);}
    to {opacity: 1; transform: translateY(0);}
}

/* Header, Body, Footer */
.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}
.modal-header h2 { margin: 0; }
.modal-body { padding: 15px 5px; }
.modal-footer {
    padding-top: 10px;
    border-top: 1px solid #eee;
    text-align: right;
}

/* Close Button */
.close-button {
    color: #aaa;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
}
.close-button:hover, .close-button:focus {
    color: black;
}

/* Form Styling */
#scheduleForm label {
    display: block;
    margin-top: 10px;
    margin-bottom: 5px;
    font-weight: bold;
}
#scheduleForm input[type="date"],
#scheduleForm input[type="time"],
#scheduleForm textarea {
    width: 100%;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box; /* Important */
}

/* Buttons */
.button-primary, .button-secondary {
    padding: 10px 15px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 16px;
}
.button-primary {
    background-color: #007bff;
    color: white;
}
.button-secondary {
    background-color: #6c757d;
    color: white;
    margin-left: 10px;
}




.filters-box {
    width: 100%;
    margin-bottom: 18px;
    background: #f8f9fa;
    border-radius: 16px;
    box-shadow: 0 2px 8px #0001;
    padding: 15px 14px 8px 14px;
    direction: rtl;
}
.filters-row {
    display: flex;
    flex-wrap: wrap;
    gap: 14px;
    align-items: flex-end;
}
.filter-item {
    display: flex;
    flex-direction: column;
    min-width: 160px;
    flex: 1 1 190px;
    margin-bottom: 5px;
}
.filter-item label {
    font-size: 0.98em;
    color: #626262;
    font-weight: 600;
    margin-bottom: 6px;
    display: flex;
    align-items: center;
    gap: 5px;
}
.filter-item input, .filter-item select {
    background: #fff;
    border: 1.5px solid #e3e8ee;
    border-radius: 9px;
    padding: 8px 12px;
    font-size: 1em;
    transition: border-color .2s;
    outline: none;
    box-shadow: 0 1px 2px #0000000a;
}
.filter-item input:focus, .filter-item select:focus {
    border-color: #2fa17a;
    box-shadow: 0 0 0 2px #2fa17a22;
}
.filter-date .date-range {
    display: flex;
    align-items: center;
}
.filter-date input[type="date"] {
    min-width: 100px;
}
.filter-actions {
    display: flex;
    align-items: flex-end;
    height: 100%;
    margin-bottom: 0;
}
.filter-actions .btn {
    height: 42px;
    padding: 0 20px;
    font-size: 1.2em;
}

@media (max-width: 900px) {
    .filters-row { flex-direction: column; gap: 12px; }
    .filter-item, .filter-date { width: 100%; min-width: 0; }
    .filter-actions { width: 100%; justify-content: flex-end; }
}
body.dark .filters-box {
    background: #23272b;
    box-shadow: 0 2px 12px #0005;
}
body.dark .filter-item input, 
body.dark .filter-item select {
    background: #2d3137;
    border-color: #444c55;
    color: #e2eaf2;
}
body.dark .filter-item label { color: #d4e1f0; }



/* Import Modal Styles */
.import-preview-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.9rem;
    margin-top: 15px;
}

.import-preview-table th,
.import-preview-table td {
    padding: 8px 12px;
    border: 1px solid #ddd;
    text-align: right;
}

.import-preview-table th {
    background: #f8f9fa;
    font-weight: bold;
}

.import-preview-table tr:nth-child(even) {
    background: #f9f9f9;
}

.import-stats {
    background: linear-gradient(135deg, #28a745, #20c997);
    color: white;
    padding: 20px;
    border-radius: 12px;
    margin: 20px 0;
    text-align: center;
}

.import-stats h4 {
    margin: 0 0 10px 0;
    font-size: 1.5rem;
}

.file-upload-zone {
    border: 2px dashed #28a745;
    padding: 40px;
    text-align: center;
    border-radius: 12px;
    transition: all 0.3s ease;
    cursor: pointer;
}

.file-upload-zone:hover {
    border-color: #1e7e34;
    background: rgba(40, 167, 69, 0.05);
}

.file-upload-zone.dragover {
    border-color: #1e7e34;
    background: rgba(40, 167, 69, 0.1);
}

/* Loader Enhancement */
.crm-loader {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
    backdrop-filter: blur(3px);
}

.crm-loader.show {
    opacity: 1;
    visibility: visible;
}

.crm-loader-icon {
    width: 50px;
    height: 50px;
    border: 4px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: #28a745;
    animation: spin 1s ease-in-out infinite;
    margin-bottom: 20px;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.crm-loader span {
    color: white;
    font-size: 1.2rem;
    font-weight: 600;
}

/* Notification Toast */
.notif-toast {
    position: fixed;
    top: 80px;
    right: 20px;
    padding: 15px 25px;
    border-radius: 8px;
    color: white;
    font-weight: 600;
    z-index: 9999;
    transform: translateX(350px);
    transition: all 0.4s ease;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    min-width: 300px;
}

.notif-toast.show {
    transform: translateX(0);
}

.notif-success {
    background: linear-gradient(135deg, #28a745, #20c997);
}

.notif-danger {
    background: linear-gradient(135deg, #dc3545, #e74c3c);
}

.notif-warning {
    background: linear-gradient(135deg, #ffc107, #fd7e14);
}

.notif-info {
    background: linear-gradient(135deg, #17a2b8, #007bff);
}

</style>
</head>
<body>
<div class="dashboard-container">
    <div class="header">
        <div style="display: flex; align-items: center;">
            <img src="https://teamsportsweareg.com/wp-content/uploads/2025/12/12989f23-d4de-46b0-b116-186a19248274-removebg-preview.png" alt="Smart Logic Logo">
            <h1>Team Sports Wear</h1>
        </div>
        <div class="actions">
            <button class="btn btn-dark" onclick="toggleDark()"><i class="fa fa-moon"></i> الوضع الليلي</button>
            <button class="btn btn-primary" onclick="location.reload()"><i class="fa fa-sync"></i> تحديث</button>
            <button class="btn btn-secondary" onclick="exportSelected()"><i class="fa fa-file-excel"></i> تصدير</button>
            <button class="btn btn-primary" onclick="showBulkComposer()"><i class="fa fa-bullhorn"></i> إرسال جماعي</button>
            <!-- في الـ header، أضف هذا الزر -->
<button class="btn btn-success" onclick="showImportModal()">
    <i class="fa fa-file-import"></i> استيراد ملف خارجي
</button>

        </div>
    </div>



<!-- نافذة تحميل ملفات خارجية -->
<!-- نافذة تحميل ملفات خارجية (محسنة) -->
<div class="modal" id="importFileModal">
    <div class="modal-content" style="max-width: 900px;">
        <span class="close-btn" onclick="hideImportModal()">&times;</span>
        
        <div id="importStep1">
            <h3><i class="fas fa-file-upload"></i> استيراد جهات اتصال من ملف خارجي</h3>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;">
                <h4><i class="fas fa-info-circle"></i> الملفات المدعومة:</h4>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 15px;">
                    <div>
                        <h5>📊 Excel (.xlsx, .xls)</h5>
                        <p>يجب أن تحتوي على أعمدة: Name, Phone, Company, Business_Type, City, Email</p>
                    </div>
                    <div>
                        <h5>📄 CSV</h5>
                        <p>نفس الأعمدة مفصولة بفواصل</p>
                    </div>
                    <div>
                        <h5>📝 TXT</h5>
                        <p>كل سطر: اسم,هاتف,شركة,نشاط,مدينة,إيميل</p>
                    </div>
                    <div>
                        <h5>📱 أرقام فقط</h5>
                        <p>كل رقم في سطر منفصل</p>
                    </div>
                </div>
                
                <div style="background: #e8f4f8; padding: 15px; border-radius: 6px; margin-top: 15px;">
                    <strong>مثال CSV:</strong><br>
                    <code style="font-size: 0.9rem;">
                        Name,Phone,Company,Business_Type,City,Email<br>
                        أحمد محمد,201234567890,شركة التقنية,تكنولوجيا,القاهرة,ahmed@company.com<br>
                        فاطمة علي,201987654321,محل تجاري,تجارة,الإسكندرية,fatma@shop.com
                    </code>
                </div>
            </div>
            
            <form id="importForm" enctype="multipart/form-data">
                <div class="file-upload-zone" onclick="document.getElementById('importFile').click()" style="margin: 20px 0;">
                    <div style="text-align: center;">
                        <i class="fas fa-cloud-upload-alt fa-3x" style="color: #28a745; margin-bottom: 15px;"></i>
                        <h4>اضغط لاختيار الملف أو اسحبه هنا</h4>
                        <p>الحد الأقصى: 10MB | الأنواع المدعومة: Excel, CSV, TXT</p>
                    </div>
                    <input type="file" id="importFile" name="external_file" 
                           accept=".xlsx,.xls,.csv,.txt" required
                           style="display: none;">
                </div>
                
                <div style="margin: 20px 0;">
                    <label><strong><i class="fas fa-file-alt"></i> نوع الملف:</strong></label>
                    <select id="fileType" name="file_type" required 
                            style="width: 100%; padding: 12px; border-radius: 8px; border: 1px solid #ddd; margin-top: 8px;">
                        <option value="">اختر نوع الملف</option>
                        <option value="excel">📊 Excel (.xlsx, .xls)</option>
                        <option value="csv">📄 CSV</option>
                        <option value="txt">📝 Text (.txt)</option>
                    </select>
                </div>
                
                <div style="text-align: center; margin-top: 30px;">
                    <button type="button" class="btn btn-primary" onclick="uploadExternalFile()" 
                            style="padding: 12px 30px; font-size: 1.1rem;">
                        <i class="fa fa-upload"></i> تحميل وتحليل الملف
                    </button>
                </div>
            </form>
        </div>
        
        <div id="importStep2" style="display: none;">
            <h3><i class="fas fa-eye"></i> معاينة البيانات المستوردة</h3>
            <div id="importPreview"></div>
            
            <div style="margin: 20px 0;">
                <h4><i class="fas fa-envelope"></i> رسالة الإرسال الجماعي:</h4>
                <div class="variables-list" style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 10px 0;">
                    <strong><i class="fas fa-tags"></i> متغيرات متاحة:</strong>
                    <div style="margin-top: 10px;">
                        <span class="variable-item">{name}</span>
                        <span class="variable-item">{phone}</span>
                        <span class="variable-item">{company}</span>
                        <span class="variable-item">{business_type}</span>
                        <span class="variable-item">{city}</span>
                        <span class="variable-item">{email}</span>
                    </div>
                </div>
                <textarea id="importedMessage" rows="6" 
                          style="width: 100%; padding: 15px; border-radius: 8px; border: 1px solid #ddd; font-family: 'Tajawal';" 
                          placeholder="مرحباً {name}، نتواصل معك من {company} بخصوص خدماتنا في مجال {business_type}...">مرحباً {name} 👋

نتواصل معك من شركة Smart Logic بخصوص خدماتنا في مجال التكنولوجيا والذكاء الاصطناعي.

نحن متخصصون في:
🤖 تطوير أنظمة الذكاء الاصطناعي
💻 تطوير المواقع والتطبيقات  
📊 أنظمة إدارة العملاء (CRM)
🛒 التجارة الإلكترونية

هل تود معرفة المزيد عن خدماتنا؟

🌐 smartlogiceg.com
📱 +201144470365</textarea>
            </div>
            
            <div style="text-align: center; margin-top: 30px; display: flex; gap: 15px; justify-content: center;">
                <button class="btn btn-secondary" onclick="backToStep1()" style="padding: 12px 25px;">
                    <i class="fas fa-arrow-right"></i> العودة
                </button>
                <button class="btn btn-primary" onclick="sendToImported()" style="padding: 12px 25px;">
                    <i class="fa fa-paper-plane"></i> إرسال للجميع
                </button>
            </div>
        </div>
        
        <div id="importStep3" style="display: none;">
            <h3><i class="fas fa-check-circle"></i> نتائج الإرسال</h3>
            <div id="importResults"></div>
            <div style="text-align: center; margin-top: 30px;">
                <button class="btn btn-primary" onclick="hideImportModal()" style="padding: 12px 30px;">
                    <i class="fas fa-times"></i> إغلاق
                </button>
            </div>
        </div>
    </div>
</div>


    <?php if (!empty($sendResults)): ?>
    <div class="panel" style="background: #d4f0d4; border: 1px solid #28a745;">
        <strong>نتائج الإرسال الجماعي:</strong>
        <ul style="margin-top: 10px;">
            <?php foreach ($sendResults as $ph => $st): ?>
            <li><?=htmlspecialchars($ph)?>: <?=htmlspecialchars($st)?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>

    <div class="analytics-highlights">
        <div class="highlight-card">
            <h3><i class="fas fa-users"></i> إجمالى العملاء</h3>
            <div class="value"><?= $stats['count'] ?></div>
            <div class="trend <?= $trends['totalCustomers'] < 0 ? 'down' : '' ?>">
                <i class="fas fa-arrow-<?= $trends['totalCustomers'] >= 0 ? 'up' : 'down' ?>"></i>
                <?= abs($trends['totalCustomers']) ?>% 
                <?= $trends['totalCustomers'] >= 0 ? 'زيادة' : 'انخفاض' ?> هذا الشهر
            </div>
        </div>
        
        <div class="highlight-card">
            <h3><i class="fas fa-comments"></i> تواصل اليوم</h3>
            <div class="value"><?= $stats['contactedToday'] ?></div>
            <div class="trend <?= $trends['contactedToday'] < 0 ? 'down' : '' ?>">
                <i class="fas fa-arrow-<?= $trends['contactedToday'] >= 0 ? 'up' : 'down' ?>"></i>
                <?= abs($trends['contactedToday']) ?>% 
                <?= $trends['contactedToday'] >= 0 ? 'زيادة' : 'انخفاض' ?> عن الأمس
            </div>
        </div>
        
        <div class="highlight-card">
            <h3><i class="fas fa-file-invoice-dollar"></i> طلبات عرض سعر</h3>
            <div class="value"><?= $stats['quotes'] ?></div>
            <div class="trend <?= $trends['quotes'] < 0 ? 'down' : '' ?>">
                <i class="fas fa-arrow-<?= $trends['quotes'] >= 0 ? 'up' : 'down' ?>"></i>
                <?= abs($trends['quotes']) ?>% 
                <?= $trends['quotes'] >= 0 ? 'زيادة' : 'انخفاض' ?> هذا الأسبوع
            </div>
        </div>
        
        <div class="highlight-card">
            <h3><i class="fas fa-calendar-check"></i> مواعيد مجدولة</h3>
            <div class="value"><?= $stats['scheduled'] ?></div>
            <div class="trend <?= $trends['scheduled'] < 0 ? 'down' : '' ?>">
                <i class="fas fa-arrow-<?= $trends['scheduled'] >= 0 ? 'up' : 'down' ?>"></i>
                <?= abs($trends['scheduled']) ?>% 
                <?= $trends['scheduled'] >= 0 ? 'زيادة' : 'انخفاض' ?> هذا الشهر
            </div>
        </div>
    </div>

    <div class="panel">
        <div class="tabs">
            <div id="tabCustomers" class="tab active"><i class="fas fa-users"></i> العملاء</div>
            <div id="tabChats" class="tab"><i class="fas fa-comments"></i> المحادثات</div>
            <div id="tabAnalytics" class="tab"><i class="fas fa-chart-line"></i> التحليلات</div>
        </div>
        
        <div class="summary-bar">
            <div class="info">
                <div>عرض <strong><?= count($customers) ?></strong> عميل</div>
                <div>تم تحديد <strong id="selectedCount">0</strong> عميل</div>
            </div>
            <div class="actions">
                <div class="export-btn" onclick="exportSelected()">
                    <i class="fa fa-file-excel"></i> تصدير المحددين
                </div>
            </div>
        </div>
        
<!-- فلتر متطور للـ CRM - Responsive ومميز -->
<div class="filters-box">
    <div class="filters-row">
        <div class="filter-item">
            <label for="searchInput"><i class="fas fa-search"></i> بحث شامل</label>
            <input id="searchInput" placeholder="اسم، هاتف، نشاط، إيميل..." autocomplete="off">
        </div>
        <div class="filter-item">
            <label for="businessFilter"><i class="fa fa-building"></i> النشاط</label>
            <select id="businessFilter">
                <option value="">كل الأنشطة</option>
                <?php foreach($biz as $b) echo "<option>$b</option>"; ?>
            </select>
        </div>
        <div class="filter-item">
            <label for="interestFilter"><i class="fa fa-heart"></i> الاهتمامات</label>
            <select id="interestFilter">
                <option value="">كل الاهتمامات</option>
                <?php foreach($interests as $i) echo "<option>$i</option>"; ?>
            </select>
        </div>
        <div class="filter-item">
            <label for="intentFilter"><i class="fa fa-lightbulb"></i> النية</label>
            <select id="intentFilter">
                <option value="">كل النوايا</option>
                <?php foreach($intents as $n) echo "<option>$n</option>"; ?>
            </select>
        </div>
        <div class="filter-item">
            <label for="statusFilter"><i class="fa fa-signal"></i> الحالة</label>
            <select id="statusFilter">
                <option value="">كل الحالات</option>
                <?php foreach($status_list as $val=>$txt) echo "<option value='$val'>$txt</option>"; ?>
            </select>
        </div>
        <div class="filter-item">
  <label for="platformFilter"><i class="fab fa-whatsapp"></i> اختر المنصة:</label>
  <select id="platformFilter" style="min-width:120px;">
    <option value="">الكل</option>
    <option value="whatsapp">واتساب</option>
    <option value="messenger">ماسنجر</option>
    <option value="instagram">انستجرام</option>
    <option value="comments">تعليقات</option>
  </select>


        </div>
        <div class="filter-item filter-date">
            <label><i class="fa fa-calendar"></i> المدى الزمني</label>
            <div class="date-range">
                <input type="date" id="fromDate" title="من تاريخ" placeholder="من">
                <span style="margin: 0 5px;">–</span>
                <input type="date" id="toDate" title="إلى تاريخ" placeholder="إلى">
            </div>
        </div>
        <div class="filter-actions">
            <button class="btn btn-outline" onclick="toggleSelectAll()" title="تحديد الكل">
                <i class="fas fa-check-square"></i>
            </button>
        </div>
    </div>
</div>

        
        <div id="customersTab">
            <div class="table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th></th>
                            <th>اسم</th>
                            <th>هاتف فعلي</th>
                            <th>ID</th>
                            <th>منصة</th>
                            <th>إيميل</th>
                            <th>مدينة</th>
                            <th>شركة</th>
                            <th>نشاط</th>
                            <th>اهتمامات</th>
                            <th>آخر رسالة</th>
                            <th>نية</th>
                            <th>حالة</th>
                            <th>محادثات</th>
                            <th>آخر تواصل</th>
                            <th>آخر طلب</th>
                            <th>عدد الطلبات</th>
                            <th>ملاحظات</th>
                            <th>تفاصيل مخصصة</th>
                            <th>إجراءات</th>
                        </tr>
                    </thead>
                    <tbody id="customerTableBody"></tbody>
                </table>
            </div>
        </div>
        
        <div id="chatsTab" style="display:none">
            <div class="chat-viewer">
                <div class="chat-list">
                    <div class="chat-list-search">
                        <input type="text" id="chatSearch" placeholder="بحث بالهاتف أو الاسم..." style="width:100%; padding:10px; border-radius:6px; border:1px solid #ddd;">
                    </div>
                    <ul id="chatList">
                        <!-- Chat list will be populated by JavaScript -->
                    </ul>
                </div>
                <div class="chat-display">
                    <div class="chat-header">
                        <div>
                            <strong id="chatCustomerName">حدد عميلاً لعرض المحادثة</strong>
                            <span id="chatCustomerPhone"></span>
                        </div>
                        <div>
                            <span id="chatMsgCount">0 رسالة</span>
                        </div>
                    </div>
                    <div class="chat-messages" id="chatMessages">
                        <!-- Chat messages will be displayed here -->
                    </div>
                </div>
            </div>
        </div>
        
        <div id="analyticsTab" style="display:none">
            <div class="panel">
                <h3 style="margin-bottom: 20px; color: #444; border-bottom: 1px solid #eee; padding-bottom: 10px;">
                    <i class="fas fa-chart-pie"></i> تحليل العملاء
                </h3>
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                    <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: var(--panel-shadow);">
                        <h4 style="margin-bottom: 15px; color: #555;">التوزيع حسب الحالة</h4>
                        <div class="chart-container">
                            <canvas id="statusChart" height="250"></canvas>
                        </div>
                    </div>
                    
                    <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: var(--panel-shadow);">
                        <h4 style="margin-bottom: 15px; color: #555;">التوزيع حسب النشاط</h4>
                        <div class="chart-container">
                            <canvas id="businessChart" height="250"></canvas>
                        </div>
                    </div>
                </div>
                
                <div style="margin-top: 30px;">
                    <h4 style="margin-bottom: 15px; color: #555;">إحصائيات المحادثات</h4>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px;">
                        <div class="stat">
                            <i class="fas fa-comments fa-2x"></i>
                            <strong><?= $chatStats['totalMessages'] ?></strong>
                            <span>إجمالي الرسائل</span>
                        </div>
                        <div class="stat">
                            <i class="fas fa-user fa-2x"></i>
                            <strong><?= $chatStats['userMessages'] ?></strong>
                            <span>رسائل العملاء</span>
                        </div>
                        <div class="stat">
                            <i class="fas fa-robot fa-2x"></i>
                            <strong><?= $chatStats['botMessages'] ?></strong>
                            <span>ردود البوت</span>
                        </div>
                        <div class="stat">
                            <i class="fas fa-ruler fa-2x"></i>
                            <strong><?= $chatStats['avgLength'] ?></strong>
                            <span>متوسط طول الرسالة</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal" id="bulkComposerModal">
    <div class="modal-content">
        <span class="close-btn" onclick="hideBulkComposer()">×</span>
        <h3><i class="fas fa-bullhorn"></i> رسالة جماعية</h3>
        <div id="selectedCountBulk" style="margin: 15px 0; font-weight: bold; color: #555;"></div>
        <!-- في نافذة bulkComposerModal أضف هذا قبل textarea الرسالة -->
<div style="margin: 15px 0;">
    <label><strong>المنصة:</strong></label>
    <select id="platformChoice" style="width: 100%; padding: 10px; border-radius: 8px; margin-top: 5px;">
        <option value="whatsapp">واتساب</option>
        <option value="messenger">ماسنجر</option>
        <option value="both">الاثنين معاً</option>
    </select>
</div>

        <div class="variables-list">
            <h4>متغيرات يمكن استخدامها:</h4>
            <div>
                <span class="variable-item">{name}</span>
                <span class="variable-item">{phone}</span>
                <span class="variable-item">{business_type}</span>
                <span class="variable-item">{company}</span>
            </div>
        </div>
        
        <form method="POST" id="bulkForm">
            <textarea name="message_content" rows="6" style="width:100%; padding: 15px; border-radius: 8px; border: 1px solid #ddd;" placeholder="رسالتك مع {name} , {phone} ..." required></textarea>
            <input type="hidden" name="selected_phones" id="selectedPhonesBulk">
            
            <div style="text-align:right; margin-top:20px; display: flex; justify-content: flex-end; gap: 10px;">
                <button class="btn" onclick="hideBulkComposer();return false;">إلغاء</button>
                <button class="btn btn-primary" onclick="sendBulkMessage();return false;">
                    <i class="fa fa-paper-plane"></i> إرسال للعملاء المحددين
                </button>
            </div>
        </form>
    </div>
</div>

<div class="modal" id="chatLogModal">
    <div class="modal-content" style="max-width:700px">
        <span class="close-btn" onclick="hideChatLog()">×</span>
        <h3><i class="fas fa-comments"></i> سجل المحادثة</h3>
        <div class="chat-log" id="chatLogBody"></div>
    </div>
</div>


<!-- Modal للنوت -->
<div class="modal" id="noteModal">
  <div class="modal-content">
    <span class="close-btn" onclick="hideNoteModal()">×</span>
    <h3>ملاحظة العميل</h3>
    <textarea id="noteInput" style="width:100%;height:120px"></textarea>
<button class="btn btn-primary" onclick="saveNote(); return false;">حفظ</button>
  </div>
</div>
<!-- Modal للتفاصيل -->
<div class="modal" id="customDetailsModal">
  <div class="modal-content">
    <span class="close-btn" onclick="hideCustomDetailsModal()">×</span>
    <h3>تفاصيل مخصصة للعميل</h3>
    <textarea id="customDetailsInput" style="width:100%;height:120px"></textarea>
    <button class="btn btn-primary" onclick="saveCustomDetails()">حفظ</button>
  </div>
</div>

<div id="scheduleModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <span class="close-button">&times;</span>
            <h2>تحديد موعد المتابعة/الاجتماع</h2>
        </div>
        <div class="modal-body">
            <p>العميل: <strong id="clientPhone"></strong></p>
            <form id="scheduleForm">
                <input type="hidden" id="clientPhoneInput">
                <input type="hidden" id="statusInput">

                <label for="followupDate">التاريخ:</label>
                <input type="date" id="followupDate" name="followupDate" required>

                <label for="followupTime">الوقت:</label>
                <input type="time" id="followupTime" name="followupTime" required>

                <label for="modalNotes">ملاحظات إضافية:</label>
                <textarea id="modalNotes" name="modalNotes" rows="3" placeholder="أضف تفاصيل الموعد هنا..."></textarea>
            </form>
        </div>
        <div class="modal-footer">
            <button id="saveSchedule" class="button-primary">حفظ الموعد</button>
            <button id="cancelSchedule" class="button-secondary">إلغاء</button>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>

/****************************************************
 * Smart Logic CRM Dashboard - Premium JS
 * Highly Organized, Professional, Global Standard
 * By: [Your Company]
 ****************************************************/

/* ======= 1. Global State & Settings ======= */
const state = {
    customers: <?= json_encode($customers, JSON_UNESCAPED_UNICODE) ?>,
    customerMap: <?= json_encode($customerMap, JSON_UNESCAPED_UNICODE) ?>,
    chatFiles: <?= json_encode($chatFiles, JSON_UNESCAPED_UNICODE) ?>,
    statusList: <?= json_encode($status_list, JSON_UNESCAPED_UNICODE) ?>,
    filtered: [],
    selected: [],
    statusChart: null,
    businessChart: null,
    chatList: [],
    editingPhone: null,
    unsavedChanges: false
};

// ========== 2. Utility Functions ==========

function getPlatformId(phone, data) {
    return (data?.platform_id || phone || '').toString();
}

function getCustomerPlatform(phone, data) {
    if (data?.platform) return data.platform;
    const chat = state.chatFiles[phone] || [];
    for (let i = chat.length - 1; i >= 0; i--) {
        const p = chat[i]?.meta?.raw?.platform;
        if (p) return p;
    }
    return '';
}

function getRealPhone(phone, data) {
    const phoneReal = (data?.phone_real || '').toString();
    if (phoneReal) return phoneReal;
    const phoneField = (data?.phone || '').toString();
    const platform = getCustomerPlatform(phone, data);
    const platformId = getPlatformId(phone, data);
    if (platform === 'whatsapp' && phoneField) return phoneField;
    if (phoneField && phoneField !== platformId) return phoneField;
    return '';
}

function formatPlatformLabel(platform) {
    switch (platform) {
        case 'whatsapp': return 'واتساب';
        case 'messenger': return 'ماسنجر';
        case 'instagram': return 'انستجرام';
        case 'comments': return 'تعليقات';
        default: return platform || '-';
    }
}

/** إشعار عصري */
function showNotif(msg, type = 'success', duration = 2300) {
    let n = document.createElement('div');
    n.innerHTML = msg;
    n.className = 'notif-toast notif-' + type;
    document.body.appendChild(n);
    setTimeout(() => n.classList.add('show'), 100);
    setTimeout(() => n.classList.remove('show'), duration);
    setTimeout(() => n.remove(), duration + 600);
}

/** تحميل فوري (Loader) */
function showLoader(msg = 'جاري التحميل...') {
    let loader = document.createElement('div');
    loader.className = 'crm-loader';
    loader.innerHTML = `<div class="crm-loader-icon"></div><span>${msg}</span>`;
    document.body.appendChild(loader);
    setTimeout(() => loader.classList.add('show'), 100);
    return loader;
}
function hideLoader(loader) {
    if (!loader) return;
    loader.classList.remove('show');
    setTimeout(() => loader.remove(), 500);
}

/** التأكد من وجود تغيير غير محفوظ */
function warnUnsaved() {
    if (state.unsavedChanges) {
        return confirm('لديك تغييرات غير محفوظة. هل تريد المتابعة؟');
    }
    return true;
}

/** حفظ الفلاتر */
function saveFilters() {
    const filters = {
        search: document.getElementById('searchInput').value,
        business: document.getElementById('businessFilter').value,
        interest: document.getElementById('interestFilter').value,
        intent: document.getElementById('intentFilter').value,
        status: document.getElementById('statusFilter').value,
        from: document.getElementById('fromDate').value,
        to: document.getElementById('toDate').value
    };
    localStorage.setItem('crm-filters', JSON.stringify(filters));
}
function loadFilters() {
    try {
        const filters = JSON.parse(localStorage.getItem('crm-filters'));
        if (!filters) return;
        document.getElementById('searchInput').value = filters.search || '';
        document.getElementById('businessFilter').value = filters.business || '';
        document.getElementById('interestFilter').value = filters.interest || '';
        document.getElementById('intentFilter').value = filters.intent || '';
        document.getElementById('statusFilter').value = filters.status || '';
        document.getElementById('fromDate').value = filters.from || '';
        document.getElementById('toDate').value = filters.to || '';
    } catch { }
}

/** دعم ESC للإغلاق جميع النوافذ */
function addEscSupport() {
    document.addEventListener('keydown', function (e) {
        if (e.key === "Escape") {
            document.querySelectorAll('.modal.show').forEach(m => m.classList.remove('show'));
        }
    });
}

/* ======= 3. Customer Table & Filters ======= */
function applyFilters() {
    const term = document.getElementById('searchInput').value.toLowerCase();
    const bt = document.getElementById('businessFilter').value;
    const it = document.getElementById('interestFilter').value;
    const intent = document.getElementById('intentFilter').value;
    const st = document.getElementById('statusFilter').value;
    const fromDate = document.getElementById('fromDate').value;
    const toDate = document.getElementById('toDate').value;
    const platform = document.getElementById('platformFilter').value;

    state.filtered = state.customers.filter(c => {
        const d = c.data;
        const platformId = getPlatformId(c.phone, d);
        const realPhone = getRealPhone(c.phone, d);
        const platformValue = getCustomerPlatform(c.phone, d);
        let ok = true;
        if (term) {
            ok = ok && (
                c.phone.includes(term) ||
                platformId.includes(term) ||
                realPhone.includes(term) ||
                (d.name || '').toLowerCase().includes(term) ||
                (d.business_type || '').toLowerCase().includes(term) ||
                (d.email || '').toLowerCase().includes(term) ||
                (d.company || '').toLowerCase().includes(term)
            );
        }
        if (bt) ok = ok && d.business_type === bt;
        if (it) ok = ok && (d.interests || []).includes(it);
        if (intent) ok = ok && d.last_intent === intent;
        if (st) ok = ok && (d.status || 'new') === st;
        let ts = d.last_contact || 0;
        if (fromDate) ok = ok && (ts >= (new Date(fromDate).getTime() / 1000));
        if (toDate) ok = ok && (ts <= (new Date(toDate).getTime() / 1000) + 86399);
        if (platform) ok = ok && platformValue === platform;
        return ok;
    });

    buildChatList(state.filtered.map(c => c.phone));
    saveFilters();
    renderTable();
    updateCharts();
}

// حدث الفلاتر:
document.querySelectorAll('.filters-box input, .filters-box select').forEach(el => {
    el.addEventListener('input', applyFilters);
    el.addEventListener('change', applyFilters);
});



function renderTable() {
    const tbody = document.getElementById('customerTableBody');
    const data = state.filtered;
    tbody.innerHTML = data.length ? '' :
        `<tr><td colspan="20" style="text-align:center;padding:30px;font-size:1.1rem;color:#777;">لا توجد بيانات تطابق معايير البحث</td></tr>`;

    data.forEach(c => {
        const d = c.data;
        const p = c.phone;
        const platformId = getPlatformId(p, d);
        const realPhone = getRealPhone(p, d);
        const platformValue = getCustomerPlatform(p, d);
        const platformLabel = formatPlatformLabel(platformValue);
        const ordersCount = d.orders_count ?? (Array.isArray(d.orders) ? d.orders.length : 0);
        const lastOrderId = d.last_order_id || '';
        const lastOrderStatus = d.last_order_status || '';
        const lastOrderDisplay = lastOrderId ? `#${lastOrderId}${lastOrderStatus ? ' (' + lastOrderStatus + ')' : ''}` : '-';
        const callPhone = realPhone || (platformValue === 'whatsapp' ? platformId : '');
        let interests = (d.interests || []).join(' ، ');
        let lastmsg = (state.chatFiles[p] && state.chatFiles[p].length > 0) ? state.chatFiles[p][state.chatFiles[p].length - 1].content.substring(0, 40) : '';
        let intentTag = d.last_intent ? `<span class="tag intent-${d.last_intent.replace(/_/g, '-')}">${d.last_intent}</span>` : '';
        let hot = (d.last_intent === 'quote_request' || d.last_intent === 'support_request') ? '<span class="hot-lead">🔥</span>' : '';
        let last = d.last_contact ? new Date(d.last_contact * 1000).toLocaleString('ar-EG') : '—';
        let chk = state.selected.includes(p) ? 'checked' : '';
        let stval = d.status || 'new';
let followupTxt = '';
if (stval === 'scheduled' && d.followup_date) {
    let fdt = new Date(d.followup_date * 1000);
    followupTxt = `<div style="font-size:0.95em;color:#2fa17a;margin-top:3px;">
        ${fdt.toLocaleDateString('ar-EG')} ${fdt.toLocaleTimeString('ar-EG', { hour: '2-digit', minute: '2-digit' })}
    </div>`;
}


        tbody.insertAdjacentHTML('beforeend', `
            <tr>
                <td><input type="checkbox" ${chk} onchange="toggleSelect('${p}')" style="transform: scale(1.3);"></td>
                <td>${d.name || '-'}</td>
                <td>${realPhone || '-'}</td>
                <td>${platformId || '-'}</td>
                <td>${platformLabel}</td>
                <td>${d.email || '-'}</td>
                <td>${d.city || '-'}</td>
                <td>${d.company || '-'}</td>
                <td>${d.business_type || '-'}</td>
                <td>${interests}</td>
                <td>${lastmsg || '-'}</td>
                <td>${intentTag} ${hot}</td>
<td>
    <select class="status-badge status-${stval}" onchange="changeStatus('${p}',this.value)" style="font-size:1em; min-width:120px;">
        ${Object.entries(state.statusList).map(([v, t]) => `<option value="${v}"${stval === v ? ' selected' : ''}>${t}</option>`).join('')}
    </select>
    ${followupTxt}
</td>

                <td>${d.conversation_count || 0}</td>
                <td>${last}</td>
                <td>${lastOrderDisplay}</td>
                <td>${ordersCount}</td>
                <td><button onclick="editNote('${p}')" class="btn btn-outline" title="إضافة أو تعديل الملاحظات"><i class="fa fa-sticky-note"></i></button></td>
                <td><button onclick="editCustomDetails('${p}')" class="btn btn-outline" title="إضافة أو تعديل تفاصيل"><i class="fa fa-file-alt"></i></button></td>
                <td class="quick-actions">
                    <button title="سجل المحادثة" onclick="showChatLog('${p}')"><i class="fa fa-comments"></i></button>
                    <button title="رد سريع" onclick="quickReply('${p}','${d.name || ''}')"><i class="fa fa-reply"></i></button>
                    <button title="اتصال" ${callPhone ? `onclick="window.open('tel:${callPhone}')"` : 'disabled'}><i class="fa fa-phone"></i></button>
                </td>
            </tr>
        `);
    });

    document.getElementById('selectedCount').innerText = state.selected.length;
}

/* ======= 4. Selection & Quick Reply ======= */
function toggleSelect(ph) {
    const index = state.selected.indexOf(ph);
    if (index > -1) state.selected.splice(index, 1);
    else state.selected.push(ph);
    renderTable();
}

function toggleSelectAll() {
    if (state.selected.length < state.filtered.length) {
        state.selected = state.filtered.map(c => c.phone);
    } else {
        state.selected = [];
    }
    renderTable();
}

function quickReply(ph, name) {
    hideBulkComposer();
    state.selected = [ph];
    showBulkComposer();
    document.querySelector('#bulkForm textarea').value = `مرحباً ${name} 👋 كيف أساعدك؟`;
}

/* ======= 5. Chat System & Log ======= */
function renderChatList(list) {
    const ul = document.getElementById('chatList');
    ul.innerHTML = '';
    if (list.length === 0) {
        ul.innerHTML = '<li style="text-align:center; padding:20px; color:#777;">لا توجد محادثات</li>';
        return;
    }
    list.forEach(item => {
        const li = document.createElement('li');
        li.className = 'chat-list-item';
        li.dataset.phone = item.phone;
        li.innerHTML = `
            <div class="phone">${item.phone}</div>
            <div class="name">${item.name || 'لا يوجد اسم'}</div>
            <div class="last-msg">${item.lastMsg || 'لا توجد رسائل'}</div>
            <div class="time">${item.lastTime ? new Date(item.lastTime * 1000).toLocaleString('ar-EG') : ''}</div>
        `;
        li.addEventListener('click', () => {
            document.querySelectorAll('.chat-list-item').forEach(el => el.classList.remove('active'));
            li.classList.add('active');
            displayChat(item.phone);
        });
        ul.appendChild(li);
    });
}

function displayChat(phone) {
    const chat = state.chatFiles[phone] || [];
    const customer = state.customerMap[phone] || {};
    const platformId = getPlatformId(phone, customer);
    const realPhone = getRealPhone(phone, customer);
    const platformValue = getCustomerPlatform(phone, customer);
    const platformLabel = formatPlatformLabel(platformValue);
    const displayPhone = realPhone ? `${realPhone} | ID: ${platformId}` : platformId;
    const headerMeta = platformValue ? `${displayPhone} | ${platformLabel}` : displayPhone;
    document.getElementById('chatCustomerName').textContent = customer.name || 'عميل';
    document.getElementById('chatCustomerPhone').textContent = headerMeta;
    document.getElementById('chatMsgCount').textContent = `${chat.length} رسالة`;
    const messagesContainer = document.getElementById('chatMessages');
    messagesContainer.innerHTML = '';
    if (chat.length === 0) {
        messagesContainer.innerHTML = '<div style="text-align:center; padding:40px; color:#777;">لا توجد محادثات لهذا العميل</div>';
        return;
    }
    chat.forEach(msg => {
        const div = document.createElement('div');
        if (msg.role === 'system') {
            div.className = 'chat-bubble chat-bubble-system';
        } else if (msg.role === 'user') {
            div.className = 'chat-bubble chat-bubble-user';
        } else {
            div.className = 'chat-bubble chat-bubble-bot';
        }
        div.innerHTML = `
            <div>${(msg.content || '').replace(/</g, '&lt;').replace(/\n/g, '<br>')}</div>
            <div class="chat-bubble-time">${msg.ts ? new Date(msg.ts * 1000).toLocaleString('ar-EG') : ''}</div>
        `;
        messagesContainer.appendChild(div);
    });
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}

function showChatLog(ph) {
    const chat = state.chatFiles[ph] || [];
    let html = '';
    chat.filter(isDialogueMsg).forEach(msg => {
        const isUser = msg.role === 'user';
        const bubble = isUser ? 'bubble-user' : 'bubble-bot';
        const who = isUser ? 'عميل' : 'بوت';
        const time = msg.ts ? new Date(msg.ts * 1000).toLocaleTimeString('ar-EG', { hour: '2-digit', minute: '2-digit' }) : '';
        html += `<div class="whatsapp-bubble ${bubble}">
            ${(msg.content || '').replace(/</g, '&lt;').replace(/\n/g, '<br>')}
            <br><span class="bubble-meta ${isUser ? 'bubble-meta-user' : ''}">${who}${time ? ' - ' + time : ''}</span>
        </div>`;
    });
    document.getElementById('chatLogBody').innerHTML = html || '<div style="text-align:center;padding:30px;color:#777;">لا يوجد سجل محادثة</div>';
    document.getElementById('chatLogModal').classList.add('show');
    setTimeout(() => { document.getElementById('chatLogBody').scrollTop = 999999; }, 100);
}
function hideChatLog() {
    document.getElementById('chatLogModal').classList.remove('show');
}
function isDialogueMsg(m) {
    if (!m.content) return false;
    const t = m.content.trim();
    if (t.startsWith('*') ||
        t.startsWith('أنت مستشار') ||
        t.startsWith('معلومات العميل') ||
        t.startsWith('أسلوبك') ||
        t.startsWith('خدماتنا') ||
        t.startsWith('ملاحظات') ||
        t.startsWith('Take a minute') ||
        t.startsWith('Get inspiration') ||
        t.length > 900) {
        return false;
    }
    return ['user', 'assistant', 'bot'].includes(m.role);
}

/* ======= 6. Bulk Message Composer ======= */
function showBulkComposer() {
    document.getElementById('bulkComposerModal').classList.add('show');
    document.getElementById('selectedCountBulk').innerText = state.selected.length
        ? `المرسل إليهم: ${state.selected.length} عميل`
        : 'لم تختَر أي عميل';
    state.unsavedChanges = false;
}
function hideBulkComposer() {
    if (!warnUnsaved()) return;
    document.getElementById('bulkComposerModal').classList.remove('show');
    state.unsavedChanges = false;
}
function sendBulkMessage() {
    if (!state.selected.length) {
        showNotif('اختر عميل واحد على الأقل', 'danger');
        return;
    }
    
    const platform = document.getElementById('platformChoice').value;
    const message = document.querySelector('#bulkForm textarea').value;
    
    // إضافة معرف المنصة للطلب
    document.getElementById('selectedPhonesBulk').value = JSON.stringify({
        phones: state.selected,
        platform: platform,
        message: message
    });
    
    showLoader("يتم الإرسال الآن...");
    document.getElementById('bulkForm').submit();
}


/* ======= 7. Notes and Details Modals ======= */
function editNote(ph) {
    state.editingPhone = ph;
    document.getElementById('noteInput').value = state.customerMap[ph]?.note || '';
    document.getElementById('noteModal').classList.add('show');
    state.unsavedChanges = false;
}
function hideNoteModal() {
    if (!warnUnsaved()) return;
    document.getElementById('noteModal').classList.remove('show');
    state.unsavedChanges = false;
}
function saveNote() {
    const note = document.getElementById('noteInput').value;
    fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `save_note=1&phone=${encodeURIComponent(state.editingPhone)}&note=${encodeURIComponent(note)}`
    })
        .then(r => r.json())
        .then(d => {
            if (d.ok) {
                state.customerMap[state.editingPhone].note = note;
                showNotif('تم حفظ الملاحظة بنجاح');
                hideNoteModal();
                renderTable();
            } else {
                showNotif('تعذر حفظ الملاحظة', 'danger');
            }
        });
}
function editCustomDetails(ph) {
    state.editingPhone = ph;
    document.getElementById('customDetailsInput').value = state.customerMap[ph]?.custom_details || '';
    document.getElementById('customDetailsModal').classList.add('show');
    state.unsavedChanges = false;
}
function hideCustomDetailsModal() {
    if (!warnUnsaved()) return;
    document.getElementById('customDetailsModal').classList.remove('show');
    state.unsavedChanges = false;
}
function saveCustomDetails() {
    const details = document.getElementById('customDetailsInput').value;
    fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `save_custom_details=1&phone=${encodeURIComponent(state.editingPhone)}&details=${encodeURIComponent(details)}`
    })
        .then(r => r.json())
        .then(d => {
            if (d.ok) {
                state.customerMap[state.editingPhone].custom_details = details;
                showNotif('تم حفظ التفاصيل بنجاح');
                hideCustomDetailsModal();
                renderTable();
            } else {
                showNotif('تعذر حفظ التفاصيل', 'danger');
            }
        });
}

/* ======= 8. Status Change with Date ======= */

function changeStatus(phone, stval) {

    // باقي الحالات القديمة (بدون مودال)
    fetch(window.location.pathname, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `set_status=1&phone=${encodeURIComponent(phone)}&status=${encodeURIComponent(stval)}`
    })
        .then(r => r.json())
        .then(d => {
            if (d.ok) {
                applyFilters();
                showNotif('تم تحديث حالة العميل');
            } else showNotif('فشل في تحديث الحالة', 'danger');
        });
}



function changeStatus(phone, stval) {
    if (stval === 'scheduled') {
        // فتح المودال وتعبئة البيانات
        state.editingPhone = phone;
        document.getElementById('clientPhone').innerText = phone;
        document.getElementById('clientPhoneInput').value = phone;
        document.getElementById('statusInput').value = stval;
        document.getElementById('followupDate').value = '';
        document.getElementById('followupTime').value = '';
        document.getElementById('modalNotes').value = '';
        document.getElementById('scheduleModal').classList.add('show');
        return;
    }
    // باقي الحالات القديمة (بدون مودال)
    fetch(window.location.pathname, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `set_status=1&phone=${encodeURIComponent(phone)}&status=${encodeURIComponent(stval)}`
    })
        .then(r => r.json())
        .then(d => {
            if (d.ok) {
                applyFilters();
                showNotif('تم تحديث حالة العميل');
            } else showNotif('فشل في تحديث الحالة', 'danger');
        });
}


document.getElementById('saveSchedule').onclick = function() {
    const phone = document.getElementById('clientPhoneInput').value;
    const stval = document.getElementById('statusInput').value;
    const date = document.getElementById('followupDate').value;
    const time = document.getElementById('followupTime').value;
    const notes = document.getElementById('modalNotes').value;

    if (!date || !time) {
        showNotif('حدد تاريخ ووقت للموعد', 'danger');
        return;
    }

    // دمج التاريخ والوقت في timestamp
    const dt = `${date} ${time}`;
    fetch(window.location.pathname, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `set_status=1&phone=${encodeURIComponent(phone)}&status=${encodeURIComponent(stval)}&date=${encodeURIComponent(dt)}&note=${encodeURIComponent(notes)}`
    })
        .then(r => r.json())
        .then(d => {
            if (d.ok) {
                applyFilters();
                showNotif('تم حفظ الموعد بنجاح');
            } else showNotif('حدث خطأ في حفظ الموعد', 'danger');
            document.getElementById('scheduleModal').classList.remove('show');
        });
};
document.getElementById('cancelSchedule').onclick = function() {
    document.getElementById('scheduleModal').classList.remove('show');
};
document.querySelector('#scheduleModal .close-button').onclick = function() {
    document.getElementById('scheduleModal').classList.remove('show');
};


/* ======= 9. Analytics & Charts ======= */
function updateCharts() {
    // Status distribution
    const statusCounts = {};
    state.filtered.forEach(c => {
        const status = c.data.status || 'new';
        statusCounts[status] = (statusCounts[status] || 0) + 1;
    });
    const statusLabels = Object.values(state.statusList);
    const statusData = Object.keys(state.statusList).map(k => statusCounts[k] || 0);
    if (state.statusChart) state.statusChart.destroy();
    const statusCtx = document.getElementById('statusChart').getContext('2d');
    state.statusChart = new Chart(statusCtx, {
        type: 'pie',
        data: {
            labels: statusLabels,
            datasets: [{
                data: statusData,
                backgroundColor: [
                    '#e3f8ff', '#fff7e0', '#e6fff1', '#d9f9c7',
                    '#ffd6d6', '#f1f0fd', '#f3e9f6', '#f8f8f8'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { position: 'bottom', rtl: true, labels: { font: { family: 'Tajawal' } } }
            }
        }
    });

    // ======== متابعة الشارت ========
    const bizCounts = {};
    state.filtered.forEach(c => {
        const biz = c.data.business_type || 'غير محدد';
        bizCounts[biz] = (bizCounts[biz] || 0) + 1;
    });
    const bizLabels = Object.keys(bizCounts);
    const bizData = Object.values(bizCounts);
    if (state.businessChart) state.businessChart.destroy();
    const businessCtx = document.getElementById('businessChart').getContext('2d');
    state.businessChart = new Chart(businessCtx, {
        type: 'bar',
        data: {
            labels: bizLabels,
            datasets: [{
                label: 'عدد العملاء',
                data: bizData,
                backgroundColor: '#2fa17a',
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            indexAxis: 'y',
            plugins: { legend: { display: false } },
            scales: { x: { beginAtZero: true } }
        }
    });
}

/* ======= 10. Dark Mode & App Init ======= */
function toggleDark() {
    document.body.classList.toggle('dark');
    localStorage.setItem('darkMode', document.body.classList.contains('dark') ? '1' : '0');
}
function setupDarkMode() {
    if (localStorage.getItem('darkMode') === '1') {
        document.body.classList.add('dark');
    }
}

/* ======= 11. Export Selected ======= */
function exportSelected() {
    if (!state.selected.length) {
        showNotif('اختر عميل واحد على الأقل للتصدير', 'danger');
        return;
    }
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '';
    form.target = '_blank';
    const phones = document.createElement('input');
    phones.type = 'hidden';
    phones.name = 'export_phones';
    phones.value = JSON.stringify(state.selected);
    form.appendChild(phones);
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

/* ======= 12. Tab Navigation ======= */
function showTab(t) {
    document.getElementById('customersTab').style.display = t === 'customers' ? 'block' : 'none';
    document.getElementById('chatsTab').style.display = t === 'chats' ? 'block' : 'none';
    document.getElementById('analyticsTab').style.display = t === 'analytics' ? 'block' : 'none';
    document.getElementById('tabCustomers').classList.toggle('active', t === 'customers');
    document.getElementById('tabChats').classList.toggle('active', t === 'chats');
    document.getElementById('tabAnalytics').classList.toggle('active', t === 'analytics');
    if (t === 'chats') {
        buildChatList();
    }
    if (t === 'analytics') {
        updateCharts();
    }
}

function buildChatList(filteredPhones = null) {
    // بناء قائمة المحادثات بناءً على الفلترة
    const allowedPhones = filteredPhones ? new Set(filteredPhones) : null;
    state.chatList = Object.keys(state.chatFiles)
        .filter(phone => !allowedPhones || allowedPhones.has(phone))
        .map(phone => {
            const chat = state.chatFiles[phone];
            const lastMsg = chat.length > 0 ? chat[chat.length - 1] : null;
            const platform = getCustomerPlatform(phone, state.customerMap[phone] || {});
            return {
                phone: phone,
                name: state.customerMap[phone]?.name || '',
                lastMsg: lastMsg?.content || '',
                lastTime: lastMsg?.ts || 0,
                count: chat.length,
                platform: platform
            };
        });

    filterChatList(); // بعد البناء، نفذ فلتر المنصة (واتساب/ماسنجر/الخ)
}



function renderChatList(list) {
    const ul = document.getElementById('chatList');
    ul.innerHTML = '';
    if (list.length === 0) {
        ul.innerHTML = '<li style="text-align:center; padding:20px; color:#777;">لا توجد محادثات</li>';
        return;
    }
    list.forEach(item => {
        let platformIcon = '';
        switch (item.platform) {
            case 'whatsapp': platformIcon = '<i class="fab fa-whatsapp" style="color:#25d366"></i>'; break;
            case 'messenger': platformIcon = '<i class="fab fa-facebook-messenger" style="color:#0084ff"></i>'; break;
            case 'instagram': platformIcon = '<i class="fab fa-instagram" style="color:#e1306c"></i>'; break;
            case 'comments': platformIcon = '<i class="fa fa-comments" style="color:#888"></i>'; break;
        }
        const customer = state.customerMap[item.phone] || {};
        const platformId = getPlatformId(item.phone, customer);
        const realPhone = getRealPhone(item.phone, customer);
        const phoneLine = realPhone || platformId;
        const idLine = realPhone && realPhone !== platformId ? `<div class="chat-id">ID: ${platformId}</div>` : '';
        const li = document.createElement('li');
        li.className = 'chat-list-item';
        li.dataset.phone = item.phone;
        li.innerHTML = `
            <div class="phone">${platformIcon} ${phoneLine}</div>
            ${idLine}
            <div class="name">${item.name || 'لا يوجد اسم'}</div>
            <div class="last-msg">${item.lastMsg || 'لا توجد رسائل'}</div>
            <div class="time">${item.lastTime ? new Date(item.lastTime * 1000).toLocaleString('ar-EG') : ''}</div>
        `;
        li.addEventListener('click', () => {
            document.querySelectorAll('.chat-list-item').forEach(el => el.classList.remove('active'));
            li.classList.add('active');
            displayChat(item.phone);
        });
        ul.appendChild(li);
    });
}


/* ======= 13. App Init (Ready) ======= */
function initDashboard() {
    setupDarkMode();
    loadFilters();
    document.getElementById('searchInput').addEventListener('input', applyFilters);
// ربط الأحداث للفلاتر الجديدة بشكل صحيح
document.querySelectorAll('.filters-box input, .filters-box select').forEach(el => {
    el.addEventListener('input', applyFilters);
    el.addEventListener('change', applyFilters);
});
    document.getElementById('chatSearch').addEventListener('input', function () {
        const term = this.value.toLowerCase();
        const filtered = state.chatList.filter(item => {
            const customer = state.customerMap[item.phone] || {};
            const platformId = getPlatformId(item.phone, customer);
            const realPhone = getRealPhone(item.phone, customer);
            return (
                item.phone.includes(term) ||
                platformId.includes(term) ||
                realPhone.toLowerCase().includes(term) ||
                (item.name && item.name.toLowerCase().includes(term)) ||
                item.lastMsg.toLowerCase().includes(term)
            );
        });
        renderChatList(filtered);
        if (filtered.length > 0) {
            const firstItem = document.querySelector('.chat-list-item');
            if (firstItem) {
                document.querySelectorAll('.chat-list-item').forEach(el => el.classList.remove('active'));
                firstItem.classList.add('active');
                displayChat(firstItem.dataset.phone);
            }
        }
    });
    // تبويبات
    document.getElementById('tabCustomers').addEventListener('click', () => showTab('customers'));
    document.getElementById('tabChats').addEventListener('click', () => showTab('chats'));
    document.getElementById('tabAnalytics').addEventListener('click', () => showTab('analytics'));
    // زر الوضع الليلي
    document.querySelectorAll('.btn-dark').forEach(btn => btn.addEventListener('click', toggleDark));
    // زر تصدير
    document.querySelectorAll('.export-btn').forEach(btn => btn.addEventListener('click', exportSelected));
    // زر إرسال جماعي
    document.querySelectorAll('.btn-primary').forEach(btn => {
        if (btn.innerText.includes('إرسال جماعي')) btn.addEventListener('click', showBulkComposer);
    });
    // زر تحديد الكل
    document.querySelectorAll('.btn-outline').forEach(btn => {
        if (btn.innerText.includes('تحديد الكل')) btn.addEventListener('click', toggleSelectAll);
    });
    addEscSupport();
    // أول عرض
    applyFilters();
    showTab('customers');
}

// انطلاق النظام بعد تحميل الصفحة
document.addEventListener('DOMContentLoaded', initDashboard);

// يمكنك هنا إضافة Footer أو قسم ترويجي صغير أسفل الصفحة مثل:
setTimeout(() => {
    const footer = document.createElement('footer');
    footer.innerHTML = `
        <div style="text-align:center; padding:18px; background:#f3faf7;color:#2fa17a; font-weight:600; border-top:1px solid #e5e5e5;">
            CRM by <a href="https://smartlogiceg.com" style="color:#0d6efd;" target="_blank">Smart Logic</a> &mdash; Upgrade anytime | <a href="mailto:info@smartlogiceg.com" style="color:#0d6efd;">Contact Support</a>
        </div>
    `;
    document.body.appendChild(footer);
}, 1500);


document.getElementById('platformFilter').addEventListener('change', applyFilters);



function filterChatList() {
    const plat = document.getElementById('platformFilter').value;
    let filtered = state.chatList;

    if (plat) {
        filtered = state.chatList.filter(item => {
            // ابحث عن رسالة واحدة على الأقل من نفس المنصة في الشات
            const chat = state.chatFiles[item.phone] || [];
            return chat.some(msg => msg.meta && msg.meta.raw && msg.meta.raw.platform === plat);
        });
    }
    renderChatList(filtered);

    // اختار أول عنصر افتراضيًا بعد التصفية
    if (filtered.length > 0) {
        const firstItem = document.querySelector('.chat-list-item');
        if (firstItem) {
            document.querySelectorAll('.chat-list-item').forEach(el => el.classList.remove('active'));
            firstItem.classList.add('active');
            displayChat(firstItem.dataset.phone);
        }
    }
}



/* ======= 14. External File Import System (Fixed) ======= */

function showImportModal() {
    const modal = document.getElementById('importFileModal');
    if (modal) {
        modal.classList.add('show');
        resetImportModal();
    } else {
        showNotif('خطأ: لا يمكن العثور على نافذة الاستيراد', 'danger');
    }
}

function hideImportModal() {
    const modal = document.getElementById('importFileModal');
    if (modal) {
        modal.classList.remove('show');
        resetImportModal();
    }
}

function resetImportModal() {
    const step1 = document.getElementById('importStep1');
    const step2 = document.getElementById('importStep2');
    const step3 = document.getElementById('importStep3');
    
    if (step1) step1.style.display = 'block';
    if (step2) step2.style.display = 'none';
    if (step3) step3.style.display = 'none';
    
    const form = document.getElementById('importForm');
    if (form) form.reset();
    
    const preview = document.getElementById('importPreview');
    if (preview) preview.innerHTML = '';
    
    const results = document.getElementById('importResults');
    if (results) results.innerHTML = '';
}

function uploadExternalFile() {
    const fileInput = document.getElementById('importFile');
    const fileType = document.getElementById('fileType').value;
    
    if (!fileInput.files[0]) {
        showNotif('اختر ملف أولاً', 'danger');
        return;
    }
    
    if (!fileType) {
        showNotif('حدد نوع الملف', 'danger');
        return;
    }
    
    const formData = new FormData();
    formData.append('external_file', fileInput.files[0]);
    formData.append('file_type', fileType);
    
    const loader = showLoader('جاري تحليل الملف...');
    
    fetch('', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        hideLoader(loader);
        if (data.success) {
            showImportPreview(data.contacts, data.count);
            showNotif(`تم استيراد ${data.count} جهة اتصال بنجاح!`, 'success');
        } else {
            showNotif(data.error || 'فشل في تحليل الملف', 'danger');
        }
    })
    .catch(error => {
        hideLoader(loader);
        showNotif('حدث خطأ في تحميل الملف', 'danger');
        console.error('Error:', error);
    });
}

function showImportPreview(contacts, totalCount) {
    document.getElementById('importStep1').style.display = 'none';
    document.getElementById('importStep2').style.display = 'block';
    
    let previewHtml = `
        <div class="import-stats">
            <h4><i class="fas fa-check-circle"></i> تم استيراد البيانات بنجاح!</h4>
            <p>تم العثور على <strong>${totalCount}</strong> جهة اتصال</p>
        </div>
        
        <div style="max-height: 400px; overflow-y: auto; border: 1px solid #ddd; border-radius: 8px; margin: 20px 0;">
            <table class="import-preview-table" style="width: 100%; border-collapse: collapse;">
                <thead style="background: #f8f9fa; position: sticky; top: 0;">
                    <tr>
                        <th>الاسم</th>
                        <th>الهاتف</th>
                        <th>الشركة</th>
                        <th>النشاط</th>
                        <th>المدينة</th>
                        <th>الإيميل</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    contacts.forEach(contact => {
        previewHtml += `
                    <tr>
                        <td>${contact.name || '-'}</td>
                        <td>${contact.phone}</td>
                        <td>${contact.company || '-'}</td>
                        <td>${contact.business_type || '-'}</td>
                        <td>${contact.city || '-'}</td>
                        <td>${contact.email || '-'}</td>
                    </tr>
        `;
    });
    
    previewHtml += `
                </tbody>
            </table>
        </div>
        
        ${totalCount > 10 ? `<p style="margin-top: 10px; color: #666; font-size: 0.9rem; text-align: center;">عرض أول 10 جهات اتصال من إجمالي ${totalCount}</p>` : ''}
    `;
    
    document.getElementById('importPreview').innerHTML = previewHtml;
}

function backToStep1() {
    document.getElementById('importStep1').style.display = 'block';
    document.getElementById('importStep2').style.display = 'none';
}

function sendToImported() {
    const message = document.getElementById('importedMessage').value.trim();
    
    if (!message) {
        showNotif('اكتب رسالة أولاً', 'danger');
        return;
    }
    
    const loader = showLoader('جاري إرسال الرسائل...');
    
    const formData = new FormData();
    formData.append('send_to_imported', '1');
    formData.append('imported_message', message);
    
    fetch('', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        hideLoader(loader);
        if (data.success) {
            showImportResults(data);
            showNotif(`تم إرسال ${data.sent} رسالة من أصل ${data.total}`, 'success');
        } else {
            showNotif('حدث خطأ في الإرسال', 'danger');
        }
    })
    .catch(error => {
        hideLoader(loader);
        showNotif('حدث خطأ في الإرسال', 'danger');
        console.error('Error:', error);
    });
}

function showImportResults(data) {
    document.getElementById('importStep2').style.display = 'none';
    document.getElementById('importStep3').style.display = 'block';
    
    let resultsHtml = `
        <div class="import-stats">
            <h4><i class="fas fa-paper-plane"></i> نتائج الإرسال الجماعي</h4>
            <p>تم إرسال <strong>${data.sent}</strong> رسالة بنجاح من أصل <strong>${data.total}</strong></p>
        </div>
        
        <div style="max-height: 400px; overflow-y: auto; border: 1px solid #ddd; border-radius: 8px; margin: 20px 0;">
            <table style="width: 100%; border-collapse: collapse;">
                <thead style="background: #f8f9fa;">
                    <tr>
                        <th style="padding: 10px; border: 1px solid #ddd;">الهاتف</th>
                        <th style="padding: 10px; border: 1px solid #ddd;">النتيجة</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    Object.entries(data.results).forEach(([phone, result]) => {
        const isSuccess = result.includes('نجاح');
        const bgColor = isSuccess ? '#d4edda' : '#f8d7da';
        const textColor = isSuccess ? '#155724' : '#721c24';
        
        resultsHtml += `
                    <tr style="background: ${bgColor}; color: ${textColor};">
                        <td style="padding: 8px; border: 1px solid #ddd;">${phone}</td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${result}</td>
                    </tr>
        `;
    });
    
    resultsHtml += `
                </tbody>
            </table>
        </div>
    `;
    
    document.getElementById('importResults').innerHTML = resultsHtml;
    
    // إعادة تحميل بيانات العملاء
    setTimeout(() => {
        location.reload();
    }, 3000);
}

// إضافة event listener عند تحميل الصفحة
document.addEventListener('DOMContentLoaded', function() {
    // التأكد من وجود الزر وإضافة event listener
    const importButton = document.querySelector('button[onclick*="showImportModal"]');
    if (importButton) {
        // إزالة onclick القديم وإضافة event listener جديد
        importButton.removeAttribute('onclick');
        importButton.addEventListener('click', function(e) {
            e.preventDefault();
            showImportModal();
        });
    }
    
    // إضافة event listeners للأزرار الأخرى
    const uploadButton = document.getElementById('uploadExternalFileBtn');
    if (uploadButton) {
        uploadButton.addEventListener('click', uploadExternalFile);
    }
});

</script>
</body>
</html>
