<?php
require_once __DIR__ . '/career/includes/db.php';
require_once __DIR__ . '/career/includes/functions.php';

function back_with_error(string $msg, int $jobId) {
    header('Location: job.php?id=' . $jobId . '&error=' . urlencode($msg));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die('Method not allowed.');
}

$jobId = (int)($_POST['job_id'] ?? 0);
$pdo = get_db();

$stmt = $pdo->prepare("SELECT * FROM jobs WHERE id = ? AND status = 'published'");
$stmt->execute([$jobId]);
$job = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$job) {
    http_response_code(404);
    die('This job posting is no longer available.');
}

if (is_job_expired($job['deadline'])) {
    back_with_error('The application deadline for this position has passed.', $jobId);
}

// Honeypot
if (!empty($_POST['website'])) {
    header('Location: job.php?id=' . $jobId . '&applied=1');
    exit;
}

// Rate limiting — max 5 applications per IP per hour
$rlDir = __DIR__ . '/career/data/rl_cache/';
if (!is_dir($rlDir)) mkdir($rlDir, 0755, true);
$ip = preg_replace('/[^0-9a-fA-F:.]/', '', $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
$rlFile = $rlDir . md5($ip) . '.json';
$now = time();
$attempts = [];
if (file_exists($rlFile)) {
    $saved = json_decode(file_get_contents($rlFile), true) ?? [];
    $attempts = array_values(array_filter($saved, fn($t) => ($now - $t) < 3600));
}
if (count($attempts) >= 5) {
    back_with_error('Too many submissions from this connection. Please try again later.', $jobId);
}

$name = trim($_POST['applicant_name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$coverNote = trim($_POST['cover_note'] ?? '');

if ($name === '' || $email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    back_with_error('Please provide a valid name and email address.', $jobId);
}
if ($coverNote === '') {
    back_with_error('Please write a short cover note — it helps us review your application.', $jobId);
}
$coverWordCount = count(array_filter(preg_split('/\s+/', $coverNote)));
if ($coverWordCount > 200) {
    back_with_error('Your cover note is too long — please keep it to 200 words or fewer.', $jobId);
}

try {
    [$cvPath, $cvOrig] = handle_upload('cv', true);
    [$docPath, $docOrig] = handle_upload('other_doc', false);
} catch (Exception $e) {
    back_with_error($e->getMessage(), $jobId);
    exit;
}

$stmt = $pdo->prepare('INSERT INTO applications
    (job_id, applicant_name, email, phone, cover_note, cv_path, cv_original_name, doc_path, doc_original_name, ip_address)
    VALUES (?,?,?,?,?,?,?,?,?,?)');
$stmt->execute([$jobId, $name, $email, $phone, $coverNote, $cvPath, $cvOrig, $docPath, $docOrig, $ip]);

$attempts[] = $now;
file_put_contents($rlFile, json_encode($attempts));

header('Location: job.php?id=' . $jobId . '&applied=1');
exit;
