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

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

verify_csrf();

$back    = '../pages/admin.php?tab=einsatzanweisung';
$action  = $_POST['_action'] ?? '';
$user_id = (int)($_POST['target_user_id'] ?? 0);

if ($user_id <= 0) {
    header('Location: ' . $back . '&err=' . urlencode('Ungültiger Nutzer.'));
    exit;
}

$stmt = db()->prepare('SELECT id FROM users WHERE id = ?');
$stmt->execute([$user_id]);
if (!$stmt->fetch()) {
    header('Location: ' . $back . '&err=' . urlencode('Nutzer nicht gefunden.'));
    exit;
}

if ($action === 'update_ort') {
    $ort = trim($_POST['ort'] ?? '');

    db()->prepare(
        'INSERT INTO einsatzanweisung (user_id, ort)
         VALUES (?, ?)
         ON CONFLICT(user_id) DO UPDATE SET ort = excluded.ort'
    )->execute([$user_id, $ort]);

    header('Location: ' . $back . '&ok=' . urlencode('Einsatzort gespeichert.'));
    exit;
}

if ($action === 'upload_pdf') {
    $stmt = db()->prepare('SELECT u.username, e.filename AS old_filename FROM users u LEFT JOIN einsatzanweisung e ON e.user_id = u.id WHERE u.id = ?');
    $stmt->execute([$user_id]);
    $row = $stmt->fetch();

    $dir = dirname(__DIR__) . '/uploads/';
    $up  = handle_upload($_FILES['pdf'] ?? [], [
        'allowed'  => UPLOAD_TYPES_PDF,
        'dir'      => $dir,
        'prefix'   => 'einsatzanweisung',
        'username' => $row['username'],
        'messages' => [
            'missing' => 'Bitte eine PDF-Datei auswählen.',
            'upload'  => 'Fehler beim Hochladen.',
            'ext'     => 'Nur PDF-Dateien erlaubt.',
            'mime'    => 'Nur PDF-Dateien erlaubt.',
            'size'    => 'Datei ist zu groß (max. 12 MB).',
            'move'    => 'Fehler beim Speichern der Datei.',
        ],
    ]);
    if (!$up['ok']) {
        header('Location: ' . $back . '&err=' . urlencode($up['error']));
        exit;
    }

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

    if (!empty($row['old_filename'])) {
        $old_path = $dir . basename($row['old_filename']);
        if (is_file($old_path)) {
            unlink($old_path);
        }
    }

    $now = date('c');
    db()->prepare(
        'INSERT INTO einsatzanweisung (user_id, filename, original_name, uploaded_at)
         VALUES (?, ?, ?, ?)
         ON CONFLICT(user_id) DO UPDATE SET
           filename      = excluded.filename,
           original_name = excluded.original_name,
           uploaded_at   = excluded.uploaded_at'
    )->execute([$user_id, $safe_name, $original_name, $now]);

    header('Location: ' . $back . '&ok=' . urlencode('PDF erfolgreich hochgeladen.'));
    exit;
}

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