<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

require_once __DIR__ . '/../../database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    $status = $_GET['status'] ?? 'all';
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    
    $params = [];
    $where = "";
    
    if ($status !== 'all') {
        $where = "WHERE status = :status";
        $params['status'] = $status;
    }
    
    $query = "SELECT 
                id,
                first_name,
                last_name,
                email,
                phone,
                position,
                experience_years,
                status,
                applied_at as created_at
              FROM job_applications
              $where
              ORDER BY applied_at DESC
              LIMIT :limit";
    
    $stmt = $db->prepare($query);
    if ($status !== 'all') {
        $stmt->bindValue(':status', $status);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    
    $applications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // تنسيق الاسم الكامل
    foreach ($applications as &$app) {
        $app['full_name'] = $app['first_name'] . ' ' . $app['last_name'];
    }
    
    echo json_encode([
        'success' => true,
        'data' => $applications
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>