<?php
// ============================================
// API الموحد لجميع الصلاحيات - AUTO TESTER
// ✅ النسخة المصححة - تم إصلاح جميع الأخطاء
// ============================================

set_time_limit(60);
ini_set('session.gc_maxlifetime', 604800);
ini_set('session.cookie_lifetime', 604800);

// ============================================
// ✅ إصلاح #1 — CORS صحيح (لا يجمع * مع credentials)
// المشكلة القديمة: header('Access-Control-Allow-Origin: *') مع Allow-Credentials: true
// المتصفح يرفض هذا التوليف تماماً — يجب تحديد الـ origin بالاسم
// ============================================
$allowed_origins = [
    'https://digitalsatcourses.com',
    'http://digitalsatcourses.com',
    'http://localhost',
    'http://localhost:3000',
    'http://localhost:8080',
    'http://127.0.0.1',
];

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

if (in_array($origin, $allowed_origins)) {
    // ✅ Origin معروف — نسمح له مع credentials
    header("Access-Control-Allow-Origin: $origin");
    header('Access-Control-Allow-Credentials: true');
} else {
    // ✅ Origin غير معروف — نسمح بدون credentials (للطلبات العامة فقط)
    header('Access-Control-Allow-Origin: ' . ($allowed_origins[0] ?? '*'));
}

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, X-HTTP-Method-Override');
header('Access-Control-Max-Age: 86400');
header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

// معالجة طلبات OPTIONS (pre-flight)
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// تسجيل الأخطاء
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');

// بدء الجلسة
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ============================================
// إعدادات قاعدة البيانات
// ============================================
class Database {
    private $host = "localhost";
    private $db_name = "digitals_autotester_db";
    private $username = "digitals_user";
    private $password = "bassam.bassam";
    private $conn;
    private static $instance = null;
    private function __construct() {}
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance;
    }

    public function getConnection() {
        if ($this->conn === null) {
            try {
                $this->conn = new PDO(
                    "mysql:host=" . $this->host . ";dbname=" . $this->db_name . ";charset=utf8mb4",
                    $this->username,
                    $this->password,
                    [
                        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                        PDO::ATTR_EMULATE_PREPARES => false,
                        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
                    ]
                );
            } catch(PDOException $e) {
                error_log('Database connection failed: ' . $e->getMessage());
                // ✅ لا نكشف تفاصيل الخطأ للمستخدم
                sendResponse(false, 'حدث خطأ في الاتصال بقاعدة البيانات. يرجى المحاولة لاحقاً.', null, 500);
            }
        }
        return $this->conn;
    }
}

// ============================================
// دوال مساعدة عامة
// ============================================

function sendResponse($success, $message = '', $data = null, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data'    => $data,
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit();
}

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

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

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

function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

function generateCsrfToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// ============================================
// دوال المصادقة والصلاحيات
// ============================================

function verifyToken($token, $pdo) {
    $stmt = $pdo->prepare("
        SELECT s.user_id, s.expires_at,
               u.id, u.full_name, u.email, u.phone, u.role, u.user_type, u.status,
               u.area, u.assigned_region, u.department_id, u.supervisor_id,
               u.rating, u.experience_years
        FROM admin_sessions s
        JOIN users u ON s.user_id = u.id
        WHERE s.token = ? AND u.status = 'active'
    ");
    $stmt->execute([$token]);
    $user = $stmt->fetch();

    if ($user) {
        $expiresAt = strtotime($user['expires_at']);
        $now = time();
        if ($expiresAt > $now) {
            return $user;
        } else {
            // حذف التوكن المنتهي
            $del = $pdo->prepare("DELETE FROM admin_sessions WHERE token = ?");
            $del->execute([$token]);
            return null;
        }
    }
    return null;
}

function checkPermission($user, $requiredRole) {
    if (!$user) return false;
    if (is_array($requiredRole)) {
        return in_array($user['role'], $requiredRole) || in_array($user['user_type'], $requiredRole);
    }
    return $user['role'] === $requiredRole || $user['user_type'] === $requiredRole;
}

function checkRegionAccess($user, $targetRegion) {
    if (checkPermission($user, 'admin')) return true;
    if (checkPermission($user, 'supervisor')) {
        return $user['assigned_region'] === $targetRegion;
    }
    return false;
}

function logActivity($pdo, $userId, $action, $details = null) {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO activity_log (user_id, action, details, ip_address, user_agent, created_at)
            VALUES (?, ?, ?, ?, ?, NOW())
        ");
        $stmt->execute([
            $userId,
            $action,
            $details,
            $_SERVER['REMOTE_ADDR'] ?? null,
            $_SERVER['HTTP_USER_AGENT'] ?? null
        ]);
    } catch (Exception $e) {
        error_log('Failed to log activity: ' . $e->getMessage());
    }
}

// ============================================
// معالج الطلبات الرئيسي
// ============================================

try {
    $db  = Database::getInstance();
    $pdo = $db->getConnection();
    $data   = getRequestData();
    $method = $_SERVER['REQUEST_METHOD'];
    $action = $_GET['action'] ?? $_POST['action'] ?? null;

    if (!$action) {
        $path      = $_SERVER['PATH_INFO'] ?? '';
        $pathParts = explode('/', trim($path, '/'));
        $action    = $pathParts[0] ?? '';
    }

    // ============================================
    // 1. تسجيل الدخول
    // ============================================
    if ($action === 'login') {
        if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
        validateRequiredFields($data, ['email', 'password']);

        $email = sanitizeInput($data['email']);

        $stmt = $pdo->prepare("
            SELECT id, user_uuid, full_name, username, email, phone, password_hash,
                   role, user_type, status, area, assigned_region, department_id, supervisor_id,
                   rating, experience_years, profile_image
            FROM users
            WHERE (email = ? OR phone = ?) AND status = 'active'
        ");
        $stmt->execute([$email, $email]);
        $user = $stmt->fetch();

        if (!$user) {
            logActivity($pdo, null, 'login_failed', "محاولة تسجيل دخول فاشلة: $email");
            sendResponse(false, 'البريد الإلكتروني أو كلمة المرور غير صحيحة', null, 401);
        }

        if (!password_verify($data['password'], $user['password_hash'])) {
            logActivity($pdo, $user['id'], 'login_failed', 'كلمة مرور غير صحيحة');
            sendResponse(false, 'البريد الإلكتروني أو كلمة المرور غير صحيحة', null, 401);
        }

        // تحديث آخر تسجيل دخول
        $stmt = $pdo->prepare("UPDATE users SET last_login_at = NOW() WHERE id = ?");
        $stmt->execute([$user['id']]);

        // إنشاء توكن جديد
        $token   = bin2hex(random_bytes(32));
        $expires = date('Y-m-d H:i:s', strtotime('+7 days'));

        // حذف الجلسات القديمة لنفس المستخدم
        $stmt = $pdo->prepare("DELETE FROM admin_sessions WHERE user_id = ?");
        $stmt->execute([$user['id']]);

        // إنشاء جلسة جديدة في قاعدة البيانات
        $stmt = $pdo->prepare("INSERT INTO admin_sessions (user_id, token, expires_at) VALUES (?, ?, ?)");
        $stmt->execute([$user['id'], $token, $expires]);

        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        $_SESSION['user_id']    = $user['id'];
        $_SESSION['role']       = $user['role'];

        // لا نُرجع كلمة المرور المُشفَّرة
        unset($user['password_hash']);

        logActivity($pdo, $user['id'], 'login', 'تسجيل دخول ناجح');

        sendResponse(true, 'تم تسجيل الدخول بنجاح', [
            'token'      => $token,
            'user'       => $user,
            'expires_at' => $expires,
            'csrf_token' => $_SESSION['csrf_token']
        ]);
    }

    // ============================================
    // 2. التحقق من التوكن
    // ============================================
    if ($action === 'verify_token') {
        $headers    = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';

        if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            $token = trim($matches[1]);
            $user  = verifyToken($token, $pdo);

            if ($user) {
                // تجديد فترة الجلسة
                $newExpires = date('Y-m-d H:i:s', strtotime('+7 days'));
                $stmt = $pdo->prepare("UPDATE admin_sessions SET expires_at = ? WHERE token = ?");
                $stmt->execute([$newExpires, $token]);

                sendResponse(true, 'توكن صالح', [
                    'user' => [
                        'id'              => $user['id'],
                        'full_name'       => $user['full_name'],
                        'email'           => $user['email'],
                        'phone'           => $user['phone'],
                        'role'            => $user['role'],
                        'user_type'       => $user['user_type'],
                        'area'            => $user['area'],
                        'assigned_region' => $user['assigned_region']
                    ],
                    'expires_at' => $newExpires
                ]);
            } else {
                sendResponse(false, 'توكن غير صالح أو منتهي', null, 401);
            }
        } else {
            sendResponse(false, 'لم يتم توفير توكن', null, 401);
        }
    }

    // ============================================
    // 3. تسجيل الخروج
    // ============================================
    if ($action === 'logout') {
        $headers    = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';

        if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            $stmt = $pdo->prepare("DELETE FROM admin_sessions WHERE token = ?");
            $stmt->execute([$matches[1]]);
            logActivity($pdo, $_SESSION['user_id'] ?? null, 'logout', 'تسجيل خروج');
        }

        $_SESSION = [];
        if (isset($_COOKIE[session_name()])) {
            setcookie(session_name(), '', time() - 3600, '/');
        }
        session_destroy();

        sendResponse(true, 'تم تسجيل الخروج بنجاح');
    }

    // ============================================
    // التحقق من المصادقة لبقية الطلبات
    // ============================================
    $headers     = getallheaders();
    $authHeader  = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    $currentUser = null;

    if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
        $currentUser = verifyToken($matches[1], $pdo);
    }

    $publicActions = ['login', 'verify_token', 'logout', 'register', 'forgot_password', 'reset_password'];

    if (!$currentUser && !in_array($action, $publicActions)) {
        sendResponse(false, 'غير مصرح بالوصول، يرجى تسجيل الدخول', null, 401);
    }

    // ============================================
    // 4. إحصائيات لوحة التحكم (للمدير والمشرف)
    // ============================================
    if ($action === 'get_dashboard_stats') {
        if (!checkPermission($currentUser, ['admin', 'supervisor'])) {
            sendResponse(false, 'غير مصرح بالوصول', null, 403);
        }

        // ✅ إصلاح #2 — فلتر المنطقة الصحيح
        // المشكلة القديمة: كان يستخدم "assigned_region" لجدول inspections
        // لكن جدول inspections فيه عمود اسمه "region" وليس "assigned_region"
        // جدول users فيه "assigned_region" وهذا صحيح للمستخدمين فقط

        $userRegionFilter        = '';   // للاستعلام على جدول users
        $inspectionRegionFilter  = '';   // للاستعلام على جدول inspections
        $params                  = [];

        if (!checkPermission($currentUser, 'admin') && $currentUser['assigned_region']) {
            $userRegionFilter       = " AND assigned_region = :region";
            $inspectionRegionFilter = " AND region = :region";           // ✅ الصح لجدول inspections
            $params[':region']      = $currentUser['assigned_region'];
        }

        // إحصائيات المستخدمين
        $sql = "SELECT
                    COUNT(*) as total,
                    SUM(CASE WHEN role = 'inspector'  THEN 1 ELSE 0 END) as inspectors,
                    SUM(CASE WHEN role = 'client'     THEN 1 ELSE 0 END) as clients,
                    SUM(CASE WHEN role = 'admin'      THEN 1 ELSE 0 END) as admins,
                    SUM(CASE WHEN role = 'supervisor' THEN 1 ELSE 0 END) as supervisors,
                    SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as new_today
                FROM users WHERE status = 'active' $userRegionFilter";

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $userStats = $stmt->fetch();

        // إحصائيات الفحوصات — ✅ يستخدم inspectionRegionFilter (region وليس assigned_region)
        $sql = "SELECT
                    COUNT(*) as total,
                    SUM(CASE WHEN status = 'pending'     THEN 1 ELSE 0 END) as pending,
                    SUM(CASE WHEN status = 'assigned'    THEN 1 ELSE 0 END) as assigned,
                    SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress,
                    SUM(CASE WHEN status = 'completed'   THEN 1 ELSE 0 END) as completed,
                    SUM(CASE WHEN status = 'cancelled'   THEN 1 ELSE 0 END) as cancelled,
                    SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today
                FROM inspections WHERE 1=1 $inspectionRegionFilter";

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $inspectionStats = $stmt->fetch();

        // إحصائيات الإيرادات
        $sql = "SELECT
                    COALESCE(SUM(total_amount), 0) as total,
                    COALESCE(SUM(CASE WHEN MONTH(created_at) = MONTH(NOW()) THEN total_amount ELSE 0 END), 0) as monthly
                FROM inspections WHERE status = 'completed' $inspectionRegionFilter";

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $revenueStats = $stmt->fetch();

        // أفضل الفاحصين
        $sql = "SELECT u.id, u.full_name, u.rating, u.assigned_region, COUNT(i.id) as inspections_count
                FROM users u
                LEFT JOIN inspections i ON u.id = i.inspector_id
                WHERE u.role = 'inspector' AND u.status = 'active' $userRegionFilter
                GROUP BY u.id
                ORDER BY inspections_count DESC LIMIT 5";

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $topInspectors = $stmt->fetchAll();

        // آخر الفحوصات
        $sql = "SELECT i.id, i.request_number, i.car_make, i.car_model, i.status, i.created_at,
                       u.full_name as customer_name, u.phone as customer_phone
                FROM inspections i
                LEFT JOIN users u ON i.user_id = u.id
                WHERE 1=1 $inspectionRegionFilter
                ORDER BY i.created_at DESC LIMIT 10";

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $recentInspections = $stmt->fetchAll();

        sendResponse(true, 'تم جلب الإحصائيات بنجاح', [
            'total_users'             => (int)($userStats['total']        ?? 0),
            'total_inspectors'        => (int)($userStats['inspectors']   ?? 0),
            'total_clients'           => (int)($userStats['clients']      ?? 0),
            'total_admins'            => (int)($userStats['admins']       ?? 0),
            'total_supervisors'       => (int)($userStats['supervisors']  ?? 0),
            'new_users_today'         => (int)($userStats['new_today']    ?? 0),
            'total_inspections'       => (int)($inspectionStats['total']       ?? 0),
            'pending_inspections'     => (int)($inspectionStats['pending']     ?? 0),
            'assigned_inspections'    => (int)($inspectionStats['assigned']    ?? 0),
            'in_progress_inspections' => (int)($inspectionStats['in_progress'] ?? 0),
            'completed_inspections'   => (int)($inspectionStats['completed']   ?? 0),
            'cancelled_inspections'   => (int)($inspectionStats['cancelled']   ?? 0),
            'today_inspections'       => (int)($inspectionStats['today']       ?? 0),
            'total_revenue'           => (float)($revenueStats['total']   ?? 0),
            'monthly_revenue'         => (float)($revenueStats['monthly'] ?? 0),
            'top_inspectors'          => $topInspectors,
            'recent_inspections'      => $recentInspections
        ]);
    }

    // ============================================
    // 5. جلب الفاحصين (للمدير والمشرف)
    // ============================================
    if ($action === 'get_inspectors') {
        if (!checkPermission($currentUser, ['admin', 'supervisor'])) {
            sendResponse(false, 'غير مصرح بالوصول', null, 403);
        }

        $regionFilter = '';
        $params       = [];

        if (!checkPermission($currentUser, 'admin') && $currentUser['assigned_region']) {
            $regionFilter         = " AND u.assigned_region = :region";
            $params[':region']    = $currentUser['assigned_region'];
        }

        $sql = "SELECT u.id, u.full_name, u.email, u.phone, u.area, u.assigned_region,
                       u.rating, u.status, u.experience_years,
                       COUNT(i.id) as inspections_count,
                       COALESCE(AVG(i.car_score), 0) as avg_score
                FROM users u
                LEFT JOIN inspections i ON u.id = i.inspector_id
                WHERE (u.role = 'inspector' OR u.user_type = 'inspector')
                $regionFilter
                GROUP BY u.id
                ORDER BY inspections_count DESC";

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        sendResponse(true, 'تم جلب الفاحصين بنجاح', $stmt->fetchAll());
    }

    // ============================================
    // 6. جلب العملاء
    // ============================================
    if ($action === 'get_clients') {
        if (!checkPermission($currentUser, ['admin', 'supervisor'])) {
            sendResponse(false, 'غير مصرح بالوصول', null, 403);
        }

        $regionFilter = '';
        $params       = [];

        if (!checkPermission($currentUser, 'admin') && $currentUser['assigned_region']) {
            $regionFilter      = " AND assigned_region = :region";
            $params[':region'] = $currentUser['assigned_region'];
        }

        $sql = "SELECT id, full_name, email, phone, status, created_at,
                       (SELECT COUNT(*) FROM inspections WHERE user_id = users.id) as inspections_count
                FROM users
                WHERE (role = 'client' OR user_type = 'client')
                $regionFilter
                ORDER BY created_at DESC";

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        sendResponse(true, 'تم جلب العملاء بنجاح', $stmt->fetchAll());
    }

    // ============================================
    // 7. جلب الطلبات المعلقة
    // ============================================
    if ($action === 'get_pending_inspections') {
        if (!checkPermission($currentUser, ['admin', 'supervisor'])) {
            sendResponse(false, 'غير مصرح بالوصول', null, 403);
        }

        $regionFilter = '';
        $params       = [];

        if (!checkPermission($currentUser, 'admin') && $currentUser['assigned_region']) {
            $regionFilter      = " AND i.region = :region";   // ✅ region الصحيح
            $params[':region'] = $currentUser['assigned_region'];
        }

        $sql = "SELECT i.*, u.full_name as customer_name, u.phone as customer_phone,
                       ins.full_name as inspector_name
                FROM inspections i
                LEFT JOIN users u   ON i.user_id     = u.id
                LEFT JOIN users ins ON i.inspector_id = ins.id
                WHERE i.status = 'pending'
                $regionFilter
                ORDER BY i.created_at ASC";

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        sendResponse(true, 'تم جلب الطلبات المعلقة', $stmt->fetchAll());
    }

    // ============================================
    // 8. جلب الفاحصين المتاحين
    // ============================================
    if ($action === 'get_available_inspectors') {
        if (!checkPermission($currentUser, ['admin', 'supervisor'])) {
            sendResponse(false, 'غير مصرح بالوصول', null, 403);
        }

        $regionFilter = '';
        $params       = [];

        if (!checkPermission($currentUser, 'admin') && $currentUser['assigned_region']) {
            $regionFilter      = " AND assigned_region = :region";
            $params[':region'] = $currentUser['assigned_region'];
        }

        $sql = "SELECT u.id, u.full_name, u.email, u.phone, u.area, u.assigned_region, u.rating,
                       (SELECT COUNT(*) FROM inspections
                        WHERE inspector_id = u.id AND status IN ('assigned','in_progress')) as active_tasks
                FROM users u
                WHERE (u.role = 'inspector' OR u.user_type = 'inspector') AND u.status = 'active'
                $regionFilter
                ORDER BY active_tasks ASC";

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        sendResponse(true, 'تم جلب الفاحصين المتاحين', $stmt->fetchAll());
    }

    // ============================================
    // 9. جلب المستخدمين
    // ============================================
    if ($action === 'get_users') {
        if (!checkPermission($currentUser, 'admin')) {
            sendResponse(false, 'غير مصرح بالوصول', null, 403);
        }

        $role  = $_GET['role'] ?? '';
        $limit = (int)($_GET['limit'] ?? 100);

        $sql = "SELECT id, full_name, email, phone, role, user_type, status, area, assigned_region, created_at
                FROM users WHERE 1=1";
        if ($role) {
            $sql .= " AND (role = :role OR user_type = :role)";
        }
        $sql .= " ORDER BY created_at DESC LIMIT :limit";

        $stmt = $pdo->prepare($sql);
        if ($role) $stmt->bindParam(':role', $role);
        $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
        $stmt->execute();

        sendResponse(true, 'تم جلب المستخدمين بنجاح', $stmt->fetchAll());
    }

    // ============================================
    // 10. إضافة مستخدم جديد (للمدير فقط)
    // ============================================
    if ($action === 'add_user') {
        if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
        if (!checkPermission($currentUser, 'admin')) {
            sendResponse(false, 'غير مصرح بالوصول', null, 403);
        }
        validateRequiredFields($data, ['full_name', 'email']);

        if (!validateEmail($data['email'])) {
            sendResponse(false, 'البريد الإلكتروني غير صحيح', null, 400);
        }

        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$data['email']]);
        if ($stmt->fetch()) {
            sendResponse(false, 'البريد الإلكتروني مستخدم بالفعل', null, 400);
        }

        $defaultPassword = '123456';
        $passwordHash    = password_hash($defaultPassword, PASSWORD_DEFAULT);

        $fullName       = sanitizeInput($data['full_name']);
        $email          = sanitizeInput($data['email']);
        $phone          = sanitizeInput($data['phone'] ?? '');
        $role           = $data['role'] ?? 'client';
        $userType       = $data['user_type'] ?? $role;
        $area           = sanitizeInput($data['area'] ?? '');
        $assignedRegion = sanitizeInput($data['assigned_region'] ?? '');

        $stmt = $pdo->prepare("
            INSERT INTO users (user_uuid, full_name, email, phone, password_hash, role, user_type, area, assigned_region, status, created_at)
            VALUES (UUID(), ?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW())
        ");
        $stmt->execute([$fullName, $email, $phone, $passwordHash, $role, $userType, $area, $assignedRegion]);

        $newUserId = $pdo->lastInsertId();
        logActivity($pdo, $currentUser['id'], 'add_user', "إضافة مستخدم ID: $newUserId - $fullName");

        sendResponse(true, 'تم إضافة المستخدم بنجاح', [
            'id'               => $newUserId,
            'default_password' => $defaultPassword
        ]);
    }

    // ============================================
    // 11. تحديث مستخدم (للمدير فقط)
    // ============================================
    if ($action === 'update_user') {
        if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
        if (!checkPermission($currentUser, 'admin')) {
            sendResponse(false, 'غير مصرح بالوصول', null, 403);
        }
        validateRequiredFields($data, ['id']);

        $updates = [];
        $params  = [];

        $allowedFields = ['full_name', 'email', 'phone', 'role', 'user_type', 'status', 'area', 'assigned_region'];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $updates[] = "$field = ?";
                $params[]  = sanitizeInput($data[$field]);
            }
        }

        if (isset($data['password']) && !empty($data['password'])) {
            $updates[] = "password_hash = ?";
            $params[]  = password_hash($data['password'], PASSWORD_DEFAULT);
        }

        if (empty($updates)) {
            sendResponse(false, 'لا توجد بيانات للتحديث', null, 400);
        }

        $params[] = $data['id'];
        $sql      = "UPDATE users SET " . implode(', ', $updates) . " WHERE id = ?";
        $stmt     = $pdo->prepare($sql);
        $stmt->execute($params);

        logActivity($pdo, $currentUser['id'], 'update_user', "تحديث مستخدم ID: {$data['id']}");
        sendResponse(true, 'تم تحديث المستخدم بنجاح');
    }

    // ============================================
    // 12. حذف مستخدم (للمدير فقط)
    // ============================================
    if ($action === 'delete_user') {
        if ($method !== 'DELETE') sendResponse(false, 'Method not allowed', null, 405);
        if (!checkPermission($currentUser, 'admin')) {
            sendResponse(false, 'غير مصرح بالوصول', null, 403);
        }

        $id = (int)($_GET['id'] ?? $data['id'] ?? 0);
        if (!$id) sendResponse(false, 'معرف المستخدم مطلوب', null, 400);

        $stmt = $pdo->prepare("SELECT role FROM users WHERE id = ?");
        $stmt->execute([$id]);
        $user = $stmt->fetch();

        if ($user && ($user['role'] === 'admin' || $user['user_type'] === 'admin')) {
            sendResponse(false, 'لا يمكن حذف حساب المدير', null, 400);
        }

        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$id]);

        logActivity($pdo, $currentUser['id'], 'delete_user', "حذف مستخدم ID: $id");
        sendResponse(true, 'تم حذف المستخدم بنجاح');
    }

    // ============================================
    // 13. تحديث حالة المستخدم (للمدير فقط)
    // ============================================
    if ($action === 'update_user_status') {
        if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
        if (!checkPermission($currentUser, 'admin')) {
            sendResponse(false, 'غير مصرح بالوصول', null, 403);
        }
        validateRequiredFields($data, ['id', 'status']);

        $stmt = $pdo->prepare("UPDATE users SET status = ? WHERE id = ?");
        $stmt->execute([$data['status'], $data['id']]);

        logActivity($pdo, $currentUser['id'], 'update_user_status', "تحديث حالة المستخدم ID: {$data['id']} إلى {$data['status']}");
        sendResponse(true, 'تم تحديث حالة المستخدم بنجاح');
    }

    // ============================================
    // 14. جلب الفحوصات (حسب الصلاحية)
    // ============================================
    if ($action === 'get_inspections') {
        $status = $_GET['status'] ?? '';
        $limit  = (int)($_GET['limit'] ?? 50);

        $sql = "SELECT i.*, u.full_name as customer_name, u.phone as customer_phone,
                       ins.full_name as inspector_name, it.name as inspection_type_name
                FROM inspections i
                LEFT JOIN users u   ON i.user_id           = u.id
                LEFT JOIN users ins ON i.inspector_id      = ins.id
                LEFT JOIN inspection_types it ON i.inspection_type_id = it.id
                WHERE 1=1";

        $params = [];

        if ($currentUser['role'] === 'inspector') {
            $sql .= " AND i.inspector_id = :user_id";
            $params[':user_id'] = $currentUser['id'];
        } elseif ($currentUser['role'] === 'supervisor' && $currentUser['assigned_region']) {
            // ✅ إصلاح — الجدول هو inspections ويحتوي على "region" وليس "assigned_region"
            $sql .= " AND i.region = :region";
            $params[':region'] = $currentUser['assigned_region'];
        }

        if ($status && $status !== 'all') {
            $sql .= " AND i.status = :status";
            $params[':status'] = $status;
        }

        $sql .= " ORDER BY i.created_at DESC LIMIT :limit";

        $stmt = $pdo->prepare($sql);
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->execute();

        sendResponse(true, 'تم جلب الفحوصات بنجاح', $stmt->fetchAll());
    }

    // ============================================
    // 15. تحديث حالة الفحص
    // ============================================
    if ($action === 'update_inspection_status') {
        if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
        validateRequiredFields($data, ['id', 'status']);

        if (!checkPermission($currentUser, ['admin', 'supervisor', 'inspector'])) {
            sendResponse(false, 'غير مصرح بالوصول', null, 403);
        }

        if ($currentUser['role'] === 'supervisor') {
            $stmt = $pdo->prepare("SELECT region FROM inspections WHERE id = ?");
            $stmt->execute([$data['id']]);
            $inspection = $stmt->fetch();
            if ($inspection && !checkRegionAccess($currentUser, $inspection['region'])) {
                sendResponse(false, 'غير مصرح بالوصول لهذه المنطقة', null, 403);
            }
        }

        $stmt = $pdo->prepare("UPDATE inspections SET status = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$data['status'], $data['id']]);

        logActivity($pdo, $currentUser['id'], 'update_inspection_status', "تحديث حالة الفحص ID: {$data['id']} إلى {$data['status']}");
        sendResponse(true, 'تم تحديث حالة الفحص بنجاح');
    }

    // ============================================
    // 16. تعيين فاحص للفحص
    // ============================================
    if ($action === 'assign_inspector') {
        if ($method !== 'POST') sendResponse(false, 'Method not allowed', null, 405);
        validateRequiredFields($data, ['inspection_id', 'inspector_id']);

        if (!checkPermission($currentUser, ['admin', 'supervisor'])) {
            sendResponse(false, 'غير مصرح بالوصول', null, 403);
        }

        if ($currentUser['role'] === 'supervisor') {
            $stmt = $pdo->prepare("SELECT region FROM inspections WHERE id = ?");
            $stmt->execute([$data['inspection_id']]);
            $inspection = $stmt->fetch();
            if ($inspection && !checkRegionAccess($currentUser, $inspection['region'])) {
                sendResponse(false, 'غير مصرح بالوصول لهذه المنطقة', null, 403);
            }

            $stmt = $pdo->prepare("SELECT assigned_region FROM users WHERE id = ?");
            $stmt->execute([$data['inspector_id']]);
            $inspector = $stmt->fetch();
            if ($inspector && $inspector['assigned_region'] !== $currentUser['assigned_region']) {
                sendResponse(false, 'لا يمكن تعيين فاحص من منطقة مختلفة', null, 403);
            }
        }

        $stmt = $pdo->prepare("
            UPDATE inspections
            SET inspector_id = ?, assigned_by = ?, assigned_at = NOW(), status = 'assigned', updated_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$data['inspector_id'], $currentUser['id'], $data['inspection_id']]);

        logActivity($pdo, $currentUser['id'], 'assign_inspector', "تعيين فاحص ID: {$data['inspector_id']} للفحص ID: {$data['inspection_id']}");
        sendResponse(true, 'تم تعيين الفاحص بنجاح');
    }

    // ============================================
    // 17. جلب المراكز
    // ============================================
    if ($action === 'get_centers') {
        $regionFilter = '';
        $params       = [];

        if (!checkPermission($currentUser, 'admin') && $currentUser['assigned_region']) {
            $regionFilter      = " WHERE region = :region";
            $params[':region'] = $currentUser['assigned_region'];
        }

        $sql  = "SELECT id, name, address, phone, email, status, region FROM centers $regionFilter ORDER BY name";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        sendResponse(true, 'تم جلب المراكز بنجاح', $stmt->fetchAll());
    }

    // ============================================
    // 18. جلب الأنشطة
    // ============================================
    if ($action === 'get_activities') {
        $limit = (int)($_GET['limit'] ?? 50);

        $sql = "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 :limit";

        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
        $stmt->execute();

        $activities = $stmt->fetchAll();
        foreach ($activities as &$activity) {
            $activity['action']  = sanitizeInput($activity['action']  ?? '');
            $activity['details'] = sanitizeInput($activity['details'] ?? '');
        }

        sendResponse(true, 'تم جلب الأنشطة بنجاح', $activities);
    }

    // ============================================
    // الإجراء غير الموجود
    // ============================================
    else {
        sendResponse(false, 'الإجراء المطلوب غير موجود', [
            'available_actions' => [
                'login', 'verify_token', 'logout',
                'get_dashboard_stats', 'get_pending_inspections', 'get_available_inspectors',
                'get_users', 'get_inspectors', 'get_clients',
                'get_inspections', 'update_inspection_status', 'assign_inspector',
                'add_user', 'update_user', 'delete_user', 'update_user_status',
                'get_centers', 'get_activities'
            ]
        ], 400);
    }

} catch (PDOException $e) {
    error_log('Database error: ' . $e->getMessage());
    sendResponse(false, 'حدث خطأ في قاعدة البيانات', null, 500);
} catch (Exception $e) {
    error_log('Server error: ' . $e->getMessage());
    sendResponse(false, 'حدث خطأ في الخادم', null, 500);
}
?>
