<?php
// api/get-inspector-details.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

$host = 'localhost';
$dbname = 'digitals_autotester_db';
$username = 'digitals';
$password = 'bassam.bassam';

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ في الاتصال بقاعدة البيانات']);
    exit;
}

$userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

if (!$userId) {
    echo json_encode(['success' => false, 'message' => 'معرف المستخدم مطلوب']);
    exit;
}

try {
    // التحقق من وجود جدول inspectors
    $checkTable = $pdo->query("SHOW TABLES LIKE 'inspectors'");
    $hasInspectorsTable = $checkTable->rowCount() > 0;
    
    if ($hasInspectorsTable) {
        $stmt = $pdo->prepare("SELECT * FROM inspectors WHERE user_id = ?");
        $stmt->execute([$userId]);
        $inspector = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($inspector) {
            echo json_encode(['success' => true, 'data' => $inspector]);
        } else {
            echo json_encode(['success' => true, 'data' => null]);
        }
    } else {
        echo json_encode(['success' => true, 'data' => null]);
    }
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>