<?php
// api/create-job-application.php
header('Content-Type: application/json');
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->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ في الاتصال بقاعدة البيانات']);
    exit;
}

// استقبال البيانات
$input = file_get_contents('php://input');
$data = json_decode($input, true);

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

// التحقق من البيانات المطلوبة
$required = ['fullName', 'email', 'phone', 'jobRole', 'governorate'];
foreach ($required as $field) {
    if (empty($data[$field])) {
        echo json_encode(['success' => false, 'message' => 'جميع الحقول المطلوبة يجب ملؤها']);
        exit;
    }
}

try {
    // التحقق من عدم تكرار الطلب
    $check = $pdo->prepare("SELECT id FROM job_applications WHERE email = ? AND status = 'pending'");
    $check->execute([$data['email']]);
    
    if ($check->fetch()) {
        echo json_encode(['success' => false, 'message' => 'لديك طلب قيد الانتظار بالفعل']);
        exit;
    }
    
    // إدراج طلب التوظيف
    $stmt = $pdo->prepare("
        INSERT INTO job_applications (full_name, email, phone, job_role, years_experience, qualification, skills, governorate, city, status, created_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
    ");
    
    $stmt->execute([
        $data['fullName'],
        $data['email'],
        $data['phone'],
        $data['jobRole'],
        $data['yearsExperience'] ?? null,
        $data['qualification'] ?? null,
        $data['skills'] ?? null,
        $data['governorate'],
        $data['city'] ?? null
    ]);
    
    $applicationId = $pdo->lastInsertId();
    
    echo json_encode([
        'success' => true,
        'message' => 'تم إرسال طلب التوظيف بنجاح',
        'applicationId' => $applicationId
    ]);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>