<?php
session_start();
require_once '../../../config/database.php';
header('Content-Type: application/json');

// التحقق من صلاحيات المدير
if (!isset($_SESSION['user_role']) || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'supervisor')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'غير مصرح']);
    exit;
}

try {
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
    $stmt = $pdo->query("
        SELECT
            ir.id,
            ir.request_number,
            CONCAT(u.first_name, ' ', u.last_name) as customer_name,
            u.phone as customer_phone,
            ir.vehicle_type,
            ir.vehicle_model,
            ir.inspection_type,
            ir.status,
            ir.created_at
        FROM inspection_requests_new ir
        JOIN users u ON ir.user_id = u.id
        ORDER BY ir.created_at DESC
        LIMIT $limit
    ");
    $inspections = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'data' => $inspections
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'خطأ في الخادم: ' . $e->getMessage()]);
}
?>