<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

require_once __DIR__ . '/../../database.php';

try {
    $db = Database::getInstance();
    $conn = $db->getConnection();
    
    if (!$conn) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    $status = $_GET['status'] ?? 'all';
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    
    $where = "";
    if ($status !== 'all') {
        $where = "WHERE ir.status = :status";
    }
    
    $query = "SELECT 
                ir.id,
                ir.request_number,
                ir.status,
                ir.created_at,
                ir.total_amount,
                CONCAT(u.first_name, ' ', u.last_name) as full_name,
                u.phone,
                cc.brand,
                cc.model,
                cc.year,
                it.name as inspection_name
              FROM inspection_requests ir
              JOIN clients c ON ir.client_id = c.id
              JOIN users u ON c.user_id = u.id
              JOIN client_cars cc ON ir.car_id = cc.id
              JOIN inspection_types it ON ir.inspection_type_id = it.id
              $where
              ORDER BY ir.created_at DESC
              LIMIT :limit";
    
    $stmt = $conn->prepare($query);
    if ($status !== 'all') {
        $stmt->bindValue(':status', $status);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    
    $requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $requests
    ], JSON_UNESCAPED_UNICODE);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>