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

check_role('alumno');

$user = get_logged_in_user();

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

if (!$student) {
    echo json_encode(['success' => false, 'message' => 'Student 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 = 'student'");
$stmt->execute([$job_id, $student['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 (?, ?, 'student')");
    if ($stmt->execute([$job_id, $student['id']])) {
        echo json_encode(['success' => true, 'message' => 'Solicitud enviada exitosamente.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'No se pudo aplicar.']);
    }
}
?>