<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once '../includes/db.php';
require_once '../includes/auth.php';

check_role('egresado');

$user = get_logged_in_user();

// Get graduate
$stmt = $pdo->prepare("SELECT * FROM graduates WHERE user_id = ?");
$stmt->execute([$user['id']]);
$graduate = $stmt->fetch();

if (!$graduate) {
    echo json_encode(['success' => false, 'message' => 'Graduate profile not found.']);
    exit;
}

$job_id = $_GET['job_id'] ?? 0;

if (!$job_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid job ID.']);
    exit;
}

// Check if already applied
$stmt = $pdo->prepare("SELECT id FROM applications WHERE job_id = ? AND applicant_id = ? AND applicant_type = 'graduate'");
$stmt->execute([$job_id, $graduate['id']]);
$existing_application = $stmt->fetch();

if ($existing_application) {
    echo json_encode(['success' => false, 'message' => 'Ya has solicitado este trabajo.']);
} else {
    // Apply
    $stmt = $pdo->prepare("INSERT INTO applications (job_id, applicant_id, applicant_type) VALUES (?, ?, 'graduate')");
    if ($stmt->execute([$job_id, $graduate['id']])) {
        echo json_encode(['success' => true, 'message' => 'Solicitud enviada exitosamente.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'No se pudo aplicar.']);
    }
}
?>