<?php
// api/admin/index.php - Developed for Auto Tester (Cyber Scan System)
// النسخة الكاملة - تشمل جميع الدوال من الملفات الـ 45

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

require_once '../config/database.php';

class AdminAPI {
    private $conn;
    private $action;
    private $method;
    private $admin_id;
    private $admin_role;

    public function __construct() {
        $this->conn = getDatabaseConnection();
        $this->method = $_SERVER['REQUEST_METHOD'];
        $this->action = $_GET['action'] ?? '';
    }

    public function handle() {
        // 1. استثناء تسجيل الدخول من التحقق
        if ($this->action === 'login') {
            $this->login();
            return;
        }

        // 2. التحقق من المصادقة والتوكن
        if (!$this->isAuthenticated()) {
            $this->jsonResponse(['error' => 'غير مصرح لك بالوصول، يرجى تسجيل الدخول'], 401);
        }

        // 3. توجيه العمليات بناءً على الـ Action
        switch ($this->action) {
            // ========== الإحصائيات ==========
            case 'get_stats':
            case 'get_dashboard_stats':
                $this->getDashboardStats();
                break;
                
            // ========== المستخدمين ==========
            case 'get_users':
                $this->getUsers();
                break;
            case 'add_user':
                if ($this->method !== 'POST') $this->jsonResponse(['error' => 'Method Not Allowed'], 405);
                $this->addUser();
                break;
            case 'update_user':
                $this->updateUser();
                break;
            case 'delete_user':
                $this->deleteUser();
                break;
            case 'toggle_user_status':
                $this->toggleUserStatus();
                break;
                
            // ========== الفاحصين ==========
            case 'get_inspectors':
                $this->getInspectors();
                break;
            case 'add_inspector':
                $this->addInspector();
                break;
            case 'update_inspector':
                $this->updateInspector();
                break;
            case 'delete_inspector':
                $this->deleteInspector();
                break;
            case 'get_available_inspectors':
                $this->getAvailableInspectors();
                break;
            case 'check_inspectors_table':
                $this->checkInspectorsTable();
                break;
                
            // ========== العملاء ==========
            case 'get_clients':
                $this->getClients();
                break;
            case 'update_client_status':
                $this->updateClientStatus();
                break;
            case 'get_client_cars':
                $this->getClientCars();
                break;
                
            // ========== الفحوصات ==========
            case 'get_inspections':
                $this->getInspections();
                break;
            case 'get_full_inspection_details':
                $this->getFullInspectionDetails();
                break;
            case 'update_inspection_status':
                $this->updateInspectionStatus();
                break;
            case 'get_inspection_types':
                $this->getInspectionTypes();
                break;
            case 'calculate_car_score':
                $this->handleCarScoring();
                break;
                
            // ========== الطلبات ==========
            case 'get_requests':
            case 'get_all_requests':
                $this->getRequests();
                break;
            case 'get_pending_requests':
            case 'getpending_requests':
                $this->getPendingRequests();
                break;
            case 'get_administrative_requests':
                $this->getAdministrativeRequests();
                break;
            case 'get_request_details':
                $this->getRequestDetails();
                break;
            case 'update_request_status':
                $this->updateRequestStatus();
                break;
                
            // ========== طلبات الشركات ==========
            case 'get_companies':
                $this->getCompanies();
                break;
            case 'get_companies_requests':
                $this->getCompaniesRequests();
                break;
                
            // ========== طلبات المتدربين والمشرفين ==========
            case 'get_trainees_requests':
                $this->getTraineesRequests();
                break;
            case 'get_supervisors_requests':
                $this->getSupervisorsRequests();
                break;
            case 'get_supervisor_applications':
                $this->getSupervisorApplications();
                break;
            case 'update_supervisor_application':
                $this->updateSupervisorApplication();
                break;
                
            // ========== طلبات التسجيل والتوظيف ==========
            case 'get_registration_requests':
                $this->getRegistrationRequests();
                break;
            case 'get_job_applications':
                $this->getJobApplications();
                break;
            case 'update_application_status':
                $this->updateApplicationStatus();
                break;
                
            // ========== الصلاحيات والأذونات ==========
            case 'get_permission_requests':
                $this->getPermissionRequests();
                break;
                
            // ========== المدفوعات ==========
            case 'approve_payment':
                $this->approvePayment();
                break;
                
            // ========== الإشعارات ==========
            case 'get_notifications':
                $this->getNotifications();
                break;
            case 'mark_notifications_read':
                $this->markNotificationsRead();
                break;
                
            // ========== الأنشطة ==========
            case 'get_activities':
                $this->getActivities();
                break;
                
            // ========== البحث العام ==========
            case 'global_search':
                $this->globalSearch();
                break;
                
            // ========== النسخ الاحتياطي ==========
            case 'create_backup':
                $this->createBackup();
                break;
            case 'get_backup_info':
                $this->getBackupInfo();
                break;
                
            // ========== الإعدادات العامة ==========
            case 'get_settings':
                $this->getSettings();
                break;
            case 'update_settings':
                $this->updateSettings();
                break;
                
            default:
                $this->jsonResponse(['error' => 'الإجراء المطلوب غير مدرج في النظام'], 400);
        }
    }

    // ========== المصادقة ==========
    private function login() {
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!$data || empty($data['email']) || empty($data['password'])) {
            $this->jsonResponse(['error' => 'البريد الإلكتروني وكلمة المرور مطلوبة'], 400);
        }
        
        $email = $this->conn->real_escape_string($data['email']);
        $stmt = $this->conn->prepare("SELECT id, full_name, email, password, role FROM users WHERE email = ? AND status = 'active'");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($user = $result->fetch_assoc()) {
            if (password_verify($data['password'], $user['password'])) {
                // إنشاء توكن جديد
                $token = bin2hex(random_bytes(32));
                $expires = date('Y-m-d H:i:s', strtotime('+24 hours'));
                
                $stmt2 = $this->conn->prepare("INSERT INTO admin_sessions (user_id, token, expires_at) VALUES (?, ?, ?)");
                $stmt2->bind_param("iss", $user['id'], $token, $expires);
                $stmt2->execute();
                
                unset($user['password']);
                $this->jsonResponse([
                    'success' => true,
                    'token' => $token,
                    'user' => $user
                ]);
                return;
            }
        }
        
        $this->jsonResponse(['error' => 'بيانات الدخول غير صحيحة'], 401);
    }

    private function isAuthenticated() {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        
        if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            $token = $matches[1];
            $stmt = $this->conn->prepare("SELECT user_id, u.role FROM admin_sessions s JOIN users u ON s.user_id = u.id WHERE s.token = ? AND s.expires_at > NOW()");
            $stmt->bind_param("s", $token);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($row = $result->fetch_assoc()) {
                $this->admin_id = $row['user_id'];
                $this->admin_role = $row['role'];
                return true;
            }
        }
        return false;
    }

    // ========== الإحصائيات ==========
    private function getDashboardStats() {
        $stats = [];
        
        $stats['total_users'] = $this->getSingleValue("SELECT COUNT(*) FROM users");
        $stats['total_inspectors'] = $this->getSingleValue("SELECT COUNT(*) FROM users WHERE role = 'inspector'");
        $stats['total_clients'] = $this->getSingleValue("SELECT COUNT(*) FROM users WHERE role = 'client'");
        $stats['total_inspections'] = $this->getSingleValue("SELECT COUNT(*) FROM inspections");
        $stats['total_revenue'] = $this->getSingleValue("SELECT SUM(amount) FROM payments") ?? 0;
        $stats['active_centers'] = $this->getSingleValue("SELECT COUNT(*) FROM centers WHERE status = 'active'");
        
        // الفحوصات حسب الحالة
        $stats['pending_inspections'] = $this->getSingleValue("SELECT COUNT(*) FROM inspections WHERE status = 'pending'");
        $stats['in_progress_inspections'] = $this->getSingleValue("SELECT COUNT(*) FROM inspections WHERE status IN ('assigned', 'in_progress')");
        $stats['completed_inspections'] = $this->getSingleValue("SELECT COUNT(*) FROM inspections WHERE status = 'completed'");
        $stats['cancelled_inspections'] = $this->getSingleValue("SELECT COUNT(*) FROM inspections WHERE status = 'cancelled'");
        
        $today = date('Y-m-d');
        $stats['today_inspections'] = $this->getSingleValue("SELECT COUNT(*) FROM inspections WHERE DATE(created_at) = '$today'");
        
        // أفضل الفاحصين
        $sql = "SELECT u.id, u.full_name, COUNT(i.id) as inspections_count 
                FROM users u 
                LEFT JOIN inspections i ON u.id = i.inspector_id 
                WHERE u.role = 'inspector' 
                GROUP BY u.id 
                ORDER BY inspections_count DESC 
                LIMIT 5";
        $stats['inspector_stats'] = $this->conn->query($sql)->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $stats]);
    }

    // ========== إدارة المستخدمين ==========
    private function getUsers() {
        $role = $_GET['role'] ?? '';
        $limit = (int)($_GET['limit'] ?? 100);
        $offset = (int)($_GET['offset'] ?? 0);
        
        $sql = "SELECT id, full_name, email, phone, role, status, created_at FROM users";
        if ($role) {
            $sql .= " WHERE role = '" . $this->conn->real_escape_string($role) . "'";
        }
        $sql .= " ORDER BY created_at DESC LIMIT $limit OFFSET $offset";
        
        $result = $this->conn->query($sql);
        $users = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $users]);
    }

    private function addUser() {
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (empty($data['full_name']) || empty($data['email']) || empty($data['password'])) {
            $this->jsonResponse(['error' => 'جميع الحقول الأساسية مطلوبة'], 400);
        }

        $full_name = $data['full_name'];
        $email = $data['email'];
        $phone = $data['phone'] ?? '';
        $role = $data['role'] ?? 'client';
        $password = password_hash($data['password'], PASSWORD_DEFAULT);

        $stmt = $this->conn->prepare("INSERT INTO users (full_name, email, phone, role, password) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("sssss", $full_name, $email, $phone, $role, $password);

        if ($stmt->execute()) {
            $this->jsonResponse(['success' => true, 'message' => 'تم إنشاء الحساب بنجاح', 'user_id' => $stmt->insert_id]);
        } else {
            $this->jsonResponse(['error' => 'فشل التسجيل: ' . $this->conn->error], 500);
        }
    }

    private function updateUser() {
        $data = json_decode(file_get_contents('php://input'), true);
        if (empty($data['id'])) {
            $this->jsonResponse(['error' => 'معرف المستخدم مطلوب'], 400);
        }
        
        $id = (int)$data['id'];
        $updates = [];
        $params = [];
        $types = '';
        
        $allowedFields = ['full_name', 'email', 'phone', 'role', 'status'];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $updates[] = "$field = ?";
                $params[] = $data[$field];
                $types .= 's';
            }
        }
        
        if (isset($data['password']) && !empty($data['password'])) {
            $updates[] = "password = ?";
            $params[] = password_hash($data['password'], PASSWORD_DEFAULT);
            $types .= 's';
        }
        
        if (empty($updates)) {
            $this->jsonResponse(['error' => 'لا توجد بيانات للتحديث'], 400);
        }
        
        $params[] = $id;
        $types .= 'i';
        
        $sql = "UPDATE users SET " . implode(', ', $updates) . " WHERE id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        
        if ($stmt->execute()) {
            $this->jsonResponse(['success' => true, 'message' => 'تم تحديث المستخدم بنجاح']);
        } else {
            $this->jsonResponse(['error' => $this->conn->error], 500);
        }
    }

    private function deleteUser() {
        $id = (int)($_GET['id'] ?? 0);
        if (!$id) {
            $this->jsonResponse(['error' => 'معرف المستخدم مطلوب'], 400);
        }
        
        $stmt = $this->conn->prepare("DELETE FROM users WHERE id = ? AND role != 'admin'");
        $stmt->bind_param("i", $id);
        
        if ($stmt->execute() && $stmt->affected_rows > 0) {
            $this->jsonResponse(['success' => true, 'message' => 'تم حذف المستخدم بنجاح']);
        } else {
            $this->jsonResponse(['error' => 'لا يمكن حذف هذا المستخدم'], 400);
        }
    }

    private function toggleUserStatus() {
        $id = (int)($_GET['id'] ?? 0);
        $stmt = $this->conn->prepare("UPDATE users SET status = IF(status = 'active', 'inactive', 'active') WHERE id = ?");
        $stmt->bind_param("i", $id);
        
        if ($stmt->execute()) {
            $this->jsonResponse(['success' => true, 'message' => 'تم تغيير الحالة بنجاح']);
        } else {
            $this->jsonResponse(['error' => $this->conn->error], 500);
        }
    }

    // ========== إدارة الفاحصين ==========
    private function getInspectors() {
        $sql = "SELECT u.*, COUNT(i.id) as inspections_count 
                FROM users u 
                LEFT JOIN inspections i ON i.inspector_id = u.id 
                WHERE u.role = 'inspector' 
                GROUP BY u.id 
                ORDER BY u.full_name";
        $result = $this->conn->query($sql);
        $inspectors = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $inspectors]);
    }

    private function addInspector() {
        $data = json_decode(file_get_contents('php://input'), true);
        $data['role'] = 'inspector';
        // إعادة استخدام addUser مع تعديل
        $_POST = $data;
        $this->addUser();
    }

    private function updateInspector() {
        $this->updateUser();
    }

    private function deleteInspector() {
        $this->deleteUser();
    }

    private function getAvailableInspectors() {
        $date = $this->conn->real_escape_string($_GET['date'] ?? date('Y-m-d'));
        
        $sql = "SELECT u.* FROM users u 
                WHERE u.role = 'inspector' AND u.status = 'active'
                AND u.id NOT IN (
                    SELECT inspector_id FROM inspections 
                    WHERE DATE(scheduled_date) = '$date' AND status != 'completed'
                )";
        
        $result = $this->conn->query($sql);
        $inspectors = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $inspectors]);
    }

    private function checkInspectorsTable() {
        $result = $this->conn->query("SHOW TABLES LIKE 'inspectors'");
        $exists = $result->num_rows > 0;
        
        if (!$exists) {
            // إنشاء الجدول إذا لم يكن موجوداً
            $this->conn->query("CREATE TABLE IF NOT EXISTS inspectors (
                id INT PRIMARY KEY AUTO_INCREMENT,
                user_id INT UNIQUE,
                specialization VARCHAR(255),
                experience_years INT DEFAULT 0,
                license_number VARCHAR(100),
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
            )");
        }
        
        $this->jsonResponse(['success' => true, 'table_exists' => $exists]);
    }

    // ========== إدارة العملاء ==========
    private function getClients() {
        $sql = "SELECT * FROM users WHERE role = 'client' ORDER BY created_at DESC";
        $result = $this->conn->query($sql);
        $clients = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $clients]);
    }

    private function updateClientStatus() {
        $this->toggleUserStatus();
    }

    private function getClientCars() {
        $clientId = (int)($_GET['client_id'] ?? 0);
        $sql = "SELECT * FROM client_cars WHERE client_id = $clientId ORDER BY is_default DESC";
        $result = $this->conn->query($sql);
        $cars = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $cars]);
    }

    // ========== إدارة الفحوصات ==========
    private function getInspections() {
        $limit = (int)($_GET['limit'] ?? 50);
        $status = $_GET['status'] ?? '';
        $inspectorId = (int)($_GET['inspector_id'] ?? 0);
        
        $sql = "SELECT i.*, 
                       u.full_name as customer_name, 
                       u.phone as customer_phone,
                       ins.full_name as inspector_name
                FROM inspections i 
                LEFT JOIN users u ON i.user_id = u.id 
                LEFT JOIN users ins ON i.inspector_id = ins.id
                WHERE 1=1";
        
        if ($status) {
            $sql .= " AND i.status = '" . $this->conn->real_escape_string($status) . "'";
        }
        if ($inspectorId) {
            $sql .= " AND i.inspector_id = $inspectorId";
        }
        
        $sql .= " ORDER BY i.created_at DESC LIMIT $limit";
        
        $result = $this->conn->query($sql);
        $inspections = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $inspections]);
    }

    private function getFullInspectionDetails() {
        $id = (int)($_GET['id'] ?? 0);
        
        $sql = "SELECT i.*, 
                       u.full_name as customer_name, u.phone as customer_phone, u.email as customer_email,
                       ins.full_name as inspector_name, ins.phone as inspector_phone,
                       c.name as center_name, c.address as center_address
                FROM inspections i 
                LEFT JOIN users u ON i.user_id = u.id
                LEFT JOIN users ins ON i.inspector_id = ins.id
                LEFT JOIN centers c ON i.center_id = c.id
                WHERE i.id = $id";
        
        $result = $this->conn->query($sql);
        $inspection = $result->fetch_assoc();
        
        // جلب التفاصيل الفنية إن وجدت
        $detailsSql = "SELECT * FROM inspection_details WHERE inspection_id = $id";
        $detailsResult = $this->conn->query($detailsSql);
        $inspection['technical_details'] = $detailsResult->fetch_assoc();
        
        $this->jsonResponse(['success' => true, 'data' => $inspection]);
    }

    private function updateInspectionStatus() {
        $data = json_decode(file_get_contents('php://input'), true);
        $id = (int)$data['id'];
        $status = $this->conn->real_escape_string($data['status']);
        $inspectorId = isset($data['inspector_id']) ? (int)$data['inspector_id'] : 0;
        
        $sql = "UPDATE inspections SET status = '$status'";
        if ($inspectorId) {
            $sql .= ", inspector_id = $inspectorId";
        }
        $sql .= " WHERE id = $id";
        
        if ($this->conn->query($sql)) {
            $this->jsonResponse(['success' => true, 'message' => 'تم تحديث حالة الفحص']);
        } else {
            $this->jsonResponse(['error' => $this->conn->error], 500);
        }
    }

    private function getInspectionTypes() {
        $sql = "SELECT * FROM inspection_types WHERE status = 'active' ORDER BY name";
        $result = $this->conn->query($sql);
        $types = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $types]);
    }

    private function handleCarScoring() {
        $inspection_id = (int)($_GET['id'] ?? 0);
        
        $stmt = $this->conn->prepare("SELECT * FROM inspection_details WHERE inspection_id = ?");
        $stmt->bind_param("i", $inspection_id);
        $stmt->execute();
        $details = $stmt->get_result()->fetch_assoc();

        if (!$details) {
            $this->jsonResponse(['error' => 'بيانات الفحص غير موجودة'], 404);
        }

        $score = 100;
        if (($details['engine_status'] ?? '') === 'major_issue') $score -= 30;
        if (($details['chassis_damage'] ?? '') === 'yes') $score -= 40;
        if (($details['gearbox_status'] ?? '') === 'repairs_needed') $score -= 15;
        if (($details['odometer'] ?? 0) > 200000) $score -= 10;
        if (($details['accident_history'] ?? '') === 'yes') $score -= 20;

        $final_score = max(0, min(100, $score));

        $update = $this->conn->prepare("UPDATE inspections SET car_score = ?, rating_text = ? WHERE id = ?");
        $rating = $this->getRatingText($final_score);
        $update->bind_param("isi", $final_score, $rating, $inspection_id);
        $update->execute();

        $this->jsonResponse([
            'success' => true, 
            'inspection_id' => $inspection_id,
            'score' => $final_score,
            'rating' => $rating
        ]);
    }

    // ========== إدارة الطلبات ==========
    private function getRequests() {
        $type = $_GET['type'] ?? 'all';
        $status = $_GET['status'] ?? '';
        $limit = (int)($_GET['limit'] ?? 50);
        
        $sql = "SELECT r.*, u.full_name as user_name, u.phone as user_phone 
                FROM requests r 
                LEFT JOIN users u ON r.user_id = u.id 
                WHERE 1=1";
        
        if ($type !== 'all') {
            $sql .= " AND r.request_type = '" . $this->conn->real_escape_string($type) . "'";
        }
        if ($status) {
            $sql .= " AND r.status = '" . $this->conn->real_escape_string($status) . "'";
        }
        
        $sql .= " ORDER BY r.created_at DESC LIMIT $limit";
        
        $result = $this->conn->query($sql);
        $requests = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $requests]);
    }

    private function getPendingRequests() {
        $_GET['status'] = 'pending';
        $this->getRequests();
    }

    private function getAdministrativeRequests() {
        $_GET['type'] = 'administrative';
        $this->getRequests();
    }

    private function getRequestDetails() {
        $id = (int)($_GET['id'] ?? 0);
        $sql = "SELECT r.*, u.full_name as user_name, u.email, u.phone 
                FROM requests r 
                LEFT JOIN users u ON r.user_id = u.id 
                WHERE r.id = $id";
        $result = $this->conn->query($sql);
        $request = $result->fetch_assoc();
        
        $this->jsonResponse(['success' => true, 'data' => $request]);
    }

    private function updateRequestStatus() {
        $data = json_decode(file_get_contents('php://input'), true);
        $id = (int)$data['id'];
        $status = $this->conn->real_escape_string($data['status']);
        $notes = $this->conn->real_escape_string($data['notes'] ?? '');
        
        $sql = "UPDATE requests SET status = '$status', admin_notes = '$notes', updated_at = NOW() WHERE id = $id";
        
        if ($this->conn->query($sql)) {
            $this->jsonResponse(['success' => true, 'message' => 'تم تحديث حالة الطلب']);
        } else {
            $this->jsonResponse(['error' => $this->conn->error], 500);
        }
    }

    // ========== الشركات ==========
    private function getCompanies() {
        $sql = "SELECT * FROM companies ORDER BY name";
        $result = $this->conn->query($sql);
        $companies = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $companies]);
    }

    private function getCompaniesRequests() {
        $companyId = (int)($_GET['company_id'] ?? 0);
        $sql = "SELECT r.*, u.full_name as user_name 
                FROM requests r 
                LEFT JOIN users u ON r.user_id = u.id 
                WHERE r.company_id = $companyId 
                ORDER BY r.created_at DESC";
        $result = $this->conn->query($sql);
        $requests = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $requests]);
    }

    // ========== المتدربين والمشرفين ==========
    private function getTraineesRequests() {
        $sql = "SELECT * FROM trainee_requests WHERE status = 'pending' ORDER BY created_at DESC";
        $result = $this->conn->query($sql);
        $requests = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $requests]);
    }

    private function getSupervisorsRequests() {
        $sql = "SELECT * FROM supervisor_requests WHERE status = 'pending' ORDER BY created_at DESC";
        $result = $this->conn->query($sql);
        $requests = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $requests]);
    }

    private function getSupervisorApplications() {
        $sql = "SELECT sa.*, u.full_name, u.email, u.phone 
                FROM supervisor_applications sa 
                JOIN users u ON sa.user_id = u.id 
                WHERE sa.status = 'pending' 
                ORDER BY sa.created_at DESC";
        $result = $this->conn->query($sql);
        $applications = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $applications]);
    }

    private function updateSupervisorApplication() {
        $data = json_decode(file_get_contents('php://input'), true);
        $id = (int)$data['id'];
        $status = $this->conn->real_escape_string($data['status']);
        
        $sql = "UPDATE supervisor_applications SET status = '$status', reviewed_at = NOW() WHERE id = $id";
        
        if ($this->conn->query($sql) && $status === 'approved') {
            // تحديث دور المستخدم إلى مشرف
            $this->conn->query("UPDATE users SET role = 'supervisor' WHERE id = (SELECT user_id FROM supervisor_applications WHERE id = $id)");
        }
        
        $this->jsonResponse(['success' => true]);
    }

    // ========== طلبات التسجيل والتوظيف ==========
    private function getRegistrationRequests() {
        $sql = "SELECT * FROM registration_requests WHERE status = 'pending' ORDER BY created_at DESC";
        $result = $this->conn->query($sql);
        $requests = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $requests]);
    }

    private function getJobApplications() {
        $sql = "SELECT ja.*, j.title as job_title 
                FROM job_applications ja 
                JOIN jobs j ON ja.job_id = j.id 
                WHERE ja.status = 'pending' 
                ORDER BY ja.created_at DESC";
        $result = $this->conn->query($sql);
        $applications = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $applications]);
    }

    private function updateApplicationStatus() {
        $data = json_decode(file_get_contents('php://input'), true);
        $id = (int)$data['id'];
        $status = $this->conn->real_escape_string($data['status']);
        $table = $this->conn->real_escape_string($data['table'] ?? 'registration_requests');
        
        $sql = "UPDATE $table SET status = '$status', reviewed_at = NOW() WHERE id = $id";
        
        if ($this->conn->query($sql)) {
            $this->jsonResponse(['success' => true, 'message' => 'تم تحديث حالة الطلب']);
        } else {
            $this->jsonResponse(['error' => $this->conn->error], 500);
        }
    }

    // ========== الصلاحيات ==========
    private function getPermissionRequests() {
        $sql = "SELECT pr.*, u.full_name, u.email, u.role 
                FROM permission_requests pr 
                JOIN users u ON pr.user_id = u.id 
                WHERE pr.status = 'pending' 
                ORDER BY pr.created_at DESC";
        $result = $this->conn->query($sql);
        $requests = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $requests]);
    }

    // ========== المدفوعات ==========
    private function approvePayment() {
        $data = json_decode(file_get_contents('php://input'), true);
        $id = (int)$data['id'];
        
        $sql = "UPDATE payments SET status = 'approved', approved_at = NOW() WHERE id = $id";
        
        if ($this->conn->query($sql)) {
            $this->jsonResponse(['success' => true, 'message' => 'تم اعتماد الدفع']);
        } else {
            $this->jsonResponse(['error' => $this->conn->error], 500);
        }
    }

    // ========== الإشعارات ==========
    private function getNotifications() {
        $limit = (int)($_GET['limit'] ?? 50);
        $userId = $this->admin_id;
        
        $sql = "SELECT * FROM notifications 
                WHERE user_id = $userId OR user_id IS NULL 
                ORDER BY created_at DESC LIMIT $limit";
        $result = $this->conn->query($sql);
        $notifications = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $notifications]);
    }

    private function markNotificationsRead() {
        $data = json_decode(file_get_contents('php://input'), true);
        $ids = $data['ids'] ?? [];
        
        if (!empty($ids)) {
            $idsStr = implode(',', array_map('intval', $ids));
            $this->conn->query("UPDATE notifications SET is_read = 1 WHERE id IN ($idsStr)");
        }
        
        $this->jsonResponse(['success' => true]);
    }

    // ========== الأنشطة ==========
    private function getActivities() {
        $limit = (int)($_GET['limit'] ?? 50);
        
        $sql = "SELECT a.*, u.full_name as user_name 
                FROM activities a 
                LEFT JOIN users u ON a.user_id = u.id 
                ORDER BY a.created_at DESC LIMIT $limit";
        $result = $this->conn->query($sql);
        $activities = $result->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $activities]);
    }

    // ========== البحث العام ==========
    private function globalSearch() {
        $keyword = $this->conn->real_escape_string($_GET['keyword'] ?? '');
        
        if (strlen($keyword) < 2) {
            $this->jsonResponse(['success' => true, 'data' => []]);
        }
        
        $results = [];
        
        // بحث في المستخدمين
        $sql = "SELECT id, full_name, email, phone, role, 'user' as type FROM users 
                WHERE full_name LIKE '%$keyword%' OR email LIKE '%$keyword%' OR phone LIKE '%$keyword%' LIMIT 10";
        $results['users'] = $this->conn->query($sql)->fetch_all(MYSQLI_ASSOC);
        
        // بحث في الفحوصات
        $sql = "SELECT i.id, i.request_number, i.status, u.full_name as customer_name, 'inspection' as type 
                FROM inspections i
                LEFT JOIN users u ON i.user_id = u.id
                WHERE i.request_number LIKE '%$keyword%' OR u.full_name LIKE '%$keyword%' LIMIT 10";
        $results['inspections'] = $this->conn->query($sql)->fetch_all(MYSQLI_ASSOC);
        
        // بحث في الطلبات
        $sql = "SELECT id, request_type, status, details, 'request' as type 
                FROM requests 
                WHERE details LIKE '%$keyword%' LIMIT 10";
        $results['requests'] = $this->conn->query($sql)->fetch_all(MYSQLI_ASSOC);
        
        $this->jsonResponse(['success' => true, 'data' => $results]);
    }

    // ========== النسخ الاحتياطي ==========
    private function createBackup() {
        $backupDir = dirname(__DIR__, 2) . '/backups/';
        if (!is_dir($backupDir)) {
            mkdir($backupDir, 0755, true);
        }
        
        $filename = 'backup_' . date('Y-m-d_H-i-s') . '.sql';
        $filepath = $backupDir . $filename;
        
        // تصدير قاعدة البيانات
        $tables = [];
        $result = $this->conn->query("SHOW TABLES");
        while ($row = $result->fetch_row()) {
            $tables[] = $row[0];
        }
        
        $output = "-- Auto Tester Database Backup\n-- Date: " . date('Y-m-d H:i:s') . "\n\n";
        
        foreach ($tables as $table) {
            $output .= "DROP TABLE IF EXISTS `$table`;\n";
            $createResult = $this->conn->query("SHOW CREATE TABLE `$table`");
            $createRow = $createResult->fetch_row();
            $output .= $createRow[1] . ";\n\n";
            
            $dataResult = $this->conn->query("SELECT * FROM `$table`");
            while ($row = $dataResult->fetch_assoc()) {
                $values = array_map(function($val) {
                    return $val === null ? 'NULL' : "'" . $this->conn->real_escape_string($val) . "'";
                }, $row);
                $output .= "INSERT INTO `$table` VALUES (" . implode(',', $values) . ");\n";
            }
            $output .= "\n";
        }
        
        file_put_contents($filepath, $output);
        
        $this->jsonResponse([
            'success' => true,
            'message' => 'تم إنشاء النسخة الاحتياطية',
            'file' => $filename,
            'size' => filesize($filepath)
        ]);
    }

    private function getBackupInfo() {
        $backupDir = dirname(__DIR__, 2) . '/backups/';
        $backups = [];
        
        if (is_dir($backupDir)) {
            $files = glob($backupDir . '*.sql');
            foreach ($files as $file) {
                $backups[] = [
                    'name' => basename($file),
                    'size' => filesize($file),
                    'date' => date('Y-m-d H:i:s', filemtime($file)),
                    'path' => $file
                ];
            }
            rsort($backups);
        }
        
        $this->jsonResponse(['success' => true, 'data' => $backups]);
    }

    // ========== الإعدادات ==========
    private function getSettings() {
        $sql = "SELECT * FROM system_settings";
        $result = $this->conn->query($sql);
        $settings = [];
        while ($row = $result->fetch_assoc()) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }
        
        $this->jsonResponse(['success' => true, 'data' => $settings]);
    }

    private function updateSettings() {
        $data = json_decode(file_get_contents('php://input'), true);
        
        foreach ($data as $key => $value) {
            $key = $this->conn->real_escape_string($key);
            $value = $this->conn->real_escape_string($value);
            $this->conn->query("INSERT INTO system_settings (setting_key, setting_value) 
                                VALUES ('$key', '$value') 
                                ON DUPLICATE KEY UPDATE setting_value = '$value'");
        }
        
        $this->jsonResponse(['success' => true, 'message' => 'تم حفظ الإعدادات']);
    }

    // ========== دوال مساعدة ==========
    private function getSingleValue($sql) {
        $result = $this->conn->query($sql);
        if ($result && $row = $result->fetch_row()) {
            return $row[0];
        }
        return 0;
    }

    private function getRatingText($score) {
        if ($score >= 90) return "ممتاز - حالة نادرة";
        if ($score >= 75) return "جيد جداً - يوصى بالشراء";
        if ($score >= 60) return "جيد - يحتاج صيانة بسيطة";
        if ($score >= 45) return "متوسط - يحتاج مصاريف إضافية";
        if ($score >= 25) return "ضعيف - يحتاج إصلاحات كثيرة";
        return "حرج - لا ينصح بالشراء إطلاقاً";
    }

    private function jsonResponse($data, $statusCode = 200) {
        http_response_code($statusCode);
        echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        exit;
    }
}

// تشغيل النظام
$api = new AdminAPI();
$api->handle();
?>