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

$ajax = !empty($_POST['_ajax']);

function ajax_error(string $msg): never {
    header('Content-Type: application/json');
    echo json_encode(['ok' => false, 'error' => $msg]);
    exit;
}
function ajax_ok(): never {
    header('Content-Type: application/json');
    echo json_encode(['ok' => true]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    if ($ajax) ajax_error('Ungültige Anfrage.');
    header('Location: ../pages/dienstplan.php'); exit;
}

$user_id = current_user()['id'];
$year    = (int)($_POST['year']  ?? 0);
$month   = (int)($_POST['month'] ?? 0);

if ($year < 2020 || $year > 2099 || $month < 1 || $month > 12) {
    if ($ajax) ajax_error('Ungültiger Monat.');
    header('Location: ../pages/dienstplan.php'); exit;
}

$back       = '../pages/dienstplan.php?year=' . $year . '&month=' . $month;
$month_str  = sprintf('%04d-%02d', $year, $month);
$schicht_ok = ['frueh', 'spaet', 'nacht'];
$submitted  = $_POST['schicht'] ?? [];

if (!is_array($submitted)) {
    header('Location: ' . $back . '&saved=1'); exit;
}

$now = date('c');
db()->beginTransaction();
try {
    foreach ($submitted as $date => $schicht) {
        if (!is_string($date) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) continue;
        if (substr($date, 0, 7) !== $month_str) continue;
        [$y, $m, $d] = array_map('intval', explode('-', $date));
        if (!checkdate($m, $d, $y)) continue;

        if (in_array($schicht, $schicht_ok, true)) {
            db()->prepare(
                'INSERT INTO dienstplan (user_id, date, schicht, created_at, updated_at)
                 VALUES (?, ?, ?, ?, ?)
                 ON DUPLICATE KEY UPDATE schicht=VALUES(schicht), updated_at=VALUES(updated_at)'
            )->execute([$user_id, $date, $schicht, $now, $now]);
        } else {
            db()->prepare(
                'DELETE FROM dienstplan WHERE user_id = ? AND date = ?'
            )->execute([$user_id, $date]);
        }
    }
    db()->commit();
} catch (\PDOException $ex) {
    if (db()->inTransaction()) db()->rollBack();
    $msg = 'Datenbankfehler: ' . $ex->getMessage();
    if ($ajax) ajax_error($msg);
    header('Location: ' . $back . '&error=' . urlencode($msg));
    exit;
}

if ($ajax) ajax_ok();
header('Location: ' . $back . '&saved=1');
exit;
