<?php
session_start();
require_once('inc/config.inc.php');
require_once('inc/functions.inc.php');

$user = check_user();

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['id'])) {
    http_response_code(400);
    die('Bad request');
}

$id = (int)$_POST['id'];
$referer = $_POST['referer'] ?? 'urlaubsantrag.php';

// Fetch vacation to verify ownership
$stmt = $pdo->prepare("SELECT user_id, status FROM vacations WHERE id = ?");
$stmt->execute([$id]);
$vac = $stmt->fetch();

if (!$vac) {
    die('Urlaubseintrag nicht gefunden.');
}

$isAdmin = is_admin_user();

if (!$isAdmin && $vac['user_id'] != $_SESSION['userid']) {
    die('Zugriff verweigert.');
}

// Allow deletion for admins or owner
$del = $pdo->prepare("DELETE FROM vacations WHERE id = ?");
$del->execute([$id]);

header('Location: ' . $referer);
exit();

?>
