<?php
require_once __DIR__ . '/../lib/auth.php';
require_once __DIR__ . '/../lib/upload.php';
require_once __DIR__ . '/../lib/mail.php';
require_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../pages/urlaubsantrag.php');
    exit;
}

$back = '../pages/urlaubsantrag.php';

verify_csrf();

$von        = trim($_POST['von']        ?? '');
$bis        = trim($_POST['bis']        ?? '');
$vertretung = trim($_POST['vertretung'] ?? '');
$nachricht  = trim($_POST['nachricht']  ?? '');

if ($von === '' || $bis === '') {
    redirect_error($back, 'Von und Bis sind Pflichtfelder.');
}

if (!strtotime($von) || !strtotime($bis)) {
    redirect_error($back, 'Ungültiges Datum.');
}

if (strtotime($von) > strtotime($bis)) {
    redirect_error($back, 'Das Startdatum muss vor dem Enddatum liegen.');
}

$up = handle_upload($_FILES['datei'] ?? [], [
    'allowed'  => UPLOAD_TYPES_DOCS,
    'dir'      => dirname(__DIR__) . '/uploads/',
    'prefix'   => 'urlaubsantrag',
    'required' => false,
]);
if (!$up['ok']) {
    redirect_error($back, $up['error']);
}

$filename      = $up['filename'] ?? '';
$original_name = $up['original_name'] ?? '';
$mime          = $up['mime'] ?? null;

$user_id = current_user()['id'];
$now     = date('c');

db()->prepare(
    'INSERT INTO requests_urlaubsantrag (user_id, status, admin_note, created_at, updated_at, von, bis, vertretung, nachricht, filename, original_name)
     VALUES (?, \'pending\', \'\', ?, ?, ?, ?, ?, ?, ?, ?)'
)->execute([$user_id, $now, $now, $von, $bis, $vertretung, $nachricht, $filename, $original_name]);

$config = require __DIR__ . '/../lib/config.php';
$attach = ($filename !== '')
    ? ['path' => dirname(__DIR__) . '/uploads/' . $filename, 'name' => $original_name, 'mime' => $mime]
    : [];
smtp_send(
    $config,
    $config['mail_sabrina'],
    'Neuer Urlaubsantrag: ' . current_name(),
    "Ein Urlaubsantrag wurde eingereicht.\n\n"
        . 'Mitarbeiter: ' . current_name() . "\n"
        . 'Von: ' . $von . "\n"
        . 'Bis: ' . $bis . "\n"
        . 'Vertretung: ' . ($vertretung ?: '—') . "\n"
        . 'Nachricht: ' . ($nachricht ?: '—') . "\n\n"
        . "---\nGesendet über OMSORG Connect",
    $attach
);

redirect_ok($back);
