<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
$u = require_superadmin();
$pdo = get_db();

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

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

$stmt = $pdo->prepare('SELECT * FROM applications WHERE id = ?');
$stmt->execute([$id]);
$app = $stmt->fetch(PDO::FETCH_ASSOC);

if ($app) {
    foreach (['cv_path', 'doc_path'] as $col) {
        if (!empty($app[$col])) {
            $p = UPLOAD_DIR . basename($app[$col]);
            if (is_file($p)) @unlink($p);
        }
    }
    $pdo->prepare('DELETE FROM applications WHERE id = ?')->execute([$id]);
}

header('Location: applicants.php?job_id=' . $jobId . '&msg=' . urlencode('Application deleted.'));
exit;
