<?php
/**
 * API: تسجيل مشرف فني - Auto Tester
 */

error_reporting(0);
ini_set('display_errors', 0);

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";

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

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

    if (!$input) {
        throw new Exception("لم يتم استلام بيانات صالحة");
    }

    // توليد رقم الطلب
    $requestNumber = 'SUP-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));

    // معالجة الملفات المرفوعة (Base64)
    $photoPath = !empty($input['photo']) ? saveBase64File($input['photo'], 'sup_photo') : null;
    $cvPath = !empty($input['cv']) ? saveBase64File($input['cv'], 'sup_cv') : null;
    $idPath = !empty($input['idCard']) ? saveBase64File($input['idCard'], 'sup_id') : null;

    // معالجة مصفوفة الشهادات الفنية
    $certsPaths = [];
    if (!empty($input['certificates']) && is_array($input['certificates'])) {
        foreach ($input['certificates'] as $index => $base64) {
            $path = saveBase64File($base64, 'sup_cert_' . ($index + 1));
            if ($path) $certsPaths[] = $path;
        }
    }

    $sql = "INSERT INTO `supervisors_requests` (
        `request_number`, `full_name`, `email`, `phone`, `governorate`, 
        `city`, `address`, `birth_date`, `gender`, `marital_status`,
        `specialty`, `experience_years`, `current_job`, `education`, `expected_salary`,
        `photo_file`, `cv_file`, `id_file`, `tech_certs`
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $requestNumber, $input['fullName'], $input['email'], $input['phone'], $input['governorate'],
        $input['city'], $input['address'], $input['birthDate'], $input['gender'], $input['maritalStatus'],
        $input['specialty'], $input['experienceYears'], $input['currentJob'], $input['education'], $input['expectedSalary'],
        $photoPath, $cvPath, $idPath, json_encode($certsPaths, JSON_UNESCAPED_UNICODE)
    ]);

    echo json_encode([
        'success' => true,
        'message' => 'تم استلام طلب التوظيف بنجاح',
        'data' => [
            'full_name' => $input['fullName'],
            'request_number' => $requestNumber
        ]
    ], JSON_UNESCAPED_UNICODE);

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

function saveBase64File($base64Data, $prefix) {
    if (empty($base64Data) || !strpos($base64Data, ',')) return null;
    try {
        $parts = explode(',', $base64Data);
        $fileData = base64_decode($parts[1]);
        $ext = (strpos($parts[0], 'pdf') !== false) ? 'pdf' : 'jpg';
        $filename = $prefix . '_' . time() . '_' . rand(100, 999) . '.' . $ext;
        $uploadDir = __DIR__ . '/../../../uploads/supervisors/'; 
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
        file_put_contents($uploadDir . $filename, $fileData);
        return 'uploads/supervisors/' . $filename;
    } catch (Exception $e) { return null; }
}