<?php
session_start();
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

// Handle quick fixes
if (isset($_GET['action'])) {
    header('Content-Type: application/json');
    
    if ($_GET['action'] === 'fix_orders_table') {
        try {
            // Check if column exists
            $columns = $db->query("SHOW COLUMNS FROM orders")->fetchAll(PDO::FETCH_COLUMN);
            
            if (!in_array('total_amount', $columns)) {
                // Add total_amount column
                $db->exec("ALTER TABLE orders ADD COLUMN total_amount DECIMAL(10,2) DEFAULT 0 AFTER status");
                
                // Update existing orders with calculated total
                $db->exec("UPDATE orders o 
                          SET total_amount = (
                              SELECT SUM(oi.quantity * oi.price) 
                              FROM order_items oi 
                              WHERE oi.order_id = o.id
                          )");
                
                echo json_encode(['success' => true, 'message' => 'تم إضافة عمود total_amount بنجاح']);
            } else {
                echo json_encode(['success' => true, 'message' => 'العمود موجود بالفعل']);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        exit;
    }
}

$results = [];
$errors = [];
$warnings = [];
$success = [];

// Function to run diagnostic
function runDiagnostic($name, $callback) {
    global $results, $errors, $warnings, $success;
    try {
        $result = $callback();
        $results[$name] = $result;
        if ($result['status'] === 'error') {
            $errors[] = $name;
        } elseif ($result['status'] === 'warning') {
            $warnings[] = $name;
        } else {
            $success[] = $name;
        }
    } catch (Exception $e) {
        $results[$name] = [
            'status' => 'error',
            'message' => $e->getMessage()
        ];
        $errors[] = $name;
    }
}

// 1. Database Connection
runDiagnostic('اتصال قاعدة البيانات', function() use ($db) {
    if ($db) {
        return ['status' => 'success', 'message' => 'الاتصال بقاعدة البيانات يعمل بشكل صحيح'];
    }
    return ['status' => 'error', 'message' => 'فشل الاتصال بقاعدة البيانات'];
});

// 2. Check Tables
runDiagnostic('فحص الجداول', function() use ($db) {
    $required_tables = [
        'users', 'products', 'categories', 'orders', 'order_items',
        'cart', 'addresses', 'beauty_services', 'beauty_bookings', 'branches',
        'reviews', 'posts', 'announcements', 'coupons'
    ];
    
    $stmt = $db->query("SHOW TABLES");
    $existing_tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    $missing = array_diff($required_tables, $existing_tables);
    
    if (empty($missing)) {
        return [
            'status' => 'success',
            'message' => 'جميع الجداول المطلوبة موجودة (' . count($existing_tables) . ' جدول)',
            'details' => $existing_tables
        ];
    }
    
    return [
        'status' => 'warning',
        'message' => 'بعض الجداول مفقودة: ' . implode(', ', $missing),
        'details' => ['existing' => $existing_tables, 'missing' => $missing]
    ];
});

// 3. Check Users Table
runDiagnostic('جدول المستخدمين', function() use ($db) {
    $stmt = $db->query("SELECT COUNT(*) as count FROM users");
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    $stmt = $db->query("SELECT COUNT(*) as admin_count FROM users WHERE role = 'admin'");
    $admin_count = $stmt->fetch(PDO::FETCH_ASSOC)['admin_count'];
    
    // Check location columns
    $columns = $db->query("SHOW COLUMNS FROM users")->fetchAll(PDO::FETCH_COLUMN);
    $has_location = in_array('location', $columns);
    $has_latitude = in_array('latitude', $columns);
    $has_longitude = in_array('longitude', $columns);
    
    $location_status = ($has_location && $has_latitude && $has_longitude) ? '✓ Location' : '✗ Location';
    
    if ($admin_count == 0) {
        return [
            'status' => 'error',
            'message' => 'لا يوجد مستخدمين مدراء! يجب إنشاء حساب مدير',
            'details' => ['total' => $count, 'admins' => $admin_count, 'location_support' => $location_status]
        ];
    }
    
    return [
        'status' => 'success',
        'message' => "إجمالي المستخدمين: {$count} | المدراء: {$admin_count} | {$location_status}",
        'details' => ['total' => $count, 'admins' => $admin_count, 'location_support' => $location_status]
    ];
});

// 3.5. Check Addresses Tables (Location Support)
runDiagnostic('جداول العناوين (دعم الموقع)', function() use ($db) {
    $tables_status = [];
    
    // Check addresses table
    $check = $db->query("SHOW TABLES LIKE 'addresses'")->rowCount();
    if ($check > 0) {
        $columns = $db->query("SHOW COLUMNS FROM addresses")->fetchAll(PDO::FETCH_COLUMN);
        $has_location = in_array('location', $columns) && in_array('latitude', $columns) && in_array('longitude', $columns);
        $tables_status['addresses'] = $has_location ? '✓' : '✗';
    } else {
        $tables_status['addresses'] = 'غير موجود';
    }
    
    // Check user_addresses table
    $check = $db->query("SHOW TABLES LIKE 'user_addresses'")->rowCount();
    if ($check > 0) {
        $columns = $db->query("SHOW COLUMNS FROM user_addresses")->fetchAll(PDO::FETCH_COLUMN);
        $has_location = in_array('location', $columns) && in_array('latitude', $columns) && in_array('longitude', $columns);
        $tables_status['user_addresses'] = $has_location ? '✓' : '✗';
    } else {
        $tables_status['user_addresses'] = 'غير موجود';
    }
    
    $all_ok = !in_array('✗', $tables_status);
    
    return [
        'status' => $all_ok ? 'success' : 'warning',
        'message' => 'addresses: ' . $tables_status['addresses'] . ' | user_addresses: ' . $tables_status['user_addresses'],
        'details' => $tables_status
    ];
});

// 4. Check Products
runDiagnostic('المنتجات', function() use ($db) {
    $stmt = $db->query("SELECT COUNT(*) as count FROM products");
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    // Check if is_active column exists
    $columns = $db->query("SHOW COLUMNS FROM products")->fetchAll(PDO::FETCH_COLUMN);
    $has_is_active = in_array('is_active', $columns);
    $has_active = in_array('active', $columns);
    $has_status = in_array('status', $columns);
    
    $active = 0;
    if ($has_is_active) {
        $stmt = $db->query("SELECT COUNT(*) as active FROM products WHERE is_active = 1");
        $active = $stmt->fetch(PDO::FETCH_ASSOC)['active'];
    } elseif ($has_active) {
        $stmt = $db->query("SELECT COUNT(*) as active FROM products WHERE active = 1");
        $active = $stmt->fetch(PDO::FETCH_ASSOC)['active'];
    } elseif ($has_status) {
        $stmt = $db->query("SELECT COUNT(*) as active FROM products WHERE status = 'active'");
        $active = $stmt->fetch(PDO::FETCH_ASSOC)['active'];
    } else {
        $active = $count; // Assume all active if no status column
    }
    
    $stmt = $db->query("SELECT COUNT(*) as no_image FROM products WHERE (image IS NULL OR image = '')");
    $no_image = $stmt->fetch(PDO::FETCH_ASSOC)['no_image'];
    
    $status = $count > 0 ? 'success' : 'warning';
    
    return [
        'status' => $status,
        'message' => "إجمالي: {$count} | نشط: {$active} | بدون صورة: {$no_image}",
        'details' => ['total' => $count, 'active' => $active, 'no_image' => $no_image, 'has_status_column' => $has_is_active || $has_active || $has_status]
    ];
});

// 5. Check Services
runDiagnostic('خدمات البيوتي', function() use ($db) {
    $stmt = $db->query("SELECT COUNT(*) as count FROM beauty_services");
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    $stmt = $db->query("SELECT COUNT(*) as active FROM beauty_services WHERE is_active = 1");
    $active = $stmt->fetch(PDO::FETCH_ASSOC)['active'];
    
    $stmt = $db->query("SELECT COUNT(*) as with_discount FROM beauty_services WHERE discount_percentage > 0");
    $with_discount = $stmt->fetch(PDO::FETCH_ASSOC)['with_discount'];
    
    return [
        'status' => 'success',
        'message' => "إجمالي: {$count} | نشط: {$active} | بخصم: {$with_discount}",
        'details' => ['total' => $count, 'active' => $active, 'with_discount' => $with_discount]
    ];
});

// 6. Check Orders
runDiagnostic('الطلبات', function() use ($db) {
    $stmt = $db->query("SELECT COUNT(*) as count FROM orders");
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    $stmt = $db->query("SELECT COUNT(*) as pending FROM orders WHERE status = 'pending'");
    $pending = $stmt->fetch(PDO::FETCH_ASSOC)['pending'];
    
    // Check which column exists for total
    $columns = $db->query("SHOW COLUMNS FROM orders")->fetchAll(PDO::FETCH_COLUMN);
    $total_column = in_array('total_amount', $columns) ? 'total_amount' : 
                   (in_array('total_price', $columns) ? 'total_price' : 
                   (in_array('total', $columns) ? 'total' : null));
    
    $revenue = 0;
    if ($total_column) {
        $stmt = $db->query("SELECT SUM({$total_column}) as revenue FROM orders WHERE status = 'completed'");
        $revenue = $stmt->fetch(PDO::FETCH_ASSOC)['revenue'] ?? 0;
    }
    
    return [
        'status' => 'success',
        'message' => "إجمالي: {$count} | قيد الانتظار: {$pending} | الإيرادات: " . number_format($revenue, 2) . " ج.م",
        'details' => ['total' => $count, 'pending' => $pending, 'revenue' => $revenue, 'total_column' => $total_column]
    ];
});

// 7. Check Bookings
runDiagnostic('الحجوزات', function() use ($db) {
    $stmt = $db->query("SELECT COUNT(*) as count FROM beauty_bookings");
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    $stmt = $db->query("SELECT COUNT(*) as pending FROM beauty_bookings WHERE status = 'pending'");
    $pending = $stmt->fetch(PDO::FETCH_ASSOC)['pending'];
    
    $stmt = $db->query("SELECT COUNT(*) as confirmed FROM beauty_bookings WHERE status = 'confirmed'");
    $confirmed = $stmt->fetch(PDO::FETCH_ASSOC)['confirmed'];
    
    return [
        'status' => 'success',
        'message' => "إجمالي: {$count} | قيد الانتظار: {$pending} | مؤكد: {$confirmed}",
        'details' => ['total' => $count, 'pending' => $pending, 'confirmed' => $confirmed]
    ];
});

// 8. Check Categories
runDiagnostic('الفئات', function() use ($db) {
    $stmt = $db->query("SELECT COUNT(*) as count FROM categories");
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    // Check if is_active column exists
    $columns = $db->query("SHOW COLUMNS FROM categories")->fetchAll(PDO::FETCH_COLUMN);
    $has_is_active = in_array('is_active', $columns);
    
    $active = $count; // Default to all active
    if ($has_is_active) {
        $stmt = $db->query("SELECT COUNT(*) as active FROM categories WHERE is_active = 1");
        $active = $stmt->fetch(PDO::FETCH_ASSOC)['active'];
    }
    
    $status = $count > 0 ? 'success' : 'warning';
    
    return [
        'status' => $status,
        'message' => "إجمالي: {$count} | نشط: {$active}",
        'details' => ['total' => $count, 'active' => $active]
    ];
});

// 9. Check Branches
runDiagnostic('الفروع', function() use ($db) {
    $stmt = $db->query("SELECT COUNT(*) as count FROM branches");
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    // Check if is_active column exists
    $columns = $db->query("SHOW COLUMNS FROM branches")->fetchAll(PDO::FETCH_COLUMN);
    $has_is_active = in_array('is_active', $columns);
    
    $active = $count;
    if ($has_is_active) {
        $stmt = $db->query("SELECT COUNT(*) as active FROM branches WHERE is_active = 1");
        $active = $stmt->fetch(PDO::FETCH_ASSOC)['active'];
    }
    
    return [
        'status' => 'success',
        'message' => "إجمالي: {$count} | نشط: {$active}",
        'details' => ['total' => $count, 'active' => $active]
    ];
});

// 10. Check Cart
runDiagnostic('السلة', function() use ($db) {
    $stmt = $db->query("SELECT COUNT(*) as count FROM cart");
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    $stmt = $db->query("SELECT COUNT(DISTINCT user_id) as users FROM cart");
    $users = $stmt->fetch(PDO::FETCH_ASSOC)['users'];
    
    return [
        'status' => 'success',
        'message' => "عدد المنتجات في السلة: {$count} | عدد المستخدمين: {$users}",
        'details' => ['items' => $count, 'users' => $users]
    ];
});

// 11. Check Reviews
runDiagnostic('التقييمات', function() use ($db) {
    $stmt = $db->query("SELECT COUNT(*) as count FROM reviews");
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    // Check if is_approved column exists
    $columns = $db->query("SHOW COLUMNS FROM reviews")->fetchAll(PDO::FETCH_COLUMN);
    $has_is_approved = in_array('is_approved', $columns);
    
    if ($has_is_approved) {
        $stmt = $db->query("SELECT AVG(rating) as avg_rating FROM reviews WHERE is_approved = 1");
    } else {
        $stmt = $db->query("SELECT AVG(rating) as avg_rating FROM reviews");
    }
    $avg_rating = $stmt->fetch(PDO::FETCH_ASSOC)['avg_rating'] ?? 0;
    
    return [
        'status' => 'success',
        'message' => "إجمالي: {$count} | متوسط التقييم: " . number_format($avg_rating, 1) . "/5",
        'details' => ['total' => $count, 'avg_rating' => $avg_rating]
    ];
});

// 12. Check Posts/Blog
runDiagnostic('المدونة', function() use ($db) {
    $stmt = $db->query("SELECT COUNT(*) as count FROM posts");
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    $stmt = $db->query("SELECT COUNT(*) as published FROM posts WHERE status = 'published'");
    $published = $stmt->fetch(PDO::FETCH_ASSOC)['published'];
    
    return [
        'status' => 'success',
        'message' => "إجمالي: {$count} | منشور: {$published}",
        'details' => ['total' => $count, 'published' => $published]
    ];
});

// 13. Check Coupons
runDiagnostic('كوبونات الخصم', function() use ($db) {
    $stmt = $db->query("SELECT COUNT(*) as count FROM coupons");
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    // Check if is_active column exists
    $columns = $db->query("SHOW COLUMNS FROM coupons")->fetchAll(PDO::FETCH_COLUMN);
    $has_is_active = in_array('is_active', $columns);
    $has_expiry = in_array('expiry_date', $columns);
    
    $active = $count;
    if ($has_is_active && $has_expiry) {
        $stmt = $db->query("SELECT COUNT(*) as active FROM coupons WHERE is_active = 1 AND (expiry_date IS NULL OR expiry_date > NOW())");
        $active = $stmt->fetch(PDO::FETCH_ASSOC)['active'];
    } elseif ($has_is_active) {
        $stmt = $db->query("SELECT COUNT(*) as active FROM coupons WHERE is_active = 1");
        $active = $stmt->fetch(PDO::FETCH_ASSOC)['active'];
    }
    
    return [
        'status' => 'success',
        'message' => "إجمالي: {$count} | نشط: {$active}",
        'details' => ['total' => $count, 'active' => $active]
    ];
});

// 14. Check Announcements
runDiagnostic('الإعلانات', function() use ($db) {
    $stmt = $db->query("SELECT COUNT(*) as count FROM announcements");
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    // Check if is_active column exists
    $columns = $db->query("SHOW COLUMNS FROM announcements")->fetchAll(PDO::FETCH_COLUMN);
    $has_is_active = in_array('is_active', $columns);
    
    $active = $count;
    if ($has_is_active) {
        $stmt = $db->query("SELECT COUNT(*) as active FROM announcements WHERE is_active = 1");
        $active = $stmt->fetch(PDO::FETCH_ASSOC)['active'];
    }
    
    return [
        'status' => 'success',
        'message' => "إجمالي: {$count} | نشط: {$active}",
        'details' => ['total' => $count, 'active' => $active]
    ];
});

// 15. Check Uploads Directory
runDiagnostic('مجلد الصور', function() {
    $uploads_dir = '../uploads';
    $writable = is_writable($uploads_dir);
    $size = 0;
    
    if (file_exists($uploads_dir)) {
        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploads_dir));
        foreach ($iterator as $file) {
            if ($file->isFile()) {
                $size += $file->getSize();
            }
        }
    }
    
    $size_mb = round($size / 1024 / 1024, 2);
    
    if (!$writable) {
        return [
            'status' => 'error',
            'message' => 'مجلد الصور غير قابل للكتابة!',
            'details' => ['writable' => false, 'size' => $size_mb . ' MB']
        ];
    }
    
    return [
        'status' => 'success',
        'message' => "المجلد يعمل بشكل صحيح | الحجم: {$size_mb} MB",
        'details' => ['writable' => true, 'size' => $size_mb . ' MB']
    ];
});

// 16. Check PHP Version
runDiagnostic('إصدار PHP', function() {
    $version = phpversion();
    $required = '7.4';
    
    if (version_compare($version, $required, '<')) {
        return [
            'status' => 'warning',
            'message' => "الإصدار الحالي: {$version} | يُنصح بـ {$required} أو أحدث",
            'details' => ['current' => $version, 'required' => $required]
        ];
    }
    
    return [
        'status' => 'success',
        'message' => "الإصدار: {$version}",
        'details' => ['version' => $version]
    ];
});

// 17. Check Required Extensions
runDiagnostic('إضافات PHP المطلوبة', function() {
    $required = ['pdo', 'pdo_mysql', 'gd', 'mbstring', 'json', 'curl'];
    $missing = [];
    
    foreach ($required as $ext) {
        if (!extension_loaded($ext)) {
            $missing[] = $ext;
        }
    }
    
    if (!empty($missing)) {
        return [
            'status' => 'error',
            'message' => 'إضافات مفقودة: ' . implode(', ', $missing),
            'details' => ['missing' => $missing]
        ];
    }
    
    return [
        'status' => 'success',
        'message' => 'جميع الإضافات المطلوبة متوفرة',
        'details' => ['extensions' => $required]
    ];
});

// 18. Check Memory Limit
runDiagnostic('حد الذاكرة', function() {
    $memory_limit = ini_get('memory_limit');
    $memory_bytes = return_bytes($memory_limit);
    $recommended = return_bytes('128M');
    
    if ($memory_bytes < $recommended) {
        return [
            'status' => 'warning',
            'message' => "الحد الحالي: {$memory_limit} | يُنصح بـ 128M أو أكثر",
            'details' => ['current' => $memory_limit, 'recommended' => '128M']
        ];
    }
    
    return [
        'status' => 'success',
        'message' => "الحد الحالي: {$memory_limit}",
        'details' => ['memory_limit' => $memory_limit]
    ];
});

// 18.5. Check Consultations
runDiagnostic('الاستشارات والمكالمات', function() use ($db) {
    // Check if table exists
    $check_table = $db->query("SHOW TABLES LIKE 'consultations'")->rowCount();
    if ($check_table == 0) {
        return [
            'status' => 'warning',
            'message' => 'جدول الاستشارات غير موجود',
            'details' => ['table_exists' => false]
        ];
    }
    
    $stmt = $db->query("SELECT COUNT(*) as count FROM consultations");
    $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    $stmt = $db->query("SELECT COUNT(*) as active_count FROM consultations WHERE is_active = 1");
    $active_count = $stmt->fetch(PDO::FETCH_ASSOC)['active_count'];
    
    // Check bookings table
    $check_bookings = $db->query("SHOW TABLES LIKE 'consultation_bookings'")->rowCount();
    $bookings_count = 0;
    if ($check_bookings > 0) {
        $stmt = $db->query("SELECT COUNT(*) as count FROM consultation_bookings");
        $bookings_count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    }
    
    if ($count == 0) {
        return [
            'status' => 'warning',
            'message' => 'لا توجد استشارات. أضف استشارات جديدة',
            'details' => ['total' => 0, 'active' => 0, 'bookings' => 0]
        ];
    }
    
    return [
        'status' => 'success',
        'message' => "إجمالي: {$count} | نشط: {$active_count} | حجوزات: {$bookings_count}",
        'details' => ['total' => $count, 'active' => $active_count, 'bookings' => $bookings_count]
    ];
});

// 19. Check Orders Table Structure
runDiagnostic('هيكل جدول الطلبات', function() use ($db) {
    $columns = $db->query("SHOW COLUMNS FROM orders")->fetchAll(PDO::FETCH_ASSOC);
    $column_names = array_column($columns, 'Field');
    
    $required_columns = ['id', 'user_id', 'status', 'created_at'];
    $missing = array_diff($required_columns, $column_names);
    
    // Check for total column variants
    $has_total = in_array('total_amount', $column_names) || 
                 in_array('total_price', $column_names) || 
                 in_array('total', $column_names);
    
    if (!empty($missing)) {
        return [
            'status' => 'error',
            'message' => 'أعمدة مفقودة: ' . implode(', ', $missing),
            'details' => ['columns' => $column_names, 'missing' => $missing]
        ];
    }
    
    if (!$has_total) {
        return [
            'status' => 'warning',
            'message' => 'لا يوجد عمود للمجموع (total_amount, total_price, أو total)',
            'details' => ['columns' => $column_names]
        ];
    }
    
    return [
        'status' => 'success',
        'message' => "الجدول يحتوي على " . count($column_names) . " عمود",
        'details' => ['columns' => $column_names]
    ];
});

function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    $val = (int)$val;
    switch($last) {
        case 'g': $val *= 1024;
        case 'm': $val *= 1024;
        case 'k': $val *= 1024;
    }
    return $val;
}

// 20. Check Environment Compatibility
runDiagnostic('توافق البيئة (Environment Compatibility)', function() {
    $issues = [];
    $scanned_files = 0;
    $root_dir = '../'; // Backend root
    
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root_dir));
    foreach ($iterator as $file) {
        if ($file->isFile() && $file->getExtension() === 'php') {
            $scanned_files++;
            $content = file_get_contents($file->getPathname());
            
            // Check for backslashes in include/require paths
            if (preg_match_all('/(include|require)(_once)?\s*\(?\s*[\'"]([^\'"]*\\\\[^\'"]*)[\'"]/', $content, $matches)) {
                foreach ($matches[3] as $match) {
                    // Ignore if it's just escaping a quote
                    if (strpos($match, '\\\'') === false && strpos($match, '\\"') === false) {
                        $rel_path = str_replace($root_dir, '', $file->getPathname());
                        $issues[] = "ملف: $rel_path | مسار خاطئ: $match";
                    }
                }
            }
        }
    }
    
    if (!empty($issues)) {
        return [
            'status' => 'warning',
            'message' => "تم العثور على " . count($issues) . " مسار يستخدم Backslash (\) وهذا قد يسبب مشاكل في Linux",
            'details' => ['scanned_files' => $scanned_files, 'issues' => $issues]
        ];
    }
    
    return [
        'status' => 'success',
        'message' => "تم فحص $scanned_files ملف. جميع المسارات متوافقة مع Linux",
        'details' => ['scanned_files' => $scanned_files]
    ];
});

// Handle JSON Export
if (isset($_GET['action']) && $_GET['action'] === 'export_json') {
    header('Content-Type: application/json');
    header('Content-Disposition: attachment; filename="store_diagnostics_' . date('Y-m-d_H-i') . '.json"');
    
    $report = [
        'generated_at' => date('Y-m-d H:i:s'),
        'environment' => [
            'os' => PHP_OS,
            'php_version' => phpversion(),
            'server' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown'
        ],
        'summary' => [
            'success' => count($success),
            'warnings' => count($warnings),
            'errors' => count($errors)
        ],
        'results' => $results
    ];
    
    echo json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تشخيص المتجر الشامل</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family: 'Tajawal', sans-serif; }
        .diagnostic-card { transition: all 0.3s ease; }
        .diagnostic-card:hover { transform: translateY(-2px); }
    </style>
</head>
<body class="bg-gray-50">

<div class="min-h-screen py-8">
    <div class="max-w-7xl mx-auto px-4">
        
        <!-- Header -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-stethoscope text-blue-600 ml-2"></i>
                        تشخيص المتجر الشامل
                    </h1>
                    <p class="text-gray-600">فحص شامل لجميع مكونات المتجر</p>
                </div>
                <a href="dashboard.php" class="px-6 py-3 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition">
                    <i class="fas fa-arrow-right ml-2"></i>
                    العودة للوحة التحكم
                </a>
                <a href="?action=export_json" class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition ml-2">
                    <i class="fas fa-file-export ml-2"></i>
                    تصدير تقرير JSON
                </a>
            </div>
        </div>

        <!-- Summary -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="bg-green-50 border-2 border-green-200 rounded-xl p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-green-600 font-medium mb-1">نجح</p>
                        <p class="text-3xl font-bold text-green-700"><?php echo count($success); ?></p>
                    </div>
                    <div class="bg-green-200 p-4 rounded-full">
                        <i class="fas fa-check-circle text-green-700 text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-yellow-50 border-2 border-yellow-200 rounded-xl p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-yellow-600 font-medium mb-1">تحذيرات</p>
                        <p class="text-3xl font-bold text-yellow-700"><?php echo count($warnings); ?></p>
                    </div>
                    <div class="bg-yellow-200 p-4 rounded-full">
                        <i class="fas fa-exclamation-triangle text-yellow-700 text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-red-50 border-2 border-red-200 rounded-xl p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-red-600 font-medium mb-1">أخطاء</p>
                        <p class="text-3xl font-bold text-red-700"><?php echo count($errors); ?></p>
                    </div>
                    <div class="bg-red-200 p-4 rounded-full">
                        <i class="fas fa-times-circle text-red-700 text-2xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Diagnostics Results -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <?php foreach ($results as $name => $result): ?>
            <div class="diagnostic-card bg-white rounded-xl shadow-md p-6 border-r-4 
                <?php 
                    echo $result['status'] === 'success' ? 'border-green-500' : 
                        ($result['status'] === 'warning' ? 'border-yellow-500' : 'border-red-500');
                ?>">
                
                <div class="flex items-start justify-between mb-3">
                    <h3 class="text-lg font-bold text-gray-900"><?php echo $name; ?></h3>
                    <span class="px-3 py-1 rounded-full text-xs font-medium
                        <?php 
                            echo $result['status'] === 'success' ? 'bg-green-100 text-green-700' : 
                                ($result['status'] === 'warning' ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700');
                        ?>">
                        <?php 
                            echo $result['status'] === 'success' ? '✓ نجح' : 
                                ($result['status'] === 'warning' ? '⚠ تحذير' : '✗ خطأ');
                        ?>
                    </span>
                </div>

                <p class="text-gray-700 text-sm mb-3"><?php echo $result['message']; ?></p>

                <?php if (!empty($result['details'])): ?>
                <details class="text-xs text-gray-500">
                    <summary class="cursor-pointer hover:text-gray-700">عرض التفاصيل</summary>
                    <pre class="mt-2 p-2 bg-gray-50 rounded overflow-x-auto"><?php echo json_encode($result['details'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); ?></pre>
                </details>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- Quick Fixes -->
        <?php if (count($errors) > 0 || count($warnings) > 0): ?>
        <div class="mt-8 bg-red-50 border-2 border-red-200 rounded-xl p-6">
            <h2 class="text-xl font-bold text-red-900 mb-4">
                <i class="fas fa-exclamation-triangle text-red-600 ml-2"></i>
                إصلاحات سريعة
            </h2>
            <div class="space-y-3">
                <?php if (in_array('هيكل جدول الطلبات', $warnings)): ?>
                <div class="bg-white p-4 rounded-lg border border-red-200">
                    <p class="text-sm text-gray-700 mb-2">
                        <strong>مشكلة:</strong> جدول الطلبات يحتاج تحديث
                    </p>
                    <button onclick="fixOrdersTable()" 
                            class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition text-sm">
                        <i class="fas fa-wrench ml-1"></i>
                        إصلاح جدول الطلبات
                    </button>
                </div>
                <?php endif; ?>
                
                <?php if (in_array('جدول المستخدمين', $errors)): ?>
                <div class="bg-white p-4 rounded-lg border border-red-200">
                    <p class="text-sm text-gray-700 mb-2">
                        <strong>مشكلة:</strong> لا يوجد مستخدمين مدراء
                    </p>
                    <a href="../create-admin.php" 
                       class="inline-block px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition text-sm">
                        <i class="fas fa-user-plus ml-1"></i>
                        إنشاء حساب مدير
                    </a>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Actions -->
        <div class="mt-8 bg-white rounded-xl shadow-lg p-6">
            <h2 class="text-xl font-bold text-gray-900 mb-4">
                <i class="fas fa-tools text-blue-600 ml-2"></i>
                إجراءات سريعة
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <a href="backup.php" 
                   class="block p-4 bg-green-50 border border-green-200 rounded-lg hover:bg-green-100 transition text-center">
                    <i class="fas fa-download text-green-600 text-2xl mb-2"></i>
                    <p class="font-medium text-gray-900">نسخ احتياطي</p>
                </a>
                
                <a href="services/index.php" 
                   class="block p-4 bg-pink-50 border border-pink-200 rounded-lg hover:bg-pink-100 transition text-center">
                    <i class="fas fa-spa text-pink-600 text-2xl mb-2"></i>
                    <p class="font-medium text-gray-900">إدارة الخدمات</p>
                </a>
                
                <button onclick="location.reload()" 
                        class="block w-full p-4 bg-purple-50 border border-purple-200 rounded-lg hover:bg-purple-100 transition text-center">
                    <i class="fas fa-sync text-purple-600 text-2xl mb-2"></i>
                    <p class="font-medium text-gray-900">إعادة الفحص</p>
                </button>
            </div>
        </div>

<script>
function fixOrdersTable() {
    if (confirm('هل تريد إضافة عمود total_amount لجدول الطلبات؟')) {
        fetch('?action=fix_orders_table')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('تم الإصلاح بنجاح!');
                    location.reload();
                } else {
                    alert('حدث خطأ: ' + data.message);
                }
            });
    }
}
</script>

        <!-- Footer -->
        <div class="mt-6 text-center text-sm text-gray-500">
            <p>آخر فحص: <?php echo date('Y-m-d H:i:s'); ?></p>
        </div>

    </div>
</div>

</body>
</html>
