<?php
/**
 * API: جلب طلبات التوظيف (فاحصين ومتدربين)
 * GET /api/admin/endpoints/get_job_applications.php
 */

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

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // جلب طلبات التوظيف من جدول job_applications
    $query = "SELECT 
                j.id,
                j.request_number,
                j.user_id,
                j.full_name,
                j.email,
                j.phone,
                j.governorate,
                j.city,
                j.address,
                j.job_role,
                j.years_experience,
                j.qualification,
                j.skills,
                j.specialization,
                j.certificates,
                j.expected_salary,
                j.available_from,
                j.photo_path,
                j.id_card_path,
                j.cv_path,
                j.license_path,
                j.status,
                j.created_at,
                u.username
              FROM job_applications j
              LEFT JOIN users u ON j.user_id = u.id
              ORDER BY 
                CASE WHEN j.status = 'pending' THEN 1 ELSE 2 END,
                j.created_at DESC";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $applications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $applications,
        'total' => count($applications),
        '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);
}
?>