<?php
/**
 * API: جلب تفاصيل الفحص كاملة مع معلومات المركز والفاحص
 * GET /api/supervisor/endpoints/get_full_inspection_details.php?id=1
 */

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

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

// إعدادات الاتصال بقاعدة البيانات
$host = "localhost";
$dbname = "digitals_autotester_db";
$username = "digitals";
$password = "bassam.bassam";

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'معرف الفحص غير صالح']);
    exit;
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // جلب تفاصيل الفحص مع معلومات المركز والفاحص
    $query = "SELECT 
                ir.*,
                ic.center_name,
                ic.address as center_address,
                ic.region as center_region,
                ic.city as center_city,
                ic.phone as center_phone,
                ic.email as center_email,
                ic.manager_name,
                ic.capacity as center_capacity,
                ins.full_name as inspector_name,
                ins.phone as inspector_phone,
                ins.email as inspector_email,
                ins.specialization as inspector_specialization,
                ins.experience_years,
                ins.rating as inspector_rating,
                ins.status as inspector_status
              FROM inspection_requests_new ir
              LEFT JOIN inspection_centers ic ON ir.center_id = ic.id
              LEFT JOIN inspectors ins ON ir.inspector_id = ins.id
              WHERE ir.id = :id";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([':id' => $id]);
    $inspection = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$inspection) {
        echo json_encode(['success' => false, 'message' => 'الفحص غير موجود']);
        exit;
    }
    
    echo json_encode([
        'success' => true,
        'data' => $inspection,
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>