<?php
/**
 * AUTO TESTER - Unified API System
 * Complete backend API for all operations
 * Version: 2.0
 * Author: AUTO TESTER Team
 */

// Load secure configuration
require_once __DIR__ . '/config.php';

// WhatsApp API Configuration
define('WHATSAPP_API_URL', 'https://graph.facebook.com/v18.0/YOUR_PHONE_NUMBER_ID/messages');
define('WHATSAPP_ACCESS_TOKEN', 'YOUR_ACCESS_TOKEN');
define('WHATSAPP_BUSINESS_PHONE', '201234567890'); // رقم واتساب بزنس

// Check maintenance mode
if (isMaintenanceMode()) {
    http_response_code(503);
    echo json_encode([
        'success' => false,
        'message' => 'System is under maintenance'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

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');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Rate limiting configuration
define('RATE_LIMIT_REQUESTS', 60); // requests per minute
define('RATE_LIMIT_WINDOW', 60); // seconds

// Rate limiting function
function checkRateLimit() {
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $key = "rate_limit_{$ip}";
    
    if (function_exists('apcu_fetch')) {
        $current = apcu_fetch($key) ?: 0;
        if ($current >= RATE_LIMIT_REQUESTS) {
            http_response_code(429);
            echo json_encode([
                'success' => false,
                'message' => 'Rate limit exceeded. Try again later.',
                'retry_after' => RATE_LIMIT_WINDOW
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
        apcu_store($key, $current + 1, RATE_LIMIT_WINDOW);
    } else {
        // Fallback to file-based rate limiting
        $cacheDir = getCacheDir();
        $rateFile = $cacheDir . "rate_limit_{$ip}.json";
        $currentTime = time();
        
        if (file_exists($rateFile)) {
            $data = json_decode(file_get_contents($rateFile), true) ?: [];
            // Clean old entries
            $data = array_filter($data, function($timestamp) use ($currentTime) {
                return $currentTime - $timestamp < RATE_LIMIT_WINDOW;
            });
            
            if (count($data) >= RATE_LIMIT_REQUESTS) {
                http_response_code(429);
                echo json_encode([
                    'success' => false,
                    'message' => 'Rate limit exceeded. Try again later.',
                    'retry_after' => RATE_LIMIT_WINDOW
                ], JSON_UNESCAPED_UNICODE);
                exit;
            }
        } else {
            $data = [];
        }
        
        $data[] = $currentTime;
        file_put_contents($rateFile, json_encode($data));
    }
}

// Apply rate limiting
checkRateLimit();

// Input validation function
function validateRequest($data, $required = [], $optional = []) {
    $errors = [];
    $sanitized = [];
    
    // Check required fields
    foreach ($required as $field) {
        if (empty($data[$field])) {
            $errors[] = "Field '{$field}' is required";
        } else {
            $sanitized[$field] = sanitizeInput($data[$field]);
        }
    }
    
    // Check optional fields
    foreach ($optional as $field) {
        if (isset($data[$field]) && !empty($data[$field])) {
            $sanitized[$field] = sanitizeInput($data[$field]);
        }
    }
    
    if (!empty($errors)) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Validation failed',
            'errors' => $errors
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    return $sanitized;
}

// Input sanitization function
function sanitizeInput($input) {
    if (is_array($input)) {
        return array_map('sanitizeInput', $input);
    }
    
    // Remove HTML tags and special characters
    $input = trim($input);
    $input = strip_tags($input);
    $input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
    
    return $input;
}

// Email validation function
function validateEmail($email) {
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return false;
    }
    return $email;
}

// Phone validation function (Egyptian format)
function validatePhone($phone) {
    // Remove all non-numeric characters
    $phone = preg_replace('/[^0-9]/', '', $phone);
    
    // Check if it's a valid Egyptian phone number
    if (strlen($phone) === 10 && in_array(substr($phone, 0, 2), ['10', '11', '12', '15'])) {
        return $phone;
    }
    
    return false;
}

// Password validation function
function validatePassword($password) {
    $errors = [];
    
    if (strlen($password) < 8) {
        $errors[] = "Password must be at least 8 characters";
    }
    
    if (!preg_match('/[A-Z]/', $password)) {
        $errors[] = "Password must contain at least one uppercase letter";
    }
    
    if (!preg_match('/[a-z]/', $password)) {
        $errors[] = "Password must contain at least one lowercase letter";
    }
    
    if (!preg_match('/[0-9]/', $password)) {
        $errors[] = "Password must contain at least one number";
    }
    
    return $errors;
}

// URL validation function
function validateUrl($url) {
    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        return false;
    }
    return filter_var($url, FILTER_SANITIZE_URL);
}

// Numeric validation function
function validateNumeric($value, $min = null, $max = null) {
    if (!is_numeric($value)) {
        return false;
    }
    
    $value = (float) $value;
    
    if ($min !== null && $value < $min) {
        return false;
    }
    
    if ($max !== null && $value > $max) {
        return false;
    }
    
    return $value;
}

// JWT Token generation function
function generateJWTToken($userId, $userRole) {
    $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
    $payload = json_encode([
        'user_id' => $userId,
        'user_role' => $userRole,
        'iat' => time(),
        'exp' => time() + (7 * 24 * 60 * 60), // 7 days
        'jti' => bin2hex(random_bytes(16))
    ]);
    
    $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
    $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
    
    $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, JWT_SECRET, true);
    $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
    
    return $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
}

// JWT Token validation function
function validateJWTToken($token) {
    if (empty($token)) {
        return false;
    }
    
    $parts = explode('.', $token);
    if (count($parts) !== 3) {
        return false;
    }
    
    list($header, $payload, $signature) = $parts;
    
    // Verify signature
    $expectedSignature = hash_hmac('sha256', $header . "." . $payload, JWT_SECRET, true);
    $expectedSignatureBase64 = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($expectedSignature));
    
    if (!hash_equals($expectedSignatureBase64, $signature)) {
        return false;
    }
    
    // Decode payload
    $payloadData = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $payload)), true);
    if (!$payloadData) {
        return false;
    }
    
    // Check expiration
    if (isset($payloadData['exp']) && $payloadData['exp'] < time()) {
        return false;
    }
    
    return $payloadData;
}

// Refresh Token generation function
function generateRefreshToken($userId) {
    $token = bin2hex(random_bytes(32));
    $expiresAt = date('Y-m-d H:i:s', strtotime('+30 days'));
    
    global $db;
    $stmt = $db->prepare("UPDATE users SET refresh_token = ?, refresh_token_expires = ? WHERE id = ?");
    $stmt->execute([$token, $expiresAt, $userId]);
    
    return $token;
}

// Refresh Token validation function
function validateRefreshToken($token) {
    if (empty($token)) {
        return false;
    }
    
    global $db;
    $stmt = $db->prepare("SELECT id, email, role FROM users WHERE refresh_token = ? AND refresh_token_expires > NOW()");
    $stmt->execute([$token]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        return false;
    }
    
    return $user;
}

ini_set('error_log', __DIR__ . '/logs/error.log');

// Ensure logs directory exists
if (!file_exists(__DIR__ . '/logs')) {
    mkdir(__DIR__ . '/logs', 0755, true);
}

/**
 * Database Connection Class
 */
class Database {
    private $host;
    private $dbname;
    private $username;
    private $password;
    private $charset = 'utf8mb4';
    private $pdo;
    private static $instance = null;
    
    public function __construct() {
        $config = getDatabaseConfig();
        $this->host = $config['host'];
        $this->dbname = $config['dbname'];
        $this->username = $config['username'];
        $this->password = $config['password'];
        $this->connect();
    }
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function connect() {
        try {
            $dsn = "mysql:host={$this->host};dbname={$this->dbname};charset={$this->charset}";
            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
            ];
            
            $this->pdo = new PDO($dsn, $this->username, $this->password, $options);
        } catch (PDOException $e) {
            $this->logError("Database connection failed: " . $e->getMessage());
            $this->sendResponse(false, 'Database connection failed', 500);
        }
    }
    
    public function getConnection() {
        return $this->pdo;
    }
    
    public function logError($message) {
        $timestamp = date('Y-m-d H:i:s');
        $logMessage = "[{$timestamp}] {$message}\n";
        file_put_contents(__DIR__ . '/logs/error.log', $logMessage, FILE_APPEND);
    }
}

/**
 * Authentication and Security Class
 */
class Auth {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
    }
    
    public function login($email, $password) {
        try {
            $stmt = $this->db->prepare("SELECT * FROM users WHERE email = ? AND status = 'active'");
            $stmt->execute([$email]);
            $user = $stmt->fetch();
            
            if ($user && password_verify($password, $user['password'])) {
                // Generate token
                $token = $this->generateToken();
                $expires_at = date('Y-m-d H:i:s', strtotime('+7 days'));
                
                // Update user token
                $update = $this->db->prepare("UPDATE users SET token = ?, token_expires_at = ? WHERE id = ?");
                $update->execute([$token, $expires_at, $user['id']]);
                
                // Remove password from response
                unset($user['password']);
                
                return [
                    'success' => true,
                    'data' => [
                        'user' => $user,
                        'token' => $token,
                        'expires_at' => $expires_at
                    ]
                ];
            }
            
            return ['success' => false, 'message' => 'Invalid credentials'];
        } catch (Exception $e) {
            Database::getInstance()->logError("Login error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Login failed'];
        }
    }
    
    public function register($userData) {
        try {
            // Check if email exists
            $check = $this->db->prepare("SELECT id FROM users WHERE email = ?");
            $check->execute([$userData['email']]);
            if ($check->fetch()) {
                return ['success' => false, 'message' => 'Email already exists'];
            }
            
            // Hash password
            $hashedPassword = password_hash($userData['password'], PASSWORD_DEFAULT);
            
            // Insert user
            $stmt = $this->db->prepare("
                INSERT INTO users (name, email, phone, password, role, status, created_at) 
                VALUES (?, ?, ?, ?, ?, 'active', NOW())
            ");
            $stmt->execute([
                $userData['name'],
                $userData['email'],
                $userData['phone'] ?? '',
                $hashedPassword,
                $userData['role'] ?? 'client'
            ]);
            
            $userId = $this->db->lastInsertId();
            
            // Generate token
            $token = $this->generateToken();
            $expires_at = date('Y-m-d H:i:s', strtotime('+7 days'));
            
            // Update token
            $update = $this->db->prepare("UPDATE users SET token = ?, token_expires_at = ? WHERE id = ?");
            $update->execute([$token, $expires_at, $userId]);
            
            return [
                'success' => true,
                'message' => 'Registration successful',
                'data' => [
                    'user_id' => $userId,
                    'token' => $token,
                    'expires_at' => $expires_at
                ]
            ];
        } catch (Exception $e) {
            Database::getInstance()->logError("Registration error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Registration failed'];
        }
    }
    
    public function verifyToken($token) {
        try {
            $stmt = $this->db->prepare("
                SELECT * FROM users 
                WHERE token = ? AND token_expires_at > NOW() AND status = 'active'
            ");
            $stmt->execute([$token]);
            $user = $stmt->fetch();
            
            if ($user) {
                unset($user['password']);
                return ['success' => true, 'data' => $user];
            }
            
            return ['success' => false, 'message' => 'Invalid or expired token'];
        } catch (Exception $e) {
            Database::getInstance()->logError("Token verification error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Token verification failed'];
        }
    }
    
    public function logout($token) {
        try {
            $stmt = $this->db->prepare("UPDATE users SET token = NULL, token_expires_at = NULL WHERE token = ?");
            $stmt->execute([$token]);
            
            return ['success' => true, 'message' => 'Logged out successfully'];
        } catch (Exception $e) {
            Database::getInstance()->logError("Logout error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Logout failed'];
        }
    }
    
    private function generateToken() {
        return bin2hex(random_bytes(32));
    }
}

/**
 * API Handler Class
 */
class APIHandler {
    private $db;
    private $auth;
    private $currentUser = null;
    
    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
        $this->auth = new Auth();
    }
    
    public function handleRequest() {
        $method = $_SERVER['REQUEST_METHOD'];
        $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $pathParts = explode('/', trim($path, '/'));
        
        // Remove base directory if present
        if ($pathParts[0] === 'autotestersystem111') {
            array_shift($pathParts);
        }
        
        $endpoint = $pathParts[0] ?? '';
        $action = $pathParts[1] ?? '';
        
        // Verify token for protected endpoints
        if ($endpoint !== 'auth' && $endpoint !== 'public') {
            $token = $this->getTokenFromRequest();
            if (!$token) {
                $this->sendResponse(false, 'Token required', 401);
            }
            
            $verification = $this->auth->verifyToken($token);
            if (!$verification['success']) {
                $this->sendResponse(false, 'Invalid token', 401);
            }
            
            $this->currentUser = $verification['data'];
        }
        
        // Route to appropriate handler
        switch ($endpoint) {
            case 'auth':
                $this->handleAuth($method, $action);
                break;
            case 'client':
                $this->handleClient($method, $action);
                break;
            case 'inspector':
                $this->handleInspector($method, $action);
                break;
            case 'supervisor':
                $this->handleSupervisor($method, $action);
                break;
            case 'admin':
                $this->handleAdmin($method, $action);
                break;
            case 'common':
                $this->handleCommon($method, $action);
                break;
            case 'ai':
                $this->handleAI($method, $action);
                break;
            case 'public':
                $this->handlePublic($method, $action);
                break;
            default:
                $this->sendResponse(false, 'Endpoint not found', 404);
        }
    }
    
    private function handleAuth($method, $action) {
        switch ($action) {
            case 'login':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    $result = $this->auth->login($data['email'], $data['password']);
                    $this->sendResponse($result['success'], $result['message'] ?? '', 200, $result['data'] ?? null);
                }
                break;
                
            case 'register':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    $result = $this->auth->register($data);
                    $this->sendResponse($result['success'], $result['message'] ?? '', 200, $result['data'] ?? null);
                }
                break;
                
            case 'verify':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    $result = $this->auth->verifyToken($data['token']);
                    $this->sendResponse($result['success'], $result['message'] ?? '', 200, $result['data'] ?? null);
                }
                break;
                
            case 'logout':
                if ($method === 'POST') {
                    $token = $this->getTokenFromRequest();
                    $result = $this->auth->logout($token);
                    $this->sendResponse($result['success'], $result['message'] ?? '');
                }
                break;
                
            default:
                $this->sendResponse(false, 'Auth action not found', 404);
        }
    }
    
    private function handleClient($method, $action) {
        $this->checkRole(['client', 'admin', 'supervisor']);
        
        switch ($action) {
            case 'requests':
                if ($method === 'GET') {
                    $stmt = $this->db->prepare("
                        SELECT r.*, u.name as customer_name 
                        FROM inspection_requests r 
                        LEFT JOIN users u ON r.customer_id = u.id 
                        WHERE r.customer_id = ? 
                        ORDER BY r.created_at DESC
                    ");
                    $stmt->execute([$this->currentUser['id']]);
                    $requests = $stmt->fetchAll();
                    $this->sendResponse(true, '', 200, $requests);
                } elseif ($method === 'POST') {
                    $data = $this->getRequestData();
                    $stmt = $this->db->prepare("
                        INSERT INTO inspection_requests (
                            customer_id, customer_name, customer_phone, customer_email,
                            vehicle_make, vehicle_model, vehicle_year, plate_number, vin_number, mileage,
                            inspection_type, appointment_date, appointment_time, notes,
                            payment_method, payment_receipt, status, created_at
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
                    ");
                    $stmt->execute([
                        $this->currentUser['id'],
                        $data['customer_name'],
                        $data['customer_phone'],
                        $data['customer_email'],
                        $data['vehicle_make'],
                        $data['vehicle_model'],
                        $data['vehicle_year'],
                        $data['plate_number'],
                        $data['vin_number'] ?? '',
                        $data['mileage'] ?? 0,
                        $data['inspection_type'],
                        $data['appointment_date'],
                        $data['appointment_time'],
                        $data['notes'] ?? '',
                        $data['payment_method'],
                        $data['payment_receipt'] ?? ''
                    ]);
                    
                    $requestId = $this->db->lastInsertId();
                    $this->sendResponse(true, 'Request created successfully', 200, ['request_id' => $requestId]);
                }
                break;
                
            default:
                $this->sendResponse(false, 'Client action not found', 404);
        }
    }
    
    private function handleInspector($method, $action) {
        $this->checkRole(['inspector', 'admin', 'supervisor']);
        
        switch ($action) {
            case 'inspections':
                if ($method === 'GET') {
                    $stmt = $this->db->prepare("
                        SELECT r.*, u.name as customer_name, i.name as inspector_name
                        FROM inspection_requests r
                        LEFT JOIN users u ON r.customer_id = u.id
                        LEFT JOIN users i ON r.inspector_id = i.id
                        WHERE r.inspector_id = ? OR r.status = 'pending'
                        ORDER BY r.created_at DESC
                    ");
                    $stmt->execute([$this->currentUser['id']]);
                    $inspections = $stmt->fetchAll();
                    $this->sendResponse(true, '', 200, $inspections);
                }
                break;
                
            case 'assign':
                if ($method === 'POST') {
                    $this->checkRole(['admin', 'supervisor']);
                    $data = $this->getRequestData();
                    $stmt = $this->db->prepare("
                        UPDATE inspection_requests 
                        SET inspector_id = ?, status = 'assigned', assigned_at = NOW() 
                        WHERE id = ?
                    ");
                    $stmt->execute([$data['inspector_id'], $data['request_id']]);
                    $this->sendResponse(true, 'Inspector assigned successfully');
                }
                break;
                
            case 'update-status':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    $stmt = $this->db->prepare("
                        UPDATE inspection_requests 
                        SET status = ?, updated_at = NOW() 
                        WHERE id = ? AND inspector_id = ?
                    ");
                    $stmt->execute([$data['status'], $data['request_id'], $this->currentUser['id']]);
                    $this->sendResponse(true, 'Status updated successfully');
                }
                break;
                
            default:
                $this->sendResponse(false, 'Inspector action not found', 404);
        }
    }
    
    private function handleSupervisor($method, $action) {
        $this->checkRole(['supervisor', 'admin']);
        
        switch ($action) {
            case 'dashboard':
                if ($method === 'GET') {
                    $stats = $this->getDashboardStats();
                    $this->sendResponse(true, '', 200, $stats);
                }
                break;
                
            case 'inspectors':
                if ($method === 'GET') {
                    $stmt = $this->db->prepare("
                        SELECT id, name, email, phone, status, created_at 
                        FROM users 
                        WHERE role = 'inspector' 
                        ORDER BY name
                    ");
                    $stmt->execute();
                    $inspectors = $stmt->fetchAll();
                    $this->sendResponse(true, '', 200, $inspectors);
                }
                break;
                
            default:
                $this->sendResponse(false, 'Supervisor action not found', 404);
        }
    }
    
    private function handleAdmin($method, $action) {
        $this->checkRole(['admin']);
        
        switch ($action) {
            case 'dashboard':
                if ($method === 'GET') {
                    $stats = $this->getDashboardStats();
                    $this->sendResponse(true, '', 200, $stats);
                }
                break;
                
            case 'users':
                if ($method === 'GET') {
                    $stmt = $this->db->prepare("
                        SELECT id, name, email, phone, role, status, created_at 
                        FROM users 
                        ORDER BY created_at DESC
                    ");
                    $stmt->execute();
                    $users = $stmt->fetchAll();
                    $this->sendResponse(true, '', 200, $users);
                } elseif ($method === 'POST') {
                    $data = $this->getRequestData();
                    $result = $this->auth->register($data);
                    $this->sendResponse($result['success'], $result['message'] ?? '', 200, $result['data'] ?? null);
                }
                break;
                
            case 'users/update':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    $stmt = $this->db->prepare("
                        UPDATE users 
                        SET name = ?, email = ?, phone = ?, role = ?, status = ? 
                        WHERE id = ?
                    ");
                    $stmt->execute([
                        $data['name'],
                        $data['email'],
                        $data['phone'],
                        $data['role'],
                        $data['status'],
                        $data['user_id']
                    ]);
                    $this->sendResponse(true, 'User updated successfully');
                }
                break;
                
            case 'users/delete':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    $stmt = $this->db->prepare("UPDATE users SET status = 'deleted' WHERE id = ?");
                    $stmt->execute([$data['user_id']]);
                    $this->sendResponse(true, 'User deleted successfully');
                }
                break;
                
            default:
                $this->sendResponse(false, 'Admin action not found', 404);
        }
    }
    
    private function handleCommon($method, $action) {
        switch ($action) {
            case 'notifications':
                if ($method === 'GET') {
                    $stmt = $this->db->prepare("
                        SELECT * FROM notifications 
                        WHERE user_id = ? AND read_at IS NULL 
                        ORDER BY created_at DESC 
                        LIMIT 10
                    ");
                    $stmt->execute([$this->currentUser['id']]);
                    $notifications = $stmt->fetchAll();
                    $this->sendResponse(true, '', 200, $notifications);
                }
                break;
                
            case 'mark-notification':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    $stmt = $this->db->prepare("
                        UPDATE notifications 
                        SET read_at = NOW() 
                        WHERE id = ? AND user_id = ?
                    ");
                    $stmt->execute([$data['notification_id'], $this->currentUser['id']]);
                    $this->sendResponse(true, 'Notification marked as read');
                }
                break;
                
            case 'upload':
                if ($method === 'POST') {
                    $this->handleFileUpload();
                }
                break;
                
            case 'inspection-checklist':
                if ($method === 'GET') {
                    $typeId = $_GET['type_id'] ?? null;
                    $this->getInspectionChecklist($typeId);
                }
                break;
                
            // AI Services Endpoints
            case 'ai-vehicle-prediction':
                if ($method === 'POST') {
                    $this->aiVehiclePrediction();
                }
                break;
                
            case 'ai-maintenance-scheduler':
                if ($method === 'POST') {
                    $this->aiMaintenanceScheduler();
                }
                break;
                
            case 'ai-inspection-assistant':
                if ($method === 'POST') {
                    $this->aiInspectionAssistant();
                }
                break;
                
            case 'ai-dashboard-stats':
                if ($method === 'GET') {
                    $this->aiDashboardStats();
                }
                break;
                
            case 'save-inspection-results':
                if ($method === 'POST') {
                    $this->saveInspectionResults();
                }
                break;
                
            case 'inspection-results':
                if ($method === 'GET') {
                    $inspectionId = $_GET['inspection_id'] ?? null;
                    $this->getInspectionResults($inspectionId);
                }
                break;
                
            case 'inspector-permissions':
                if ($method === 'GET') {
                    $inspectorId = $_GET['inspector_id'] ?? $this->currentUser['id'];
                    $this->getInspectorPermissions($inspectorId);
                } elseif ($method === 'POST') {
                    $this->grantInspectorPermission();
                }
                break;
                
            // Vehicle Rating & Pricing Endpoints
            case 'calculate-rating':
                if ($method === 'POST') {
                    $this->calculateVehicleRating();
                }
                break;
                
            case 'calculate-price':
                if ($method === 'POST') {
                    $this->calculateVehiclePrice();
                }
                break;
                
            case 'save-recommendations':
                if ($method === 'POST') {
                    $this->saveVehicleRecommendations();
                }
                break;
                
            case 'get-vehicle-prices':
                if ($method === 'GET') {
                    $this->getVehiclePrices();
                }
                break;
                
            case 'generate-inspection-report':
                if ($method === 'POST') {
                    $this->generateInspectionReport();
                }
                break;
                
            case 'whatsapp/send':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    $result = $this->sendWhatsAppMessage($data['to'], $data['message'], $data['type'] ?? 'text');
                    $this->sendResponse($result['success'], $result['message'] ?? '', 200, $result);
                }
                break;
                
            case 'whatsapp/notify-client':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    $result = $this->notifyClientNewInspection($data['client_id'], $data['inspection_id']);
                    $this->sendResponse($result['success'], $result['message'] ?? '', 200, $result);
                }
                break;
                
            case 'whatsapp/notify-inspector-assigned':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    $result = $this->notifyClientInspectorAssigned($data['inspection_id']);
                    $this->sendResponse($result['success'], $result['message'] ?? '', 200, $result);
                }
                break;
                
            case 'whatsapp/notify-status':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    $result = $this->notifyClientStatusUpdate($data['inspection_id'], $data['old_status'], $data['new_status']);
                    $this->sendResponse($result['success'], $result['message'] ?? '', 200, $result);
                }
                break;
                
            case 'whatsapp/send-report':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    $result = $this->sendInspectionReport($data['inspection_id']);
                    $this->sendResponse($result['success'], $result['message'] ?? '', 200, $result);
                }
                break;
                
            default:
                $this->sendResponse(false, 'Common action not found', 404);
        }
    }
    
    private function handleAI($method, $action) {
        switch ($action) {
            case 'assistant':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    // Simulate AI response
                    $response = $this->simulateAIResponse($data['question']);
                    $this->sendResponse(true, '', 200, ['response' => $response]);
                }
                break;
                
            default:
                $this->sendResponse(false, 'AI action not found', 404);
        }
    }
    
    private function handlePublic($method, $action) {
        switch ($action) {
            case 'inspection-types':
                if ($method === 'GET') {
                    $types = [
                        ['id' => 'comprehensive', 'name' => '&#x0641;&#x062d;&#x0635; &#x0634;&#x0627;&#x0645;&#x0644;', 'price' => 1500, 'points' => 200],
                        ['id' => 'engine', 'name' => '&#x0641;&#x062d;&#x0635; &#x0627;&#x0644;&#x0645;&#x062d;&#x0631;&#x0643;', 'price' => 500, 'points' => 50],
                        ['id' => 'transmission', 'name' => '&#x0641;&#x062d;&#x0635; &#x0646;&#x0642;&#x0644; &#x0627;&#x0644;&#x062d;&#x0631;&#x0643;&#x0629;', 'price' => 400, 'points' => 40],
                        ['id' => 'brakes', 'name' => '&#x0641;&#x062d;&#x0635; &#x0627;&#x0644;&#x0641;&#x0631;&#x0627;&#x0645;&#x0644;', 'price' => 300, 'points' => 30],
                        ['id' => 'suspension', 'name' => '&#x0641;&#x062d;&#x0635; &#x0627;&#x0644;&#x0639;&#x0644;&#x0642;&#x0629;', 'price' => 350, 'points' => 35],
                        ['id' => 'electrical', 'name' => '&#x0641;&#x062d;&#x0635; &#x0627;&#x0644;&#x0646;&#x0638;&#x0627;&#x0645; &#x0627;&#x0644;&#x0643;&#x0647;&#x0631;&#x0628;&#x0627;&#x0626;&#x064a;', 'price' => 450, 'points' => 45],
                        ['id' => 'ac', 'name' => '&#x0641;&#x062d;&#x0635; &#x062a;&#x0643;&#x064a;&#x064a;&#x0641; &#x0627;&#x0644;&#x0647;&#x0648;&#x0627;&#x0621;', 'price' => 250, 'points' => 25],
                        ['id' => 'computer', 'name' => '&#x0641;&#x062d;&#x0635; &#x0643;&#x0645;&#x0628;&#x064a;&#x0648;&#x062a;&#x0631; &#x0627;&#x0644;&#x0633;&#x064a;&#x0627;&#x0631;&#x0629;', 'price' => 200, 'points' => 20],
                        ['id' => 'dyno', 'name' => '&#x0641;&#x062d;&#x0635; &#x062f;&#x0627;&#x064a;&#x0646;&#x0648;', 'price' => 800, 'points' => 80],
                        ['id' => 'emissions', 'name' => '&#x0641;&#x062d;&#x0635; &#x0627;&#x0646;&#x0628;&#x0639;&#x0627;&#x062b; &#x0627;&#x0644;&#x0639;&#x0627;&#x062f;&#x0645;', 'price' => 150, 'points' => 15]
                    ];
                    $this->sendResponse(true, '', 200, $types);
                }
                break;
                
            case 'check-phone':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    if (empty($data['phone'])) {
                        $this->sendResponse(false, 'Phone number is required', 400);
                        break;
                    }
                    
                    $stmt = $this->db->prepare("SELECT id FROM users WHERE phone = ?");
                    $stmt->execute([$data['phone']]);
                    $exists = $stmt->fetch() ? true : false;
                    $this->sendResponse(true, '', 200, ['exists' => $exists]);
                }
                break;
                
            case 'check-email':
                if ($method === 'POST') {
                    $data = $this->getRequestData();
                    if (empty($data['email'])) {
                        $this->sendResponse(false, 'Email is required', 400);
                        break;
                    }
                    
                    $stmt = $this->db->prepare("SELECT id FROM users WHERE email = ?");
                    $stmt->execute([$data['email']]);
                    $exists = $stmt->fetch() ? true : false;
                    $this->sendResponse(true, '', 200, ['exists' => $exists]);
                }
                break;
                
            case 'admin/activity':
                if ($method === 'GET') {
                    $this->validateSession();
                    
                    $stmt = $this->db->prepare("
                        SELECT a.*, u.full_name as user_name 
                        FROM activity_log a 
                        LEFT JOIN users u ON a.user_id = u.id 
                        ORDER BY a.created_at DESC 
                        LIMIT 100
                    ");
                    $stmt->execute();
                    $activities = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    $this->sendResponse(true, '', 200, $activities);
                }
                break;
                
            case 'admin/roles':
                if ($method === 'GET') {
                    $this->validateSession();
                    
                    $stmt = $this->db->prepare("
                        SELECT r.*, COUNT(u.id) as users_count 
                        FROM roles r 
                        LEFT JOIN users u ON r.id = u.role_id 
                        GROUP BY r.id 
                        ORDER BY r.level DESC
                    ");
                    $stmt->execute();
                    $roles = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    $this->sendResponse(true, '', 200, $roles);
                } elseif ($method === 'POST') {
                    $this->validateSession();
                    $data = $this->getRequestData();
                    
                    if (empty($data['name'])) {
                        $this->sendResponse(false, 'Role name is required', 400);
                        break;
                    }
                    
                    $stmt = $this->db->prepare("
                        INSERT INTO roles (name, description, level, created_at) 
                        VALUES (?, ?, ?, NOW())
                    ");
                    $stmt->execute([
                        $data['name'],
                        $data['description'] ?? '',
                        $data['level'] ?? 1
                    ]);
                    
                    $this->sendResponse(true, 'Role created successfully', 201);
                }
                break;
                
            case 'admin/permissions':
                if ($method === 'GET') {
                    $this->validateSession();
                    
                    $stmt = $this->db->prepare("
                        SELECT u.*, r.name as role_name, r.description as role_description 
                        FROM users u 
                        JOIN roles r ON u.role_id = r.id 
                        WHERE u.id = ?
                    ");
                    $stmt->execute([$this->getCurrentUserId()]);
                    $user = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($user) {
                        $stmt = $this->db->prepare("
                            SELECT p.* 
                            FROM permissions p 
                            JOIN role_permissions rp ON p.id = rp.permission_id 
                            WHERE rp.role_id = ?
                        ");
                        $stmt->execute([$user['role_id']]);
                        $permissions = $stmt->fetchAll(PDO::FETCH_ASSOC);
                        
                        $this->sendResponse(true, '', 200, [
                            'user' => $user,
                            'role_info' => ['name' => $user['role_name'], 'description' => $user['role_description']],
                            'permissions' => $permissions
                        ]);
                    } else {
                        $this->sendResponse(false, 'User not found', 404);
                    }
                }
                break;
                
            case 'admin/centers':
                if ($method === 'GET') {
                    $this->validateSession();
                    
                    $stmt = $this->db->prepare("
                        SELECT * FROM inspection_centers 
                        ORDER BY name ASC
                    ");
                    $stmt->execute();
                    $centers = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    $this->sendResponse(true, '', 200, $centers);
                }
                break;
                
            case 'admin/inspections':
                if ($method === 'GET') {
                    $this->validateSession();
                    
                    $status = $_GET['status'] ?? null;
                    $sql = "
                        SELECT i.*, u.full_name as client_name, ins.full_name as inspector_name 
                        FROM inspection_requests i 
                        LEFT JOIN users u ON i.client_id = u.id 
                        LEFT JOIN users ins ON i.inspector_id = ins.id 
                    ";
                    
                    if ($status) {
                        $sql .= " WHERE i.status = ?";
                        $params = [$status];
                    } else {
                        $params = [];
                    }
                    
                    $sql .= " ORDER BY i.created_at DESC LIMIT 50";
                    
                    $stmt = $this->db->prepare($sql);
                    $stmt->execute($params);
                    $inspections = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    $this->sendResponse(true, '', 200, $inspections);
                }
                break;
                
            case 'admin/activity/export':
                if ($method === 'GET') {
                    $this->validateSession();
                    
                    $filename = 'activity_log_' . date('Y-m-d_H-i-s') . '.csv';
                    $filepath = sys_get_temp_dir() . '/' . $filename;
                    
                    $stmt = $this->db->prepare("
                        SELECT a.*, u.full_name as user_name 
                        FROM activity_log a 
                        LEFT JOIN users u ON a.user_id = u.id 
                        ORDER BY a.created_at DESC
                    ");
                    $stmt->execute();
                    $activities = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    $file = fopen($filepath, 'w');
                    fputcsv($file, ['ID', 'User', 'Action', 'Details', 'IP', 'Date']);
                    
                    foreach ($activities as $activity) {
                        fputcsv($file, [
                            $activity['id'],
                            $activity['user_name'],
                            $activity['action'],
                            $activity['details'] ?? '',
                            $activity['ip_address'] ?? '',
                            $activity['created_at']
                        ]);
                    }
                    
                    fclose($file);
                    
                    $this->sendResponse(true, '', 200, [
                        'url' => '/api/temp/' . $filename,
                        'filename' => $filename
                    ]);
                }
                break;
                
            default:
                $this->sendResponse(false, 'Public action not found', 404);
        }
    }
    
    private function getDashboardStats() {
        $stats = [];
        
        // Total inspections
        $stmt = $this->db->prepare("SELECT COUNT(*) as total FROM inspection_requests");
        $stmt->execute();
        $stats['total_inspections'] = $stmt->fetch()['total'];
        
        // Completed inspections
        $stmt = $this->db->prepare("SELECT COUNT(*) as total FROM inspection_requests WHERE status = 'completed'");
        $stmt->execute();
        $stats['completed_inspections'] = $stmt->fetch()['total'];
        
        // Pending inspections
        $stmt = $this->db->prepare("SELECT COUNT(*) as total FROM inspection_requests WHERE status = 'pending'");
        $stmt->execute();
        $stats['pending_inspections'] = $stmt->fetch()['total'];
        
        // Total inspectors
        $stmt = $this->db->prepare("SELECT COUNT(*) as total FROM users WHERE role = 'inspector'");
        $stmt->execute();
        $stats['total_inspectors'] = $stmt->fetch()['total'];
        
        // Active inspectors
        $stmt = $this->db->prepare("SELECT COUNT(*) as total FROM users WHERE role = 'inspector' AND status = 'active'");
        $stmt->execute();
        $stats['active_inspectors'] = $stmt->fetch()['total'];
        
        // Total centers
        $stmt = $this->db->prepare("SELECT COUNT(*) as total FROM centers");
        $stmt->execute();
        $stats['total_centers'] = $stmt->fetch()['total'];
        
        // Active centers
        $stmt = $this->db->prepare("SELECT COUNT(*) as total FROM centers WHERE status = 'active'");
        $stmt->execute();
        $stats['active_centers'] = $stmt->fetch()['total'];
        
        // Today's revenue
        $stmt = $this->db->prepare("SELECT SUM(price) as total FROM inspection_requests WHERE DATE(created_at) = CURDATE() AND status = 'completed'");
        $stmt->execute();
        $stats['revenue'] = $stmt->fetch()['total'] ?? 0;
        
        // Inspection type counts
        $stmt = $this->db->prepare("
            SELECT 
                COUNT(CASE WHEN inspection_type = 'full' THEN 1 END) as comprehensive_count,
                COUNT(CASE WHEN inspection_type = 'dyno' THEN 1 END) as dyno_count,
                COUNT(CASE WHEN inspection_type = 'computer' THEN 1 END) as computer_count,
                COUNT(CASE WHEN inspection_type = 'structure' THEN 1 END) as structure_count,
                COUNT(CASE WHEN inspection_type NOT IN ('full', 'dyno', 'computer', 'structure') THEN 1 END) as other_count
            FROM inspection_requests
        ");
        $stmt->execute();
        $typeCounts = $stmt->fetch(PDO::FETCH_ASSOC);
        $stats['comprehensive_count'] = $typeCounts['comprehensive_count'] ?? 0;
        $stats['dyno_count'] = $typeCounts['dyno_count'] ?? 0;
        $stats['computer_count'] = $typeCounts['computer_count'] ?? 0;
        $stats['structure_count'] = $typeCounts['structure_count'] ?? 0;
        $stats['other_count'] = $typeCounts['other_count'] ?? 0;
        
        // Inspector performance stats
        $stmt = $this->db->prepare("
            SELECT 
                u.id,
                u.full_name,
                COUNT(ir.id) as inspections_count
            FROM users u
            LEFT JOIN inspection_requests ir ON u.id = ir.assigned_inspector_id
            WHERE u.role = 'inspector'
            GROUP BY u.id, u.full_name
            ORDER BY inspections_count DESC
            LIMIT 10
        ");
        $stmt->execute();
        $stats['inspector_stats'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Pending approvals (for supervisors)
        $stmt = $this->db->prepare("
            SELECT 
                ir.id,
                ir.number,
                u.full_name as client_name,
                ir.car_make,
                ir.car_model,
                ir.inspection_type
            FROM inspection_requests ir
            LEFT JOIN users u ON ir.client_id = u.id
            WHERE ir.status = 'pending' AND ir.requires_approval = 1
            ORDER BY ir.created_at DESC
            LIMIT 10
        ");
        $stmt->execute();
        $stats['pending_approvals'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        return $stats;
    }
    
    private function handleFileUpload() {
        if (!isset($_FILES['file'])) {
            $this->sendResponse(false, 'No file uploaded');
        }
        
        $file = $_FILES['file'];
        $uploadDir = __DIR__ . '/uploads/';
        
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $fileName = time() . '_' . basename($file['name']);
        $targetPath = $uploadDir . $fileName;
        
        if (move_uploaded_file($file['tmp_name'], $targetPath)) {
            $fileUrl = '/uploads/' . $fileName;
            $this->sendResponse(true, 'File uploaded successfully', 200, ['file_url' => $fileUrl]);
        } else {
            $this->sendResponse(false, 'File upload failed');
        }
    }
    
    private function simulateAIResponse($question) {
        // Simple AI simulation - in real implementation, connect to AI service
        $responses = [
            'default' => '&#x0623;&#x0646;&#x0627; &#x0645;&#x0633;&#x0627;&#x0639;&#x062f; AUTO TESTER &#x0627;&#x0644;&#x0630;&#x0643;&#x064a;. &#x0643;&#x064a;&#x0641; &#x064a;&#u0645;&#x0643;&#x0646;&#x0646;&#x064a; &#x0645;&#x0633;&#x0627;&#x0639;&#x062f;&#x062a;&#x0643; &#x0627;&#x0644;&#x064a;&#x0648;&#x0645;&#x061f;',
            'inspection' => '&#x0641;&#x062d;&#x0635; &#x0627;&#x0644;&#x0633;&#x064a;&#x0627;&#x0631;&#x0627;&#x062a; &#x0647;&#x0648; &#x0639;&#x0645;&#x0644;&#x064a;&#x0629; &#u0645;&#x0647;&#x0645;&#x0629; &#x062c;&#x062f;&#x0627;&#064b; &#x0644;&#x0636;&#x0645;&#x0627;&#x0646; &#x0633;&#x0644;&#x0627;&#x0645;&#x0629; &#x0627;&#x0644;&#x0633;&#x064a;&#x0627;&#x0631;&#x0629; &#x0648;&#x0627;&#x0644;&#x0643;&#0634;&#x0641; &#x0639;&#x0646; &#x0627;&#x0644;&#x0645;&#x0634;&#x0627;&#x0643;&#x0644; &#x0627;&#x0644;&#x0645;&#x062d;&#x062a;&#0645;&#x0644;&#x0629;.',
            'pricing' => '&#x0623;&#x0633;&#x0639;&#x0627;&#x0631;&#x0646;&#x0627; &#x062a;&#x062a;&#x0631;&#x0648;&#x0627;&#x062d; &#x062d;&#x0633;&#x0628; &#x0646;&#x0648;&#x0639; &#x0627;&#x0644;&#x0641;&#x062d;&#x0635;. &#x0627;&#x0644;&#x0641;&#x062d;&#x0635; &#x0627;&#x0644;&#x0634;&#x0627;&#x0645;&#x0644; &#x0628;&#x062f;&#x0623; &#u0645;&#x0646; 1500 &#x062c;&#x0646;&#x064a;&#x0647;.'
        ];
        
        foreach ($responses as $keyword => $response) {
            if (strpos(strtolower($question), $keyword) !== false) {
                return $response;
            }
        }
        
        return $responses['default'];
    }
    
    private function checkRole($allowedRoles) {
        if (!in_array($this->currentUser['role'], $allowedRoles)) {
            $this->sendResponse(false, 'Insufficient permissions', 403);
        }
    }
    
    // =======================================================
    // WhatsApp Integration Functions
    // =======================================================
    
    /**
     * إرسال رسالة واتساب
     */
    private function sendWhatsAppMessage($to, $message, $type = 'text') {
        // تنظيف رقم الهاتف
        $to = preg_replace('/[^0-9]/', '', $to);
        if (substr($to, 0, 2) !== '20') {
            $to = '20' . $to;
        }
        
        $data = [
            'messaging_product' => 'whatsapp',
            'to' => $to,
            'type' => $type,
            'text' => ['body' => $message]
        ];
        
        $ch = curl_init(WHATSAPP_API_URL);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . WHATSAPP_ACCESS_TOKEN,
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        return ['success' => $httpCode === 200, 'response' => json_decode($response, true)];
    }
    
    /**
     * إرسال إشعار فحص جديد للعميل
     */
    private function notifyClientNewInspection($clientId, $inspectionId) {
        $stmt = $this->db->prepare("
            SELECT u.phone, u.full_name, i.id, i.inspection_type, i.appointment_date, i.appointment_time
            FROM users u
            JOIN inspection_requests i ON i.customer_id = u.id
            WHERE u.id = ? AND i.id = ?
        ");
        $stmt->execute([$clientId, $inspectionId]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($data && $data['phone']) {
            $message = "🚗 *AUTO TESTER*\n\n";
            $message .= "مرحباً {$data['full_name']}،\n";
            $message .= "تم استلام طلب الفحص الخاص بك بنجاح! ✅\n\n";
            $message .= "📋 *رقم الطلب:* #{$data['id']}\n";
            $message .= "🔧 *نوع الفحص:* " . $this->translateInspectionType($data['inspection_type']) . "\n";
            $message .= "📅 *تاريخ الموعد:* {$data['appointment_date']}\n";
            $message .= "⏰ *وقت الموعد:* {$data['appointment_time']}\n\n";
            $message .= "سيتم إبلاغك عند تعيين الفاحص. شكراً لثقتك بنا! 🙏\n\n";
            $message .= "للاستفسار: واتساب 01018518599";
            
            return $this->sendWhatsAppMessage($data['phone'], $message);
        }
        
        return ['success' => false, 'message' => 'Client not found'];
    }
    
    /**
     * ترجمة نوع الفحص
     */
    private function translateInspectionType($type) {
        $types = [
            'full' => 'فحص شامل',
            'dyno' => 'فحص داينو',
            'computer' => 'فحص كمبيوتر',
            'structure' => 'فحص هيكل',
            'safety' => 'فحص سلامة'
        ];
        return $types[$type] ?? $type;
    }
    
    /**
     * إرسال إشعار تعيين فاحص للعميل
     */
    private function notifyClientInspectorAssigned($inspectionId) {
        $stmt = $this->db->prepare("
            SELECT u.phone, u.full_name, i.inspection_type, i.appointment_date, 
                   i.appointment_time, ins.name as inspector_name, ins.phone as inspector_phone
            FROM inspection_requests i
            JOIN users u ON i.customer_id = u.id
            JOIN users ins ON i.inspector_id = ins.id
            WHERE i.id = ?
        ");
        $stmt->execute([$inspectionId]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($data && $data['phone']) {
            $inspectorWhatsapp = preg_replace('/[^0-9]/', '', $data['inspector_phone']);
            
            $message = "🚗 *AUTO TESTER*\n\n";
            $message .= "مرحباً {$data['full_name']}،\n";
            $message .= "تم تعيين الفاحص لفحص سيارتك! 🎉\n\n";
            $message .= "🔧 *الفاحص:* {$data['inspector_name']}\n";
            $message .= "📱 *واتساب الفاحص:* wa.me/{$inspectorWhatsapp}\n";
            $message .= "📋 *رقم الطلب:* #{$inspectionId}\n";
            $message .= "🔧 *نوع الفحص:* " . $this->translateInspectionType($data['inspection_type']) . "\n";
            $message .= "📅 *التاريخ:* {$data['appointment_date']}\n";
            $message .= "⏰ *الوقت:* {$data['appointment_time']}\n\n";
            $message .= "يمكنك التواصل مع الفاحص مباشرة عبر الواتساب.\n";
            $message .= "شكراً لثقتك بنا! 🙏";
            
            return $this->sendWhatsAppMessage($data['phone'], $message);
        }
        
        return ['success' => false, 'message' => 'Inspection not found'];
    }
    
    /**
     * إرسال إشعار تحديث حالة الفحص للعميل
     */
    private function notifyClientStatusUpdate($inspectionId, $oldStatus, $newStatus) {
        $statusMessages = [
            'assigned' => 'تم تعيين فاحص لسيارتك ✅',
            'in_progress' => 'بدأ الفاحص في فحص سيارتك 🔧',
            'completed' => 'تم إكمال فحص سيارتك بنجاح ✅',
            'cancelled' => 'تم إلغاء فحص سيارتك ❌'
        ];
        
        $stmt = $this->db->prepare("
            SELECT u.phone, u.full_name, i.inspection_type
            FROM inspection_requests i
            JOIN users u ON i.customer_id = u.id
            WHERE i.id = ?
        ");
        $stmt->execute([$inspectionId]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($data && $data['phone'] && isset($statusMessages[$newStatus])) {
            $message = "🚗 *AUTO TESTER*\n\n";
            $message .= "مرحباً {$data['full_name']}،\n";
            $message .= "{$statusMessages[$newStatus]}\n\n";
            $message .= "📋 *رقم الطلب:* #{$inspectionId}\n";
            $message .= "🔧 *نوع الفحص:* " . $this->translateInspectionType($data['inspection_type']) . "\n\n";
            
            if ($newStatus === 'completed') {
                $message .= "📄 يمكنك تحميل التقرير من خلال الرابط التالي:\n";
                $message .= "http://autotestersystem.com/reports/{$inspectionId}\n\n";
            }
            
            $message .= "شكراً لثقتك بنا! 🙏";
            
            return $this->sendWhatsAppMessage($data['phone'], $message);
        }
        
        return ['success' => false];
    }
    
    /**
     * إرسال تقرير الفحص النهائي للعميل
     */
    private function sendInspectionReport($inspectionId) {
        $stmt = $this->db->prepare("
            SELECT u.phone, u.full_name, i.inspection_type, i.report_summary, i.report_url
            FROM inspection_requests i
            JOIN users u ON i.customer_id = u.id
            WHERE i.id = ? AND i.status = 'completed'
        ");
        $stmt->execute([$inspectionId]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($data && $data['phone']) {
            $message = "🚗 *AUTO TESTER*\n\n";
            $message .= "مرحباً {$data['full_name']}،\n";
            $message .= "📄 *تقرير الفحص النهائي*\n\n";
            $message .= "📋 *رقم الطلب:* #{$inspectionId}\n";
            $message .= "🔧 *نوع الفحص:* " . $this->translateInspectionType($data['inspection_type']) . "\n\n";
            $message .= "📊 *ملخص التقرير:*\n";
            $message .= "{$data['report_summary']}\n\n";
            $message .= "📎 *رابط التقرير:*\n";
            $message .= "{$data['report_url']}\n\n";
            $message .= "يمكنك تحميل التقرير PDF من الرابط أعلاه.\n";
            $message .= "شكراً لاستخدامك AUTO TESTER! 🚗";
            
            return $this->sendWhatsAppMessage($data['phone'], $message);
        }
        
        return ['success' => false];
    }
    
    /**
     * AI Services - Vehicle Condition Prediction
     */
    private function aiVehiclePrediction() {
        $data = $this->getRequestData();
        
        $required = ['make', 'model', 'year', 'mileage'];
        foreach ($required as $field) {
            if (!isset($data[$field]) || empty($data[$field])) {
                $this->sendResponse(false, "Field '$field' is required", 400);
                return;
            }
        }
        
        // Simulate AI prediction logic
        $baseScore = 85;
        $yearFactor = (2024 - $data['year']) * 2;
        $mileageFactor = min($data['mileage'] / 10000, 15);
        $makeFactor = $this->getMakeReliabilityFactor($data['make']);
        
        $overallScore = max(70, min(100, $baseScore - $yearFactor - $mileageFactor + $makeFactor));
        
        $prediction = [
            'overall_score' => round($overallScore),
            'condition' => $this->getConditionLabel($overallScore),
            'components' => [
                'engine' => round($overallScore + rand(-5, 5)),
                'transmission' => round($overallScore + rand(-5, 5)),
                'brakes' => round($overallScore + rand(-5, 5)),
                'suspension' => round($overallScore + rand(-5, 5)),
                'electrical' => round($overallScore + rand(-5, 5))
            ],
            'recommendations' => $this->getVehicleRecommendations($overallScore, $data),
            'confidence' => round(85 + rand(0, 10)) . '%'
        ];
        
        $this->sendResponse(true, 'Prediction completed successfully', 200, $prediction);
    }
    
    /**
     * AI Services - Maintenance Scheduler
     */
    private function aiMaintenanceScheduler() {
        $data = $this->getRequestData();
        
        $required = ['make', 'mileage', 'last_service'];
        foreach ($required as $field) {
            if (!isset($data[$field]) || empty($data[$field])) {
                $this->sendResponse(false, "Field '$field' is required", 400);
                return;
            }
        }
        
        $schedule = [
            'immediate' => $this->getImmediateMaintenance($data),
            'scheduled' => $this->getScheduledMaintenance($data),
            'future' => $this->getFutureMaintenance($data),
            'next_service_date' => date('Y-m-d', strtotime('+30 days')),
            'estimated_cost' => $this->estimateMaintenanceCost($data)
        ];
        
        $this->sendResponse(true, 'Maintenance schedule generated', 200, $schedule);
    }
    
    /**
     * AI Services - Inspection Assistant
     */
    private function aiInspectionAssistant() {
        $data = $this->getRequestData();
        
        if (!isset($data['type']) || !isset($data['query'])) {
            $this->sendResponse(false, 'Inspection type and query are required', 400);
            return;
        }
        
        $advice = [
            'guidelines' => $this->getInspectionGuidelines($data['type']),
            'specific_advice' => $this->getSpecificInspectionAdvice($data['type'], $data['query']),
            'common_issues' => $this->getCommonIssues($data['type']),
            'tools_needed' => $this->getRequiredTools($data['type']),
            'estimated_time' => $this->getEstimatedInspectionTime($data['type'])
        ];
        
        $this->sendResponse(true, 'Inspection advice generated', 200, $advice);
    }
    
    /**
     * AI Dashboard Stats
     */
    private function aiDashboardStats() {
        // Mock AI dashboard statistics
        $stats = [
            'total_predictions' => '1247',
            'accuracy_rate' => '98.5%',
            'anomalies' => '23',
            'trend_score' => '+12%',
            'prediction_chart' => [
                'labels' => ['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
                'data' => [65, 72, 80, 78, 85, 90, 70]
            ],
            'faults_chart' => [
                'labels' => ['Brakes', 'Engine', 'Electrical', 'Suspension', 'Transmission'],
                'data' => [35, 25, 20, 15, 5]
            ],
            'predictions' => [
                ['type' => 'request_increase', 'confidence' => '95%', 'value' => '+15%', 'period' => '7 days'],
                ['type' => 'faults_expected', 'confidence' => '87%', 'value' => '12', 'period' => 'weekly'],
                ['type' => 'inspector_efficiency', 'confidence' => '92%', 'value' => '94%', 'period' => 'current']
            ],
            'recommendations' => [
                ['title' => 'Increase inspectors', 'description' => 'Expected 15% increase in requests next week', 'priority' => 'high'],
                ['title' => 'Maintenance equipment', 'description' => '3 devices need maintenance within 5 days', 'priority' => 'medium'],
                ['title' => 'Training needed', 'description' => '5 inspectors need training on new devices', 'priority' => 'low']
            ]
        ];
        
        $this->sendResponse(true, 'AI dashboard stats loaded', 200, $stats);
    }
    
    /**
     * Get all inspection types
     */
    private function getInspectionTypes() {
        $stmt = $this->db->prepare("
            SELECT * FROM inspection_types 
            WHERE is_active = TRUE 
            ORDER BY category, name_ar
        ");
        $stmt->execute();
        $types = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Group by category
        $grouped = [];
        foreach ($types as $type) {
            $grouped[$type['category']][] = $type;
        }
        
        $this->sendResponse(true, '', 200, $grouped);
    }
    
    /**
     * Get inspection checklist for a specific type
     */
    private function getInspectionChecklist($typeId) {
        if (!$typeId) {
            $this->sendResponse(false, 'Type ID is required', 400);
            return;
        }
        
        // Check if inspector has permission for this type
        if ($this->currentUser['role'] === 'inspector') {
            $hasPermission = $this->checkInspectorPermission($this->currentUser['id'], $typeId);
            if (!$hasPermission) {
                $this->sendResponse(false, 'You do not have permission for this inspection type', 403);
                return;
            }
        }
        
        $stmt = $this->db->prepare("
            SELECT 
                cc.id as category_id,
                cc.name_ar as category_name_ar,
                cc.name_en as category_name_en,
                cc.icon,
                cc.sort_order as category_sort,
                ci.id as item_id,
                ci.title_ar,
                ci.title_en,
                ci.description_ar,
                ci.description_en,
                ci.input_type,
                ci.options_ar,
                ci.options_en,
                ci.required,
                ci.sort_order as item_sort,
                ci.points_value
            FROM checklist_categories cc
            LEFT JOIN checklist_items ci ON cc.id = ci.category_id AND ci.is_active = TRUE
            WHERE cc.inspection_type_id = ?
            ORDER BY cc.sort_order, ci.sort_order
        ");
        $stmt->execute([$typeId]);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Group by category
        $checklist = [];
        foreach ($results as $row) {
            $categoryId = $row['category_id'];
            
            if (!isset($checklist[$categoryId])) {
                $checklist[$categoryId] = [
                    'id' => $categoryId,
                    'name_ar' => $row['category_name_ar'],
                    'name_en' => $row['category_name_en'],
                    'icon' => $row['icon'],
                    'sort_order' => $row['category_sort'],
                    'items' => []
                ];
            }
            
            if ($row['item_id']) {
                $checklist[$categoryId]['items'][] = [
                    'id' => $row['item_id'],
                    'title_ar' => $row['title_ar'],
                    'title_en' => $row['title_en'],
                    'description_ar' => $row['description_ar'],
                    'description_en' => $row['description_en'],
                    'input_type' => $row['input_type'],
                    'options_ar' => json_decode($row['options_ar'] ?? '[]', true),
                    'options_en' => json_decode($row['options_en'] ?? '[]', true),
                    'required' => (bool)$row['required'],
                    'sort_order' => $row['item_sort'],
                    'points_value' => $row['points_value']
                ];
            }
        }
        
        $this->sendResponse(true, '', 200, array_values($checklist));
    }
    
    /**
     * Save inspection results
     */
    private function saveInspectionResults() {
        $data = $this->getRequestData();
        
        $inspectionId = $data['inspection_id'] ?? null;
        $results = $data['results'] ?? [];
        
        if (!$inspectionId || empty($results)) {
            $this->sendResponse(false, 'Inspection ID and results are required', 400);
            return;
        }
        
        // Verify inspection belongs to this inspector
        if ($this->currentUser['role'] === 'inspector') {
            $stmt = $this->db->prepare("
                SELECT id FROM inspection_requests 
                WHERE id = ? AND inspector_id = ?
            ");
            $stmt->execute([$inspectionId, $this->currentUser['id']]);
            if (!$stmt->fetch()) {
                $this->sendResponse(false, 'Inspection not found or not assigned to you', 404);
                return;
            }
        }
        
        $this->db->beginTransaction();
        
        try {
            // Delete existing results for this inspection
            $stmt = $this->db->prepare("
                DELETE FROM inspection_results 
                WHERE inspection_request_id = ?
            ");
            $stmt->execute([$inspectionId]);
            
            // Insert new results
            $totalScore = 0;
            $maxScore = 0;
            
            foreach ($results as $result) {
                $stmt = $this->db->prepare("
                    INSERT INTO inspection_results 
                    (inspection_request_id, checklist_item_id, value, score, notes, images, inspector_id)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                
                $stmt->execute([
                    $inspectionId,
                    $result['item_id'],
                    $result['value'] ?? null,
                    $result['score'] ?? 0,
                    $result['notes'] ?? null,
                    json_encode($result['images'] ?? []),
                    $this->currentUser['id']
                ]);
                
                $totalScore += $result['score'] ?? 0;
                $maxScore += $result['points_value'] ?? 0;
            }
            
            // Update inspection status and score
            $percentage = $maxScore > 0 ? ($totalScore / $maxScore) * 100 : 0;
            $status = $percentage >= 70 ? 'completed' : 'needs_review';
            
            $stmt = $this->db->prepare("
                UPDATE inspection_requests 
                SET status = ?, score_percentage = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$status, $percentage, $inspectionId]);
            
            $this->db->commit();
            
            $this->sendResponse(true, 'Inspection results saved successfully', 200, [
                'score_percentage' => $percentage,
                'status' => $status
            ]);
            
        } catch (Exception $e) {
            $this->db->rollback();
            $this->sendResponse(false, 'Failed to save results: ' . $e->getMessage(), 500);
        }
    }
    
    /**
     * Get inspection results
     */
    private function getInspectionResults($inspectionId) {
        if (!$inspectionId) {
            $this->sendResponse(false, 'Inspection ID is required', 400);
            return;
        }
        
        // Verify access permissions
        if ($this->currentUser['role'] === 'inspector') {
            $stmt = $this->db->prepare("
                SELECT id FROM inspection_requests 
                WHERE id = ? AND inspector_id = ?
            ");
            $stmt->execute([$inspectionId, $this->currentUser['id']]);
            if (!$stmt->fetch()) {
                $this->sendResponse(false, 'Inspection not found or not assigned to you', 404);
                return;
            }
        }
        
        $stmt = $this->db->prepare("
            SELECT 
                ir.*,
                ci.title_ar,
                ci.title_en,
                ci.input_type,
                ci.options_ar,
                ci.options_en,
                ci.points_value,
                cc.name_ar as category_name_ar,
                cc.name_en as category_name_en,
                u.full_name as inspector_name
            FROM inspection_results ir
            JOIN checklist_items ci ON ir.checklist_item_id = ci.id
            JOIN checklist_categories cc ON ci.category_id = cc.id
            LEFT JOIN users u ON ir.inspector_id = u.id
            WHERE ir.inspection_request_id = ?
            ORDER BY cc.sort_order, ci.sort_order
        ");
        $stmt->execute([$inspectionId]);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Group by category
        $grouped = [];
        foreach ($results as $result) {
            $category = $result['category_name_ar'];
            if (!isset($grouped[$category])) {
                $grouped[$category] = [
                    'name_ar' => $result['category_name_ar'],
                    'name_en' => $result['category_name_en'],
                    'items' => []
                ];
            }
            
            $grouped[$category]['items'][] = [
                'title_ar' => $result['title_ar'],
                'title_en' => $result['title_en'],
                'value' => $result['value'],
                'score' => $result['score'],
                'notes' => $result['notes'],
                'images' => json_decode($result['images'] ?? '[]', true),
                'points_value' => $result['points_value'],
                'input_type' => $result['input_type'],
                'options_ar' => json_decode($result['options_ar'] ?? '[]', true),
                'options_en' => json_decode($result['options_en'] ?? '[]', true)
            ];
        }
        
        $this->sendResponse(true, '', 200, array_values($grouped));
    }
    
    /**
     * Get inspector permissions
     */
    private function getInspectorPermissions($inspectorId) {
        $stmt = $this->db->prepare("
            SELECT 
                ip.*,
                it.name_ar as type_name_ar,
                it.name_en as type_name_en,
                it.category,
                u.full_name as granted_by_name
            FROM inspector_permissions ip
            JOIN inspection_types it ON ip.inspection_type_id = it.id
            LEFT JOIN users u ON ip.granted_by = u.id
            WHERE ip.inspector_id = ? AND ip.is_active = TRUE
            ORDER BY it.category, it.name_ar
        ");
        $stmt->execute([$inspectorId]);
        $permissions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $this->sendResponse(true, '', 200, $permissions);
    }
    
    /**
     * Grant inspector permission (admin only)
     */
    private function grantInspectorPermission() {
        if ($this->currentUser['role'] !== 'admin') {
            $this->sendResponse(false, 'Admin access required', 403);
            return;
        }
        
        $data = $this->getRequestData();
        $inspectorId = $data['inspector_id'] ?? null;
        $typeId = $data['inspection_type_id'] ?? null;
        
        if (!$inspectorId || !$typeId) {
            $this->sendResponse(false, 'Inspector ID and inspection type ID are required', 400);
            return;
        }
        
        // Check if permission already exists
        $stmt = $this->db->prepare("
            SELECT id FROM inspector_permissions 
            WHERE inspector_id = ? AND inspection_type_id = ?
        ");
        $stmt->execute([$inspectorId, $typeId]);
        if ($stmt->fetch()) {
            $this->sendResponse(false, 'Permission already exists', 409);
            return;
        }
        
        $stmt = $this->db->prepare("
            INSERT INTO inspector_permissions 
            (inspector_id, inspection_type_id, granted_by)
            VALUES (?, ?, ?)
        ");
        $stmt->execute([$inspectorId, $typeId, $this->currentUser['id']]);
        
        $this->sendResponse(true, 'Permission granted successfully');
    }
    
    /**
     * AI Helper Functions
     */
    private function getMakeReliabilityFactor($make) {
        $factors = [
            'toyota' => 5,
            'honda' => 4,
            'nissan' => 3,
            'bmw' => 2,
            'mercedes' => 2,
            'audi' => 2,
            'hyundai' => 3,
            'kia' => 3
        ];
        return $factors[strtolower($make)] ?? 0;
    }
    
    private function getConditionLabel($score) {
        if ($score >= 90) return 'Excellent';
        if ($score >= 80) return 'Good';
        if ($score >= 70) return 'Fair';
        return 'Poor';
    }
    
    private function getVehicleRecommendations($score, $data) {
        $recommendations = [];
        
        if ($score < 80) {
            $recommendations[] = 'Schedule comprehensive inspection soon';
        }
        
        if ($data['mileage'] > 100000) {
            $recommendations[] = 'Consider major service check';
        }
        
        if ((2024 - $data['year']) > 10) {
            $recommendations[] = 'Check for wear and tear items';
        }
        
        return $recommendations;
    }
    
    private function getImmediateMaintenance($data) {
        return [
            ['name' => 'Oil Change', 'priority' => 'high', 'due_in' => '500 km'],
            ['name' => 'Brake Inspection', 'priority' => 'high', 'due_in' => '1,000 km']
        ];
    }
    
    private function getScheduledMaintenance($data) {
        return [
            ['name' => 'Tire Rotation', 'priority' => 'medium', 'due_in' => '5,000 km'],
            ['name' => 'Air Filter', 'priority' => 'medium', 'due_in' => '10,000 km'],
            ['name' => 'Transmission Service', 'priority' => 'medium', 'due_in' => '15,000 km']
        ];
    }
    
    private function getFutureMaintenance($data) {
        return [
            ['name' => 'Timing Belt', 'priority' => 'low', 'due_in' => '30,000 km'],
            ['name' => 'Coolant Flush', 'priority' => 'low', 'due_in' => '25,000 km']
        ];
    }
    
    private function estimateMaintenanceCost($data) {
        $baseCost = 500;
        $mileageFactor = min($data['mileage'] / 50000, 3) * 200;
        $ageFactor = (2024 - $data['year']) * 50;
        
        return $baseCost + $mileageFactor + $ageFactor;
    }
    
    private function getInspectionGuidelines($type) {
        $guidelines = [
            'engine' => ['Check oil level', 'Listen for unusual noises', 'Inspect for leaks', 'Check engine temperature'],
            'brakes' => ['Check brake pad thickness', 'Inspect brake discs', 'Test brake fluid', 'Check for vibrations'],
            'suspension' => ['Check for uneven tire wear', 'Test shock absorbers', 'Inspect for leaks', 'Check alignment'],
            'electrical' => ['Test battery voltage', 'Check lights', 'Inspect wiring', 'Test electronics']
        ];
        
        return $guidelines[$type] ?? $guidelines['engine'];
    }
    
    private function getSpecificInspectionAdvice($type, $query) {
        // Simple keyword-based advice generation
        $advice = "Based on your query about {$query}, our AI recommends a thorough inspection of the {$type} system. ";
        $advice .= "Please check all related components and consult with a qualified technician if issues persist.";
        
        return $advice;
    }
    
    private function getCommonIssues($type) {
        $issues = [
            'engine' => ['Oil leaks', 'Overheating', 'Strange noises', 'Poor performance'],
            'brakes' => ['Worn pads', 'Warped discs', 'Fluid leaks', 'Spongy pedal'],
            'suspension' => ['Worn shocks', 'Broken springs', 'Alignment issues', 'Tire wear'],
            'electrical' => ['Dead battery', 'Faulty alternator', 'Blown fuses', 'Bad wiring']
        ];
        
        return $issues[$type] ?? $issues['engine'];
    }
    
    private function getRequiredTools($type) {
        $tools = [
            'engine' => ['Socket set', 'Wrenches', 'Screwdrivers', 'Multimeter'],
            'brakes' => ['Brake tool set', 'Caliper', 'Wrenches', 'Jack stands'],
            'suspension' => ['Jack', 'Jack stands', 'Wrenches', 'Alignment tools'],
            'electrical' => ['Multimeter', 'Test light', 'Wire strippers', 'Screwdrivers']
        ];
        
        return $tools[$type] ?? $tools['engine'];
    }
    
    private function getEstimatedInspectionTime($type) {
        $times = [
            'engine' => '45-60 minutes',
            'brakes' => '30-45 minutes',
            'suspension' => '60-90 minutes',
            'electrical' => '30-60 minutes'
        ];
        
        return $times[$type] ?? '45-60 minutes';
    }
    
    /**
     * Generate inspection report
     */
    private function generateInspectionReport() {
        $data = $this->getRequestData();
        $inspectionId = $data['inspection_id'] ?? null;
        
        if (!$inspectionId) {
            $this->sendResponse(false, 'Inspection ID is required', 400);
            return;
        }
        
        // Get inspection data
        $stmt = $this->db->prepare("
            SELECT 
                ir.*,
                u.full_name as customer_name,
                u.phone as customer_phone,
                v.make,
                v.model,
                v.year,
                v.plate_number,
                insp.full_name as inspector_name
            FROM inspection_requests ir
            JOIN users u ON ir.customer_id = u.id
            JOIN vehicles v ON ir.vehicle_id = v.id
            LEFT JOIN users insp ON ir.inspector_id = insp.id
            WHERE ir.id = ?
        ");
        $stmt->execute([$inspectionId]);
        $inspection = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$inspection) {
            $this->sendResponse(false, 'Inspection not found', 404);
            return;
        }
        
        // Get results for report
        $stmt = $this->db->prepare("
            SELECT 
                ir.value,
                ir.score,
                ir.notes,
                ci.title_ar,
                ci.points_value,
                cc.name_ar as category_name
            FROM inspection_results ir
            JOIN checklist_items ci ON ir.checklist_item_id = ci.id
            JOIN checklist_categories cc ON ci.category_id = cc.id
            WHERE ir.inspection_request_id = ?
            ORDER BY cc.sort_order, ci.sort_order
        ");
        $stmt->execute([$inspectionId]);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Generate report summary
        $totalScore = array_sum(array_column($results, 'score'));
        $maxScore = array_sum(array_column($results, 'points_value'));
        $percentage = $maxScore > 0 ? ($totalScore / $maxScore) * 100 : 0;
        
        $summary = "????? ??????: " . round($percentage, 1) . "%\n";
        $summary .= "????? ??????: " . $totalScore . " / " . $maxScore . " ??????\n\n";
        $summary .= "????? ??????: " . $this->getGradeFromPercentage($percentage) . "\n\n";
        
        // Add category summaries
        $categories = [];
        foreach ($results as $result) {
            $cat = $result['category_name'];
            if (!isset($categories[$cat])) {
                $categories[$cat] = ['score' => 0, 'max' => 0, 'items' => []];
            }
            $categories[$cat]['score'] += $result['score'];
            $categories[$cat]['max'] += $result['points_value'];
            $categories[$cat]['items'][] = $result;
        }
        
        foreach ($categories as $name => $cat) {
            $catPercentage = $cat['max'] > 0 ? ($cat['score'] / $cat['max']) * 100 : 0;
            $summary .= "{$name}: " . round($catPercentage, 1) . "%\n";
        }
        
        // Update inspection with report summary
        $stmt = $this->db->prepare("
            UPDATE inspection_requests 
            SET report_summary = ?, report_url = ?, updated_at = NOW()
            WHERE id = ?
        ");
        $reportUrl = "http://autotestersystem.com/reports/{$inspectionId}";
        $stmt->execute([$summary, $reportUrl, $inspectionId]);
        
        $this->sendResponse(true, 'Report generated successfully', 200, [
            'summary' => $summary,
            'report_url' => $reportUrl,
            'percentage' => $percentage,
            'grade' => $this->getGradeFromPercentage($percentage)
        ]);
    }
    
    /**
     * Check if inspector has permission for inspection type
     */
    private function checkInspectorPermission($inspectorId, $typeId) {
        $stmt = $this->db->prepare("
            SELECT id FROM inspector_permissions 
            WHERE inspector_id = ? AND inspection_type_id = ? 
            AND is_active = TRUE AND (expires_at IS NULL OR expires_at > NOW())
        ");
        $stmt->execute([$inspectorId, $typeId]);
        return $stmt->fetch() !== false;
    }
    
    /**
     * Get grade from percentage
     */
    private function getGradeFromPercentage($percentage) {
        if ($percentage >= 85) return '??????';
        if ($percentage >= 70) return '???? ????';
        if ($percentage >= 60) return '?????';
        if ($percentage >= 50) return '?????';
        return '???? ????';
    }
    
    private function getTokenFromRequest() {
        $headers = getallheaders();
        return $headers['Authorization'] ?? $headers['authorization'] ?? null;
    }
    
    private function getRequestData() {
        $input = file_get_contents('php://input');
        return json_decode($input, true) ?? [];
    }
    
    private function sendResponse($success, $message = '', $statusCode = 200, $data = null) {
        http_response_code($statusCode);
        
        $response = [
            'success' => $success,
            'message' => $message
        ];
        
        if ($data !== null) {
            $response['data'] = $data;
        }
        
        echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        exit;
    }
    
    /**
     * Calculate vehicle rating based on inspection results
     */
    private function calculateVehicleRating() {
        $data = $this->getRequestData();
        $inspectionId = $data['inspection_id'] ?? null;
        
        if (!$inspectionId) {
            $this->sendResponse(false, 'Inspection ID is required', 400);
            return;
        }
        
        // Get inspection results
        $stmt = $this->db->prepare("
            SELECT ir.*, 
                   COUNT(CASE WHEN ic.status = 'good' THEN 1 END) as good_count,
                   COUNT(CASE WHEN ic.status = 'warning' THEN 1 END) as warning_count,
                   COUNT(CASE WHEN ic.status = 'fail' THEN 1 END) as fail_count,
                   COUNT(*) as total_count
            FROM inspection_requests ir
            LEFT JOIN inspection_checklist ic ON ir.id = ic.inspection_id
            WHERE ir.id = ?
            GROUP BY ir.id
        ");
        $stmt->execute([$inspectionId]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$result) {
            $this->sendResponse(false, 'Inspection not found', 404);
            return;
        }
        
        // Calculate percentage
        $totalItems = $result['total_count'] ?: 200;
        $goodScore = $result['good_count'] * 100;
        $warningScore = $result['warning_count'] * 60;
        $failScore = $result['fail_count'] * 20;
        
        $totalScore = $goodScore + $warningScore + $failScore;
        $overallPercentage = round($totalScore / $totalItems, 2);
        
        // Determine condition level
        if ($overallPercentage >= 90) {
            $conditionLevel = 'excellent';
            $starRating = 5.0;
            $conditionText = 'excellent';
            $conditionColor = '#00ff88';
        } elseif ($overallPercentage >= 80) {
            $conditionLevel = 'very_good';
            $starRating = 4.5;
            $conditionText = 'very_good';
            $conditionColor = '#00c8ff';
        } elseif ($overallPercentage >= 70) {
            $conditionLevel = 'good';
            $starRating = 4.0;
            $conditionText = 'good';
            $conditionColor = '#ffaa00';
        } elseif ($overallPercentage >= 60) {
            $conditionLevel = 'fair';
            $starRating = 3.0;
            $conditionText = 'fair';
            $conditionColor = '#ff8800';
        } else {
            $conditionLevel = 'poor';
            $starRating = 2.0;
            $conditionText = 'poor';
            $conditionColor = '#ff4444';
        }
        
        // Save rating
        $stmt = $this->db->prepare("
            INSERT INTO vehicle_ratings 
            (inspection_id, overall_score, star_rating, condition_level, condition_text_ar, condition_color,
             good_count, warning_count, fail_count, total_items, rated_by) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
            overall_score = VALUES(overall_score),
            star_rating = VALUES(star_rating),
            condition_level = VALUES(condition_level),
            condition_text_ar = VALUES(condition_text_ar),
            condition_color = VALUES(condition_color),
            good_count = VALUES(good_count),
            warning_count = VALUES(warning_count),
            fail_count = VALUES(fail_count),
            total_items = VALUES(total_items),
            rated_by = VALUES(rated_by),
            updated_at = NOW()
        ");
        $stmt->execute([
            $inspectionId, $overallPercentage, $starRating, $conditionLevel, $conditionText, $conditionColor,
            $result['good_count'], $result['warning_count'], $result['fail_count'], $totalItems, $this->currentUser['id']
        ]);
        
        $this->sendResponse(true, 'Rating calculated successfully', 200, [
            'percentage' => $overallPercentage,
            'star_rating' => $starRating,
            'condition_level' => $conditionLevel,
            'condition_text' => $conditionText,
            'condition_color' => $conditionColor,
            'good_count' => $result['good_count'],
            'warning_count' => $result['warning_count'],
            'fail_count' => $result['fail_count'],
            'total_items' => $totalItems
        ]);
    }
    
    /**
     * Calculate vehicle price based on rating and market data
     */
    private function calculateVehiclePrice() {
        $data = $this->getRequestData();
        $inspectionId = $data['inspection_id'] ?? null;
        $mileage = $data['mileage'] ?? null;
        
        if (!$inspectionId) {
            $this->sendResponse(false, 'Inspection ID is required', 400);
            return;
        }
        
        // Get vehicle data
        $stmt = $this->db->prepare("
            SELECT ir.*, vr.overall_score, vr.condition_level
            FROM inspection_requests ir
            LEFT JOIN vehicle_ratings vr ON ir.id = vr.inspection_id
            WHERE ir.id = ?
        ");
        $stmt->execute([$inspectionId]);
        $vehicle = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$vehicle) {
            $this->sendResponse(false, 'Vehicle not found', 404);
            return;
        }
        
        // Get base price
        $stmt = $this->db->prepare("
            SELECT * FROM vehicle_pricing 
            WHERE make = ? AND model = ? AND year = ?
        ");
        $stmt->execute([$vehicle['car_make'], $vehicle['car_model'], $vehicle['car_year']]);
        $pricing = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$pricing) {
            // Estimate base price
            $basePrice = $this->estimateBasePrice($vehicle['car_make'], $vehicle['car_model'], $vehicle['car_year']);
            $depreciationRate = 10;
        } else {
            $basePrice = $pricing['base_price'];
            $depreciationRate = $pricing['depreciation_rate'] ?? 10;
        }
        
        // Calculate deductions
        $mileage = $mileage ?? $vehicle['mileage'] ?? 0;
        $mileageDiscount = ($mileage / 10000) * 500;
        
        // Calculate depreciation
        $currentYear = date('Y');
        $vehicleAge = $currentYear - $vehicle['car_year'];
        $depreciation = $basePrice * ($depreciationRate / 100) * $vehicleAge;
        
        // Get condition adjustment
        $stmt = $this->db->prepare("SELECT adjustment_percentage FROM price_adjustments WHERE condition_level = ?");
        $stmt->execute([$vehicle['condition_level'] ?? 'good']);
        $adjustment = $stmt->fetch(PDO::FETCH_ASSOC);
        $conditionAdjustment = $adjustment['adjustment_percentage'] ?? 0;
        
        // Calculate final price
        $priceBeforeAdjustment = $basePrice - $mileageDiscount - $depreciation;
        $finalPrice = $priceBeforeAdjustment * (1 + $conditionAdjustment / 100);
        
        // Calculate price range
        $priceRange = [
            'min' => round($finalPrice * 0.9, -3),
            'max' => round($finalPrice * 1.1, -3),
            'estimated' => round($finalPrice, -3)
        ];
        
        $this->sendResponse(true, 'Price calculated successfully', 200, [
            'base_price' => $basePrice,
            'mileage_discount' => $mileageDiscount,
            'depreciation' => $depreciation,
            'condition_adjustment' => $conditionAdjustment,
            'final_price' => $finalPrice,
            'price_range' => $priceRange,
            'mileage' => $mileage,
            'vehicle_age' => $vehicleAge
        ]);
    }
    
    /**
     * Save vehicle recommendations
     */
    private function saveVehicleRecommendations() {
        $data = $this->getRequestData();
        $inspectionId = $data['inspection_id'] ?? null;
        $recommendations = $data['recommendations'] ?? null;
        
        if (!$inspectionId || !$recommendations) {
            $this->sendResponse(false, 'Inspection ID and recommendations are required', 400);
            return;
        }
        
        $stmt = $this->db->prepare("
            UPDATE vehicle_ratings 
            SET recommendation = ? 
            WHERE inspection_id = ?
        ");
        $stmt->execute([$recommendations, $inspectionId]);
        
        $this->sendResponse(true, 'Recommendations saved successfully');
    }
    
    /**
     * Get vehicle prices from database
     */
    private function getVehiclePrices() {
        $make = $_GET['make'] ?? '';
        $model = $_GET['model'] ?? '';
        $year = $_GET['year'] ?? '';
        
        $sql = "SELECT * FROM vehicle_pricing WHERE 1=1";
        $params = [];
        
        if ($make) {
            $sql .= " AND make = ?";
            $params[] = $make;
        }
        if ($model) {
            $sql .= " AND model = ?";
            $params[] = $model;
        }
        if ($year) {
            $sql .= " AND year = ?";
            $params[] = $year;
        }
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        $prices = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $this->sendResponse(true, '', 200, $prices);
    }
    
    /**
     * Estimate base price for vehicle
     */
    private function estimateBasePrice($make, $model, $year) {
        $priceEstimates = [
            'toyota' => ['camry' => 850000, 'corolla' => 650000, 'yaris' => 420000],
            'hyundai' => ['elantra' => 580000, 'tucson' => 750000, 'accent' => 480000],
            'nissan' => ['sentra' => 530000, 'sunny' => 420000, 'patrol' => 1800000],
            'mercedes' => ['e-class' => 2800000, 'c-class' => 2200000, 'a-class' => 1800000],
            'bmw' => ['x5' => 2500000, 'x3' => 2000000, '3-series' => 1900000],
            'kia' => ['sportage' => 680000, 'cerato' => 530000, 'picanto' => 380000],
            'chevrolet' => ['express' => 650000, 'captiva' => 750000, 'aveo' => 320000]
        ];
        
        $basePrice = $priceEstimates[strtolower($make)][strtolower($model)] ?? 500000;
        
        // Adjust for year
        $currentYear = date('Y');
        $yearDiff = $currentYear - $year;
        $adjustedPrice = $basePrice * (1 - ($yearDiff * 0.05));
        
        return max($adjustedPrice, 100000);
    }
    
    private function sendResponse($success, $message = '', $statusCode = 200, $data = null) {
        http_response_code($statusCode);
        
        $response = [
            'success' => $success,
            'message' => $message
        ];
        
        if ($data !== null) {
            $response['data'] = $data;
        }
        
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
        exit;
    }
}

// Initialize and handle request
try {
    $api = new APIHandler();
    $api->handleRequest();
} catch (Exception $e) {
    Database::getInstance()->logError("API Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Internal server error'
    ], JSON_UNESCAPED_UNICODE);
}
?>
