<?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/stundennachweis.php');
    exit;
}

$back    = '../pages/stundennachweis.php';
$monat_m = trim($_POST['monat_m'] ?? '');
$monat_j = trim($_POST['monat_j'] ?? '');

if (!preg_match('/^\d{2}$/', $monat_m) || !preg_match('/^\d{4}$/', $monat_j)
    || (int)$monat_m < 1 || (int)$monat_m > 12
    || (int)$monat_j < 2020 || (int)$monat_j > 2099) {
    redirect_error($back, 'Bitte einen gültigen Monat und ein gültiges Jahr auswählen.');
}
$monat = $monat_j . '-' . $monat_m;

$dir = dirname(__DIR__) . '/uploads/';
$up  = handle_upload($_FILES['datei'] ?? [], [
    'allowed'  => UPLOAD_TYPES_PDF_IMG,
    'dir'      => $dir,
    'prefix'   => 'stundennachweis',
    'messages' => [
        'missing' => 'Bitte eine Datei hochladen.',
        'ext'     => 'Dateityp nicht erlaubt. Erlaubt: PDF, JPG, PNG.',
    ],
]);
if (!$up['ok']) {
    redirect_error($back, $up['error']);
}

$safe_name     = $up['filename'];
$original_name = $up['original_name'];
$mime          = $up['mime'];

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

db()->prepare(
    'INSERT INTO requests_stundennachweis
        (user_id, status, admin_note, monat, filename, original_name, created_at, updated_at)
     VALUES (?, \'pending\', \'\', ?, ?, ?, ?, ?)'
)->execute([$user_id, $monat, $safe_name, $original_name, $now, $now]);

$config      = require __DIR__ . '/../lib/config.php';
smtp_send(
    $config,
    $config['mail_sabrina'],
    'Neuer Stundennachweis: ' . current_name(),
    "Ein Stundennachweis wurde hochgeladen.\n\n"
        . 'Mitarbeiter: ' . current_name() . "\n"
        . 'Monat: ' . $monat . "\n"
        . 'Datei: ' . $original_name . "\n\n"
        . "---\nGesendet über OMSORG Connect",
    ['path' => $dir . $safe_name, 'name' => $original_name, 'mime' => $mime]
);

redirect_ok($back);
