<?php
header('Content-Type: application/json');
session_start();

include_once __DIR__ . '/../../config/dbcon.php'; // PDO connection
include_once __DIR__ . '/../../helpers/api_helper.php';

if (!isset($_SESSION['user_id'])) {
    sendResponse(401, "Please login first.");
}

$data = json_decode(file_get_contents('php://input'), true);
$job_id = $data['job_id'];
$user_id = $_SESSION['user_id'];

try {
    // Check if already applied
    $stmt = $conn->prepare("SELECT 1 FROM applied_jobs WHERE user_id = :user_id AND job_id = :job_id LIMIT 1");
    $stmt->execute(['user_id' => $user_id, 'job_id' => $job_id]);

    if ($stmt->rowCount() > 0) {
        sendResponse(400, "You have already applied for this job.");
    }

    // Insert into applied_jobs
    $stmt = $conn->prepare("INSERT INTO applied_jobs (user_id, job_id) VALUES (:user_id, :job_id)");
    $stmt->execute(['user_id' => $user_id, 'job_id' => $job_id]);

    sendResponse(200, "Job application submitted successfully.");

} catch (PDOException $e) {
    sendResponse(500, "Database error: " . $e->getMessage());
}
