<?php
/**
 * جلب الفحوصات المنتظرة للمراجعة
 * المسار: /api/supervisor/endpoints/get_review_inspections.php
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once '../../config/database.php';

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    echo json_encode([
        'success' => false, 
        'message' => 'Database connection failed'
    ]);
    exit();
}

try {
    $query = "SELECT ir.*, i.full_name as inspector_name, i.center_name 
              FROM inspection_requests ir
              LEFT JOIN inspectors i ON ir.inspector_id = i.id
              WHERE ir.status = 'pending_approval' OR ir.status = 'pending'
              ORDER BY ir.created_at DESC";
    
    $stmt = $db->prepare($query);
    $stmt->execute();
    $inspections = $stmt->fetchAll();
    
    // تنسيق البيانات
    foreach ($inspections as &$insp) {
        $insp['inspection_type'] = $insp['service_name'];
        $insp['client_name'] = $insp['full_name'];
        $insp['client_phone'] = $insp['phone'];
        $insp['car_info'] = $insp['car_brand'] . ' ' . $insp['car_model'] . ' ' . $insp['car_year'];
        $insp['created_at_formatted'] = date('Y-m-d', strtotime($insp['created_at']));
    }
    
    echo json_encode([
        'success' => true,
        'data' => $inspections,
        'count' => count($inspections)
    ]);
    
} catch (PDOException $e) {
    error_log("Database Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred',
        'error' => $e->getMessage()
    ]);
}