<?php
// ============================================
// API Gateway الموحد - نظام AUTO TESTER
// ============================================

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

// بدء الجلسة
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// ============================================
// إعدادات قاعدة البيانات
// ============================================
class Database {
    private $host = "localhost";
    private $db_name = "digitals_autotester_db";
    private $username = "digitals";
    private $password = "bassam.bassam";
    private $conn;
    private static $instance = null;
    
    private function __construct() {}
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance;
    }
    
    public function getConnection() {
        if ($this->conn === null) {
            try {
                $this->conn = new PDO(
                    "mysql:host=" . $this->host . ";dbname=" . $this->db_name . ";charset=utf8mb4",
                    $this->username,
                    $this->password,
                    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
                );
            } catch(PDOException $e) {
                sendResponse(false, 'Database connection failed: ' . $e->getMessage(), null, 500);
            }
        }
        return $this->conn;
    }
}

// ============================================
// دوال مساعدة
// ============================================
function sendResponse($success, $message, $data = null, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode(['success' => $success, 'message' => $message, 'data' => $data, 'timestamp' => date('Y-m-d H:i:s')], JSON_UNESCAPED_UNICODE);
    exit();
}

function getRequestData() {
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method === 'GET') return $_GET;
    $input = json_decode(file_get_contents('php://input'), true);
    return $input !== null ? $input : $_POST;
}

function validateRequiredFields($data, $required) {
    $missing = [];
    foreach ($required as $field) {
        if (empty($data[$field])) $missing[] = $field;
    }
    if (!empty($missing)) sendResponse(false, 'الحقول التالية مطلوبة: ' . implode(', ', $missing), null, 400);
}

function sanitizeInput($input) {
    if ($input === null) return '';
    return htmlspecialchars(strip_tags(trim($input)), ENT_QUOTES, 'UTF-8');
}

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

// ============================================
// التحقق من المصادقة (Authentication)
// ============================================
function authenticateInspector($pdo) {
    // التحقق من الجلسة أولاً
    if (!isset($_SESSION['user_id']) || !isset($_SESSION['role'])) {
        return false;
    }
    
    // التحقق من أن المستخدم فاحص
    if ($_SESSION['role'] !== 'inspector' && $_SESSION['user_type'] !== 'inspector') {
        return false;
    }
    
    // جلب بيانات الفاحص من قاعدة البيانات (استخدام جدول users فقط)
    $stmt = $pdo->prepare("
        SELECT u.id as user_id, u.full_name, u.email, u.phone, u.role, u.user_type, u.status, u.area, u.rating, u.experience_years,
               u.current_latitude, u.current_longitude, u.last_location_update
        FROM users u
        WHERE u.id = ? AND (u.role = 'inspector' OR u.user_type = 'inspector') AND u.status = 'active'
    ");
    $stmt->execute([(int)$_SESSION['user_id']]);
    $inspector = $stmt->fetch();
    
    if (!$inspector) return false;
    
    return $inspector;
}

// ============================================
// معالج الطلبات الرئيسي
// ============================================
$action = $_GET['action'] ?? $_POST['action'] ?? null;
$method = $_SERVER['REQUEST_METHOD'];

try {
    $db = Database::getInstance();
    $pdo = $db->getConnection();
    $data = getRequestData();
    
    switch ($action) {
        
        // ========================================
        // 1. تسجيل الدخول (ينشئ Session ويحفظ في localStorage)
        // ========================================
        case 'login':
            if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
            validateRequiredFields($data, ['email', 'password']);
            
            $email = sanitizeInput($data['email']);
            $password = $data['password'];
            
            $stmt = $pdo->prepare("
                SELECT u.id, u.full_name, u.email, u.phone, u.password_hash, u.role, u.user_type, u.status, u.area, u.rating, u.experience_years
                FROM users u
                WHERE (u.email = ? OR u.phone = ?) AND (u.role = 'inspector' OR u.user_type = 'inspector')
            ");
            $stmt->execute([$email, $email]);
            $user = $stmt->fetch();
            
            if (!$user) sendResponse(false, 'بيانات الدخول غير صحيحة', null, 401);
            if (!password_verify($password, $user['password_hash'])) sendResponse(false, 'كلمة المرور غير صحيحة', null, 401);
            if ($user['status'] !== 'active') sendResponse(false, 'الحساب غير نشط', null, 403);
            
            // إنشاء جلسة آمنة
            $_SESSION['user_id'] = (int)$user['id'];
            $_SESSION['user_name'] = $user['full_name'];
            $_SESSION['role'] = $user['role'];
            $_SESSION['user_type'] = $user['user_type'];
            $_SESSION['logged_in'] = true;
            
            // إزالة كلمة المرور من البيانات
            unset($user['password_hash']);
            
            sendResponse(true, 'تم تسجيل الدخول بنجاح', [
                'user' => $user,
                'session_id' => session_id(),
                'redirect' => '/app/inspector/dashboard.html'
            ]);
            break;
        
        // ========================================
        // 2. تسجيل الخروج
        // ========================================
        case 'logout':
            session_destroy();
            sendResponse(true, 'تم تسجيل الخروج بنجاح');
            break;
        
        // ========================================
        // 3. التحقق من الجلسة
        // ========================================
        case 'check_auth':
            if (isset($_SESSION['user_id']) && isset($_SESSION['role'])) {
                // جلب أحدث بيانات المستخدم
                $stmt = $pdo->prepare("
                    SELECT id, full_name, email, phone, role, user_type, area, rating
                    FROM users WHERE id = ?
                ");
                $stmt->execute([$_SESSION['user_id']]);
                $user = $stmt->fetch();
                
                sendResponse(true, 'جلسة نشطة', [
                    'user_id' => $_SESSION['user_id'],
                    'role' => $_SESSION['role'],
                    'user' => $user
                ]);
            } else {
                sendResponse(false, 'لا توجد جلسة نشطة', null, 401);
            }
            break;
        
        // ========================================
        // 4. إحصائيات لوحة التحكم (للفاحص)
        // ========================================
        case 'get_dashboard_stats':
            $inspector = authenticateInspector($pdo);
            if (!$inspector) sendResponse(false, 'غير مصرح بالوصول', null, 401);
            
            $stmt = $pdo->prepare("
                SELECT 
                    COUNT(*) as total,
                    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
                    SUM(CASE WHEN status = 'assigned' THEN 1 ELSE 0 END) as assigned,
                    SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress,
                    SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed
                FROM inspections
                WHERE inspector_id = ?
            ");
            $stmt->execute([(int)$inspector['user_id']]);
            $stats = $stmt->fetch();
            
            sendResponse(true, 'تم جلب الإحصائيات', [
                'total_tasks' => (int)($stats['total'] ?? 0),
                'pending_tasks' => (int)($stats['pending'] ?? 0),
                'assigned_tasks' => (int)($stats['assigned'] ?? 0),
                'in_progress_tasks' => (int)($stats['in_progress'] ?? 0),
                'completed_tasks' => (int)($stats['completed'] ?? 0),
                'rating' => (float)($inspector['rating'] ?? 0),
                'inspector' => $inspector
            ]);
            break;
        
        // ========================================
        // 5. جلب مهام الفاحص
        // ========================================
        case 'get_my_tasks':
            $inspector = authenticateInspector($pdo);
            if (!$inspector) sendResponse(false, 'غير مصرح بالوصول', null, 401);
            
            $status = isset($_GET['status']) ? sanitizeInput($_GET['status']) : null;
            $sql = "
                SELECT i.*, u.full_name as client_name, u.phone as client_phone, u.area,
                       it.name as service_name, it.price as service_price
                FROM inspections i
                LEFT JOIN users u ON i.user_id = u.id
                LEFT JOIN inspection_types it ON i.inspection_type_id = it.id
                WHERE i.inspector_id = ?
            ";
            $params = [(int)$inspector['user_id']];
            
            if ($status && in_array($status, ['pending', 'assigned', 'in_progress', 'completed'])) {
                $sql .= " AND i.status = ?";
                $params[] = $status;
            }
            
            $sql .= " ORDER BY i.scheduled_date ASC, i.created_at DESC";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $tasks = $stmt->fetchAll();
            
            // تنظيف البيانات قبل الإرسال
            foreach ($tasks as &$task) {
                $task['client_name'] = sanitizeInput($task['client_name'] ?? '');
                $task['car_make'] = sanitizeInput($task['car_make'] ?? '');
                $task['car_model'] = sanitizeInput($task['car_model'] ?? '');
                $task['address'] = sanitizeInput($task['address'] ?? '');
            }
            
            sendResponse(true, 'تم جلب المهام', $tasks);
            break;
        
        // ========================================
        // 6. بدء الفحص (مع تسجيل الموقع الجغرافي)
        // ========================================
        case 'start_inspection':
            if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
            validateRequiredFields($data, ['task_id']);
            $inspector = authenticateInspector($pdo);
            if (!$inspector) sendResponse(false, 'غير مصرح بالوصول', null, 401);
            
            $taskId = (int)$data['task_id'];
            $latitude = isset($data['latitude']) ? (float)$data['latitude'] : null;
            $longitude = isset($data['longitude']) ? (float)$data['longitude'] : null;
            
            // تحديث موقع الفاحص إذا تم إرساله
            if ($latitude && $longitude) {
                $stmt = $pdo->prepare("
                    UPDATE users 
                    SET current_latitude = ?, current_longitude = ?, last_location_update = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$latitude, $longitude, $inspector['user_id']]);
            }
            
            $stmt = $pdo->prepare("
                UPDATE inspections 
                SET status = 'in_progress', updated_at = NOW()
                WHERE id = ? AND inspector_id = ? AND status = 'assigned'
            ");
            $stmt->execute([$taskId, $inspector['user_id']]);
            
            if ($stmt->rowCount() === 0) {
                sendResponse(false, 'لا يمكن بدء الفحص. تأكد من أن المهمة مسندة إليك وحالتها "معينة"');
            }
            
            sendResponse(true, 'تم بدء الفحص بنجاح');
            break;
        
        // ========================================
        // 7. إكمال الفحص
        // ========================================
        case 'complete_inspection':
            if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
            validateRequiredFields($data, ['task_id']);
            $inspector = authenticateInspector($pdo);
            if (!$inspector) sendResponse(false, 'غير مصرح بالوصول', null, 401);
            
            $taskId = (int)$data['task_id'];
            $carScore = isset($data['car_score']) ? (int)$data['car_score'] : 80;
            $notes = isset($data['notes']) ? sanitizeInput($data['notes']) : '';
            $ratingText = getRatingText($carScore);  // ✅ تم إزالة $this-> (تم الإصلاح)
            
            $pdo->beginTransaction();
            
            try {
                // تحديث الفحص
                $stmt = $pdo->prepare("
                    UPDATE inspections 
                    SET status = 'completed', car_score = ?, rating_text = ?, notes = ?, completed_at = NOW(), updated_at = NOW()
                    WHERE id = ? AND inspector_id = ? AND status = 'in_progress'
                ");
                $stmt->execute([$carScore, $ratingText, $notes, $taskId, $inspector['user_id']]);
                
                if ($stmt->rowCount() === 0) {
                    throw new Exception('لا يمكن إكمال الفحص. تأكد من أن المهمة في حالة "قيد التنفيذ"');
                }
                
                // حفظ التفاصيل الفنية إن وجدت
                if (isset($data['technical_details']) && is_array($data['technical_details'])) {
                    $tech = $data['technical_details'];
                    $stmt = $pdo->prepare("
                        INSERT INTO inspection_details (inspection_id, engine_status, chassis_damage, gearbox_status, odometer, accident_history, inspector_notes)
                        VALUES (?, ?, ?, ?, ?, ?, ?)
                        ON DUPLICATE KEY UPDATE
                        engine_status = VALUES(engine_status), chassis_damage = VALUES(chassis_damage),
                        gearbox_status = VALUES(gearbox_status), odometer = VALUES(odometer),
                        accident_history = VALUES(accident_history), inspector_notes = VALUES(inspector_notes)
                    ");
                    $stmt->execute([
                        $taskId,
                        $tech['engine_status'] ?? null,
                        $tech['chassis_damage'] ?? null,
                        $tech['gearbox_status'] ?? null,
                        $tech['odometer'] ?? null,
                        $tech['accident_history'] ?? null,
                        $tech['inspector_notes'] ?? null
                    ]);
                }
                
                $pdo->commit();
                sendResponse(true, 'تم إكمال الفحص بنجاح');
                
            } catch (Exception $e) {
                $pdo->rollBack();
                sendResponse(false, $e->getMessage(), null, 500);
            }
            break;
        
        // ========================================
        // 8. جلب تفاصيل مهمة
        // ========================================
        case 'get_task_details':
            if ($method !== 'GET') sendResponse(false, 'Method not allowed', null, 405);
            validateRequiredFields($_GET, ['task_id']);
            $inspector = authenticateInspector($pdo);
            if (!$inspector) sendResponse(false, 'غير مصرح بالوصول', null, 401);
            
            $taskId = (int)$_GET['task_id'];
            
            $stmt = $pdo->prepare("
                SELECT i.*, u.full_name as client_name, u.phone as client_phone, u.email as client_email, u.address,
                       it.name as service_name, it.price as service_price
                FROM inspections i
                LEFT JOIN users u ON i.user_id = u.id
                LEFT JOIN inspection_types it ON i.inspection_type_id = it.id
                WHERE i.id = ? AND i.inspector_id = ?
            ");
            $stmt->execute([$taskId, $inspector['user_id']]);
            $task = $stmt->fetch();
            
            if (!$task) sendResponse(false, 'المهمة غير موجودة أو غير مصرح لك بالوصول إليها');
            
            // جلب التفاصيل الفنية
            $stmt = $pdo->prepare("SELECT * FROM inspection_details WHERE inspection_id = ?");
            $stmt->execute([$task['id']]);
            $details = $stmt->fetch();
            
            $task['technical_details'] = $details;
            $task['client_name'] = sanitizeInput($task['client_name'] ?? '');
            
            sendResponse(true, 'تم جلب تفاصيل المهمة', $task);
            break;
        
        // ========================================
        // 9. جلب الإشعارات
        // ========================================
        case 'get_notifications':
            $inspector = authenticateInspector($pdo);
            if (!$inspector) sendResponse(false, 'غير مصرح بالوصول', null, 401);
            
            $stmt = $pdo->prepare("
                SELECT * FROM notifications 
                WHERE user_id = ? OR user_id IS NULL
                ORDER BY created_at DESC LIMIT 50
            ");
            $stmt->execute([$inspector['user_id']]);
            $notifications = $stmt->fetchAll();
            
            $stmt = $pdo->prepare("SELECT COUNT(*) as unread FROM notifications WHERE (user_id = ? OR user_id IS NULL) AND is_read = 0");
            $stmt->execute([$inspector['user_id']]);
            $unread = $stmt->fetch();
            
            sendResponse(true, 'تم جلب الإشعارات', [
                'data' => $notifications,
                'unread_count' => (int)($unread['unread'] ?? 0)
            ]);
            break;
        
        // ========================================
        // 10. تحديث حالة الإشعار
        // ========================================
        case 'mark_notification_read':
            if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
            validateRequiredFields($data, ['notification_id']);
            $inspector = authenticateInspector($pdo);
            if (!$inspector) sendResponse(false, 'غير مصرح بالوصول', null, 401);
            
            $notificationId = (int)$data['notification_id'];
            $stmt = $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE id = ? AND (user_id = ? OR user_id IS NULL)");
            $stmt->execute([$notificationId, $inspector['user_id']]);
            
            sendResponse(true, 'تم تحديث حالة الإشعار');
            break;
        
        // ========================================
        // 11. إضافة طلب فحص جديد (من الفاحص)
        // ========================================
        case 'add_inspection':
            if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
            validateRequiredFields($data, ['client_name', 'client_phone', 'car_make', 'car_model']);
            $inspector = authenticateInspector($pdo);
            if (!$inspector) sendResponse(false, 'غير مصرح بالوصول', null, 401);
            
            $requestNumber = 'INV-' . date('Ymd') . '-' . rand(1000, 9999);
            $clientName = sanitizeInput($data['client_name']);
            $clientPhone = sanitizeInput($data['client_phone']);
            $clientEmail = isset($data['client_email']) ? sanitizeInput($data['client_email']) : '';
            $carMake = sanitizeInput($data['car_make']);
            $carModel = sanitizeInput($data['car_model']);
            $carYear = isset($data['car_year']) ? (int)$data['car_year'] : null;
            $plateNumber = isset($data['plate_number']) ? sanitizeInput($data['plate_number']) : null;
            $area = isset($data['area']) ? sanitizeInput($data['area']) : $inspector['area'];
            $address = isset($data['address']) ? sanitizeInput($data['address']) : null;
            $serviceId = isset($data['service_id']) ? (int)$data['service_id'] : null;
            $scheduledDate = isset($data['scheduled_date']) ? $data['scheduled_date'] : null;
            $notes = isset($data['notes']) ? sanitizeInput($data['notes']) : null;
            
            // البحث عن المستخدم أو إنشاؤه
            $stmt = $pdo->prepare("SELECT id FROM users WHERE phone = ? OR email = ?");
            $stmt->execute([$clientPhone, $clientEmail]);
            $user = $stmt->fetch();
            
            if (!$user) {
                $passwordHash = password_hash('123456', PASSWORD_DEFAULT);
                $userUuid = uniqid() . '-' . rand(1000, 9999);
                $stmt = $pdo->prepare("
                    INSERT INTO users (user_uuid, full_name, email, phone, password_hash, role, user_type, status, created_at)
                    VALUES (?, ?, ?, ?, ?, 'client', 'client', 'active', NOW())
                ");
                $stmt->execute([$userUuid, $clientName, $clientEmail, $clientPhone, $passwordHash]);
                $userId = $pdo->lastInsertId();
            } else {
                $userId = $user['id'];
            }
            
            $stmt = $pdo->prepare("
                INSERT INTO inspections (
                    request_number, user_id, inspector_id, car_make, car_model, car_year, plate_number,
                    area, address, inspection_type_id, scheduled_date, notes, status, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
            ");
            $stmt->execute([
                $requestNumber, $userId, $inspector['user_id'],
                $carMake, $carModel, $carYear, $plateNumber,
                $area, $address, $serviceId, $scheduledDate, $notes
            ]);
            
            sendResponse(true, 'تم إضافة طلب الفحص بنجاح', ['request_number' => $requestNumber]);
            break;
        
        // ========================================
        // 12. جلب تقارير الفاحص
        // ========================================
        case 'get_my_reports':
            $inspector = authenticateInspector($pdo);
            if (!$inspector) sendResponse(false, 'غير مصرح بالوصول', null, 401);
            
            $stmt = $pdo->prepare("
                SELECT i.*, u.full_name as client_name, u.phone as client_phone, it.name as service_name,
                       id.engine_status, id.chassis_damage, id.gearbox_status, id.odometer, id.accident_history, id.inspector_notes
                FROM inspections i
                LEFT JOIN users u ON i.user_id = u.id
                LEFT JOIN inspection_types it ON i.inspection_type_id = it.id
                LEFT JOIN inspection_details id ON i.id = id.inspection_id
                WHERE i.inspector_id = ? AND i.status = 'completed'
                ORDER BY i.completed_at DESC
            ");
            $stmt->execute([$inspector['user_id']]);
            $reports = $stmt->fetchAll();
            
            foreach ($reports as &$report) {
                $report['client_name'] = sanitizeInput($report['client_name'] ?? '');
            }
            
            sendResponse(true, 'تم جلب التقارير', $reports);
            break;
        
        // ========================================
        // 13. رفع صور الفحص
        // ========================================
        case 'upload_inspection_images':
            if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
            validateRequiredFields($_POST, ['task_id']);
            $inspector = authenticateInspector($pdo);
            if (!$inspector) sendResponse(false, 'غير مصرح بالوصول', null, 401);
            
            $taskId = (int)$_POST['task_id'];
            
            if (!isset($_FILES['images']) || empty($_FILES['images']['name'][0])) {
                sendResponse(false, 'لم يتم رفع أي صور');
            }
            
            $uploadDir = '../../uploads/inspections/' . $taskId . '/';
            if (!file_exists($uploadDir)) mkdir($uploadDir, 0777, true);
            
            $uploadedFiles = [];
            foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
                $fileName = time() . '_' . $key . '_' . basename($_FILES['images']['name'][$key]);
                $targetPath = $uploadDir . $fileName;
                if (move_uploaded_file($tmp_name, $targetPath)) {
                    $uploadedFiles[] = '/uploads/inspections/' . $taskId . '/' . $fileName;
                }
            }
            
            // حفظ مسارات الصور في قاعدة البيانات
            if (!empty($uploadedFiles)) {
                $imagesJson = json_encode($uploadedFiles);
                $stmt = $pdo->prepare("
                    INSERT INTO inspection_details (inspection_id, images_json) 
                    VALUES (?, ?) 
                    ON DUPLICATE KEY UPDATE images_json = ?
                ");
                $stmt->execute([$taskId, $imagesJson, $imagesJson]);
            }
            
            sendResponse(true, 'تم رفع ' . count($uploadedFiles) . ' صورة بنجاح', ['files' => $uploadedFiles]);
            break;
        
        // ========================================
        // 14. تحديث موقع الفاحص (GPS)
        // ========================================
        case 'update_location':
            if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
            validateRequiredFields($data, ['latitude', 'longitude']);
            $inspector = authenticateInspector($pdo);
            if (!$inspector) sendResponse(false, 'غير مصرح بالوصول', null, 401);
            
            $latitude = (float)$data['latitude'];
            $longitude = (float)$data['longitude'];
            $locationText = isset($data['location_text']) ? sanitizeInput($data['location_text']) : null;
            
            $stmt = $pdo->prepare("
                UPDATE users 
                SET current_latitude = ?, current_longitude = ?, current_location = ?, last_location_update = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$latitude, $longitude, $locationText, $inspector['user_id']]);
            
            sendResponse(true, 'تم تحديث الموقع');
            break;
        
        // ========================================
        // 15. تحديث حالة الفاحص
        // ========================================
        case 'update_status':
            if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
            validateRequiredFields($data, ['status']);
            $inspector = authenticateInspector($pdo);
            if (!$inspector) sendResponse(false, 'غير مصرح بالوصول', null, 401);
            
            $status = sanitizeInput($data['status']);
            $allowedStatuses = ['active', 'inactive', 'busy', 'offline'];
            
            if (!in_array($status, $allowedStatuses)) {
                sendResponse(false, 'حالة غير صالحة');
            }
            
            $stmt = $pdo->prepare("UPDATE users SET status = ?, status_timestamp = NOW() WHERE id = ?");
            $stmt->execute([$status, $inspector['user_id']]);
            
            sendResponse(true, 'تم تحديث حالة الفاحص بنجاح');
            break;
        
        // ========================================
        // 16. الحالة الافتراضية
        // ========================================
        default:
            sendResponse(true, 'API Gateway - نظام الفاحصين - AUTO TESTER', [
                'available_actions' => [
                    'login' => 'POST - تسجيل دخول الفاحص',
                    'logout' => 'GET - تسجيل الخروج',
                    'check_auth' => 'GET - التحقق من الجلسة',
                    'get_dashboard_stats' => 'GET - إحصائيات لوحة التحكم',
                    'get_my_tasks' => 'GET - جلب مهامي (status?)',
                    'start_inspection' => 'POST - بدء الفحص (task_id, latitude?, longitude?)',
                    'complete_inspection' => 'POST - إكمال الفحص (task_id, car_score?, notes?, technical_details?)',
                    'get_task_details' => 'GET - تفاصيل مهمة (task_id)',
                    'get_notifications' => 'GET - الإشعارات',
                    'mark_notification_read' => 'POST - تعيين إشعار مقروء',
                    'add_inspection' => 'POST - إضافة طلب فحص جديد',
                    'get_my_reports' => 'GET - تقاريري',
                    'upload_inspection_images' => 'POST - رفع صور الفحص (multipart/form-data)',
                    'update_location' => 'POST - تحديث موقع الفاحص (latitude, longitude)',
                    'update_status' => 'POST - تحديث حالة الفاحص (status)'
                ]
            ]);
            break;
    }
    
} catch (PDOException $e) {
    sendResponse(false, 'Database error: ' . $e->getMessage(), null, 500);
} catch (Exception $e) {
    sendResponse(false, 'Server error: ' . $e->getMessage(), null, 500);
}
?>