<?php
/**
 * API: تسجيل فاحص جديد - إصلاح خطأ undefined full_name
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, 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";

$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    echo json_encode(['success' => false, 'message' => 'بيانات فارغة'], JSON_UNESCAPED_UNICODE);
    exit();
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);

    // 1. التحقق من التكرار
    $check = $pdo->prepare("SELECT COUNT(*) FROM `inspectors_requests` WHERE `email` = ? OR `phone` = ?");
    $check->execute([$input['email'], $input['phone']]);
    if ($check->fetchColumn() > 0) {
        echo json_encode(['success' => false, 'message' => 'البريد أو الهاتف مسجل مسبقاً'], JSON_UNESCAPED_UNICODE);
        exit();
    }

    // 2. توليد البيانات وحفظ الملفات
    $requestNumber = 'INS-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
    $fullName = trim($input['fullName']); // حفظ الاسم في متغير لاستخدامه في الرد

    $sql = "INSERT INTO `inspectors_requests` (
        `request_number`, `full_name`, `email`, `phone`, `role`, 
        `specialty`, `experience_years`, `license_type`, `governorate`, `status`
    ) VALUES (
        :req_num, :name, :email, :phone, 'inspector', 
        :spec, :exp, :lic_type, :gov, 'pending'
    )";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':req_num'  => $requestNumber,
        ':name'     => $fullName,
        ':email'    => trim($input['email']),
        ':phone'    => trim($input['phone']),
        ':spec'     => $input['specialty'] ?? null,
        ':exp'      => (int)($input['experienceYears'] ?? 0),
        ':lic_type' => $input['licenseType'] ?? null,
        ':gov'      => $input['governorate']
    ]);

    // 3. الرد: يجب أن يحتوي الكائن 'data' على 'full_name' ليتعرف عليه الـ JavaScript
    echo json_encode([
        'success' => true,
        'message' => 'تم التسجيل بنجاح',
        'data' => [
            'full_name' => $fullName, // هذا السطر سيحل مشكلة undefined
            'request_number' => $requestNumber
        ]
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ: ' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
}