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

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

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

$benefit   = trim($_POST['benefit']   ?? '');
$nachricht = trim($_POST['nachricht'] ?? '');

$allowed_benefits = ['yoga', 'autogenes_training', 'massage', 'tankgutschein', 'online_gutscheine'];
if (!in_array($benefit, $allowed_benefits, true)) {
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
        header('Content-Type: application/json');
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Bitte einen Benefit auswählen.']);
        exit;
    }
    header('Location: ' . $back . '?error=' . urlencode('Bitte einen Benefit auswählen.'));
    exit;
}

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

db()->prepare(
    'INSERT INTO requests_benefitsantrag (user_id, status, admin_note, created_at, updated_at, benefit, nachricht)
     VALUES (?, \'pending\', \'\', ?, ?, ?, ?)'
)->execute([$user_id, $now, $now, $benefit, $nachricht]);

$benefit_labels = [
    'yoga'               => 'Yoga',
    'autogenes_training' => 'Autogenes Training',
    'massage'            => 'Massage',
    'tankgutschein'      => 'Tankgutschein',
    'online_gutscheine'  => 'Online-Gutscheine',
];

$config = require __DIR__ . '/../lib/config.php';
smtp_send(
    $config,
    $config['mail_info'],
    'Neuer Benefitsantrag: ' . current_name(),
    "Ein Benefitsantrag wurde eingereicht.\n\n"
        . 'Mitarbeiter: ' . current_name() . "\n"
        . 'Benefit: ' . ($benefit_labels[$benefit] ?? $benefit) . "\n"
        . 'Nachricht: ' . ($nachricht ?: '—') . "\n\n"
        . "---\nGesendet über OMSORG Connect"
);

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
    header('Content-Type: application/json');
    echo json_encode(['ok' => true, 'benefit' => $benefit]);
    exit;
}

header('Location: ' . $back . '?success=1');
exit;
