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

// تشغيل عرض الأخطاء للتشخيص (يمكن إزالته بعد التأكد من العمل)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    // جلب المعاملات
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
    $inspector_id = isset($_GET['inspector_id']) ? (int)$_GET['inspector_id'] : null;
    $center_id = isset($_GET['center_id']) ? (int)$_GET['center_id'] : null;
    
    // بناء جملة SQL
    $sql = "SELECT 
                ir.id,
                ir.request_number,
                ir.created_at,
                ir.notes,
                CONCAT(u_insp.first_name, ' ', u_insp.last_name) as inspector_name,
                i.rating_avg as inspector_rating,
                ic.name as center_name,
                ic.id as center_id,
                CONCAT(u_cli.first_name, ' ', u_cli.last_name) as client_name,
                u_cli.phone as client_phone,
                CONCAT(cc.brand, ' ', cc.model, ' ', cc.year) as car_info,
                cc.plate_number,
                it.name as inspection_type
            FROM inspection_requests ir
            JOIN inspectors i ON ir.inspector_id = i.id
            JOIN users u_insp ON i.user_id = u_insp.id
            LEFT JOIN inspection_centers ic ON i.center_id = ic.id
            JOIN clients c ON ir.client_id = c.id
            JOIN users u_cli ON c.user_id = u_cli.id
            JOIN client_cars cc ON ir.car_id = cc.id
            JOIN inspection_types it ON ir.inspection_type_id = it.id
            WHERE ir.status = 'reviewed'";
    
    $params = [];
    
    if ($inspector_id) {
        $sql .= " AND ir.inspector_id = :inspector_id";
        $params['inspector_id'] = $inspector_id;
    }
    
    if ($center_id) {
        $sql .= " AND i.center_id = :center_id";
        $params['center_id'] = $center_id;
    }
    
    $sql .= " ORDER BY ir.created_at DESC LIMIT :limit";
    
    $stmt = $db->prepare($sql);
    
    foreach ($params as $key => $value) {
        $stmt->bindValue(":$key", $value);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    
    $stmt->execute();
    $inspections = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // تنسيق البيانات
    foreach ($inspections as &$inspection) {
        $inspection['inspector_rating'] = $inspection['inspector_rating'] ? round((float)$inspection['inspector_rating'], 1) : 0;
        $inspection['created_at'] = date('Y-m-d H:i:s', strtotime($inspection['created_at']));
    }
    
    echo json_encode([
        'success' => true,
        'data' => $inspections
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'خطأ في الخادم: ' . $e->getMessage()
    ]);
}
?>