/home/smartonegroup/www/system/find-customers.php
<?php
/**
 * تشخيص مشكلة عدم ظهور العملاء في CloudOnex
 * رغم نجاح عملية النقل
 */

// تحميل الإعدادات
$config = include 'config.php';

?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>البحث عن العملاء المنقولين</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; direction: rtl; background: #f5f5f5; }
        .container { max-width: 900px; margin: 0 auto; background: white; padding: 25px; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
        .success { color: green; background: #d4edda; padding: 15px; border-radius: 8px; margin: 15px 0; border-right: 5px solid #28a745; }
        .error { color: red; background: #f8d7da; padding: 15px; border-radius: 8px; margin: 15px 0; border-right: 5px solid #dc3545; }
        .warning { color: #856404; background: #fff3cd; padding: 15px; border-radius: 8px; margin: 15px 0; border-right: 5px solid #ffc107; }
        .info { color: #0c5460; background: #d1ecf1; padding: 15px; border-radius: 8px; margin: 15px 0; border-right: 5px solid #17a2b8; }
        .code { background: #2d3748; color: #e2e8f0; padding: 15px; border-radius: 8px; font-family: 'Courier New', monospace; margin: 15px 0; font-size: 12px; overflow-x: auto; }
        h1 { color: #2c3e50; text-align: center; margin-bottom: 30px; }
        h3 { color: #34495e; border-bottom: 3px solid #3498db; padding-bottom: 8px; margin-top: 30px; }
        button { background: #007bff; color: white; padding: 12px 25px; border: none; border-radius: 8px; cursor: pointer; margin: 8px; font-size: 14px; }
        button:hover { background: #0056b3; }
        button.success { background: #28a745; }
        button.warning { background: #ffc107; color: #212529; }
        button.danger { background: #dc3545; }
        #results { margin-top: 25px; }
        .result { padding: 12px; margin: 8px 0; border-radius: 6px; }
        .customer-card { background: #f8f9fa; padding: 15px; margin: 10px 0; border-radius: 8px; border-right: 4px solid #007bff; }
        .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 20px 0; }
        .stat-card { background: #e9ecef; padding: 20px; border-radius: 10px; text-align: center; }
        .stat-number { font-size: 2em; font-weight: bold; color: #007bff; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 البحث عن العملاء المنقولين</h1>
        
        <div class="success">
            <h4>✅ رائع! النقل نجح تقنياً</h4>
            <p>لكن العملاء مش ظاهرين في CloudOnex - دي مشكلة شائعة وقابلة للحل!</p>
        </div>

        <div class="info">
            <h4>🔍 أسباب محتملة لعدم ظهور العملاء:</h4>
            <ul>
                <li><strong>العملاء في حالة Draft أو Pending</strong> - تحتاج تفعيل</li>
                <li><strong>العملاء في Company أو Tenant مختلف</strong></li>
                <li><strong>مشكلة في صلاحيات المستخدم</strong> - مش شايف كل العملاء</li>
                <li><strong>العملاء محفوظين لكن في مكان مختلف</strong></li>
                <li><strong>Cache أو Session مش متحدث</strong></li>
                <li><strong>البيانات محفوظة لكن مش مفعلة</strong></li>
            </ul>
        </div>

        <h3>🧪 اختبارات للبحث عن العملاء:</h3>
        
        <button onclick="searchAllCustomers()">🔍 البحث عن جميع العملاء</button>
        <button onclick="searchWhmcsCustomers()">🔍 البحث عن عملاء WHMCS</button>
        <button onclick="searchByExternalId()">🔍 البحث بـ External ID</button>
        <button onclick="checkCustomerStatus()">📊 فحص حالة العملاء</button>
        <button onclick="testCreateCustomer()">➕ اختبار إنشاء عميل جديد</button>
        
        <div id="results"></div>
        
        <h3>📊 إحصائيات سريعة:</h3>
        <div class="stats" id="stats">
            <div class="stat-card">
                <div class="stat-number" id="totalCustomers">-</div>
                <div>إجمالي العملاء</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="whmcsCustomers">-</div>
                <div>عملاء WHMCS</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="recentCustomers">-</div>
                <div>عملاء اليوم</div>
            </div>
        </div>

        <div class="warning">
            <h4>🔧 حلول سريعة:</h4>
            <ol>
                <li><strong>تحديث الصفحة:</strong> اعمل Refresh لصفحة العملاء في CloudOnex</li>
                <li><strong>تسجيل دخول مرة أخرى:</strong> اخرج وادخل تاني في CloudOnex</li>
                <li><strong>تحقق من الفلاتر:</strong> شوف لو في فلتر مخفي العملاء</li>
                <li><strong>تحقق من الصلاحيات:</strong> تأكد إن المستخدم يقدر يشوف كل العملاء</li>
                <li><strong>فحص قاعدة البيانات:</strong> ادخل phpMyAdmin وشوف جدول العملاء</li>
            </ol>
        </div>
        
        <div class="info">
            <h4>📍 أماكن البحث في CloudOnex:</h4>
            <ul>
                <li><strong>Customers / العملاء</strong> - المكان الأساسي</li>
                <li><strong>Accounts / الحسابات</strong> - أحياناً يكون بهذا الاسم</li>
                <li><strong>Contacts / جهات الاتصال</strong> - ربما هنا</li>
                <li><strong>Draft Customers / العملاء المسودة</strong> - لو موجود</li>
                <li><strong>Pending Approval / في انتظار الموافقة</strong></li>
            </ul>
        </div>
    </div>

    <script>
        // البحث عن جميع العملاء
        function searchAllCustomers() {
            addResult('🔍 جاري البحث عن جميع العملاء...', 'info');
            
            const apiUrl = '<?= $config['cloudonex']['url'] ?>/customers';
            const token = '<?= $config['cloudonex']['token'] ?>';
            
            fetch(apiUrl, {
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data && Array.isArray(data)) {
                    addResult(`✅ وجدت ${data.length} عميل في CloudOnex`, 'success');
                    document.getElementById('totalCustomers').textContent = data.length;
                    
                    if (data.length > 0) {
                        displayCustomers(data.slice(0, 5)); // عرض أول 5 عملاء
                    } else {
                        addResult('❌ لا توجد عملاء في النظام!', 'error');
                    }
                } else if (data && data.data) {
                    const customers = data.data;
                    addResult(`✅ وجدت ${customers.length} عميل في CloudOnex`, 'success');
                    document.getElementById('totalCustomers').textContent = customers.length;
                    displayCustomers(customers.slice(0, 5));
                } else {
                    addResult('❌ استجابة غير متوقعة: ' + JSON.stringify(data), 'error');
                }
            })
            .catch(error => {
                addResult('❌ خطأ في البحث: ' + error.message, 'error');
            });
        }
        
        // البحث عن عملاء WHMCS تحديداً
        function searchWhmcsCustomers() {
            addResult('🔍 جاري البحث عن عملاء WHMCS...', 'info');
            
            const apiUrl = '<?= $config['cloudonex']['url'] ?>/customers?search=whmcs_';
            const token = '<?= $config['cloudonex']['token'] ?>';
            
            fetch(apiUrl, {
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                let customers = [];
                if (Array.isArray(data)) {
                    customers = data;
                } else if (data && data.data) {
                    customers = data.data;
                }
                
                const whmcsCustomers = customers.filter(customer => 
                    customer.external_id && customer.external_id.includes('whmcs_')
                );
                
                addResult(`✅ وجدت ${whmcsCustomers.length} عميل من WHMCS`, whmcsCustomers.length > 0 ? 'success' : 'warning');
                document.getElementById('whmcsCustomers').textContent = whmcsCustomers.length;
                
                if (whmcsCustomers.length > 0) {
                    displayCustomers(whmcsCustomers.slice(0, 5));
                    addResult('🎉 العملاء موجودين! ربما تحتاج تحديث الصفحة أو تحقق من الفلاتر', 'success');
                } else {
                    addResult('❌ لم أجد عملاء بـ external_id يحتوي على "whmcs_"', 'error');
                }
            })
            .catch(error => {
                addResult('❌ خطأ في البحث: ' + error.message, 'error');
            });
        }
        
        // البحث بـ External ID
        function searchByExternalId() {
            addResult('🔍 جاري البحث بـ External ID...', 'info');
            
            // جرب البحث عن أول عميل من WHMCS
            const apiUrl = '<?= $config['cloudonex']['url'] ?>/customers?search=whmcs_1';
            const token = '<?= $config['cloudonex']['token'] ?>';
            
            fetch(apiUrl, {
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                let found = false;
                let customers = [];
                
                if (Array.isArray(data)) {
                    customers = data;
                } else if (data && data.data) {
                    customers = data.data;
                }
                
                customers.forEach(customer => {
                    if (customer.external_id && customer.external_id.includes('whmcs_')) {
                        found = true;
                        addResult(`✅ وجدت عميل: ${customer.account || customer.name} (ID: ${customer.external_id})`, 'success');
                    }
                });
                
                if (!found) {
                    addResult('❌ لم أجد عملاء بـ external_id من WHMCS', 'error');
                }
            })
            .catch(error => {
                addResult('❌ خطأ في البحث: ' + error.message, 'error');
            });
        }
        
        // فحص حالة العملاء
        function checkCustomerStatus() {
            addResult('📊 جاري فحص حالة العملاء...', 'info');
            
            // فحص عدة endpoints محتملة
            const endpoints = [
                '/customers',
                '/customers?status=active',
                '/customers?status=pending',
                '/customers?status=draft',
                '/accounts',
                '/contacts'
            ];
            
            endpoints.forEach((endpoint, index) => {
                setTimeout(() => {
                    const apiUrl = '<?= $config['cloudonex']['url'] ?>' + endpoint;
                    const token = '<?= $config['cloudonex']['token'] ?>';
                    
                    fetch(apiUrl, {
                        headers: {
                            'Authorization': 'Bearer ' + token,
                            'Accept': 'application/json'
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        let count = 0;
                        if (Array.isArray(data)) {
                            count = data.length;
                        } else if (data && data.data) {
                            count = data.data.length;
                        }
                        
                        if (count > 0) {
                            addResult(`📊 ${endpoint}: ${count} عنصر`, 'info');
                        }
                    })
                    .catch(error => {
                        addResult(`❌ ${endpoint}: خطأ`, 'error');
                    });
                }, index * 1000);
            });
        }
        
        // اختبار إنشاء عميل جديد
        function testCreateCustomer() {
            addResult('➕ جاري اختبار إنشاء عميل جديد...', 'info');
            
            const testCustomer = {
                account: 'Test Customer ' + Date.now(),
                email: 'test' + Date.now() + '@example.com',
                phone: '123456789',
                external_id: 'test_' + Date.now()
            };
            
            const apiUrl = '<?= $config['cloudonex']['url'] ?>/customers';
            const token = '<?= $config['cloudonex']['token'] ?>';
            
            fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(testCustomer)
            })
            .then(response => response.json())
            .then(data => {
                if (data && data.id) {
                    addResult(`✅ تم إنشاء عميل تجريبي بنجاح! ID: ${data.id}`, 'success');
                    addResult('💡 هذا يعني أن API يعمل. العملاء المنقولين موجودين لكن ربما في مكان آخر', 'info');
                } else {
                    addResult('❌ فشل إنشاء عميل تجريبي: ' + JSON.stringify(data), 'error');
                }
            })
            .catch(error => {
                addResult('❌ خطأ في إنشاء عميل تجريبي: ' + error.message, 'error');
            });
        }
        
        // عرض العملاء
        function displayCustomers(customers) {
            let html = '<h4>👥 عينة من العملاء الموجودين:</h4>';
            
            customers.forEach(customer => {
                html += `
                    <div class="customer-card">
                        <strong>الاسم:</strong> ${customer.account || customer.name || 'غير محدد'}<br>
                        <strong>الإيميل:</strong> ${customer.email || 'غير محدد'}<br>
                        <strong>الهاتف:</strong> ${customer.phone || 'غير محدد'}<br>
                        <strong>External ID:</strong> ${customer.external_id || 'غير محدد'}<br>
                        <strong>تاريخ الإنشاء:</strong> ${customer.created_at || customer.date_created || 'غير محدد'}
                    </div>
                `;
            });
            
            addResult(html, 'info');
        }
        
        // إضافة نتيجة
        function addResult(message, type) {
            const resultsDiv = document.getElementById('results');
            const div = document.createElement('div');
            div.className = 'result ' + type;
            div.innerHTML = message;
            resultsDiv.appendChild(div);
            div.scrollIntoView({ behavior: 'smooth' });
        }
        
        // تشغيل البحث الأساسي عند تحميل الصفحة
        window.onload = function() {
            setTimeout(searchAllCustomers, 1000);
        };
    </script>
</body>
</html>