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

$config     = _omsorgcore_config();
$token      = $_SESSION['omsorgcore_access_token'];
$action     = $_POST['action'] ?? '';
$employeeId = $_SESSION['omsorgcore_profile']['employeeId'] ?? null;

if ($action === 'profile') {
    $email   = trim($_POST['email'] ?? '');
    $telefon = trim($_POST['telefon'] ?? '');

    if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        header('Location: ../pages/settings.php?error=' . urlencode('Ungültige E-Mail-Adresse.'));
        exit;
    }

    if (!$employeeId) {
        header('Location: ../pages/settings.php?error=' . urlencode('Kein verknüpfter Mitarbeiter-Datensatz gefunden.'));
        exit;
    }

    $current = omsorgcore_employees_get($config, $token, $employeeId);
    if (!$current['ok']) {
        header('Location: ../pages/settings.php?error=' . urlencode('Profil konnte nicht geladen werden.'));
        exit;
    }

    $payload = $current['data'];
    $payload['email']       = $email;
    $payload['phoneNumber'] = $telefon;
    unset($payload['id']);

    $result = omsorgcore_employees_update($config, $token, $employeeId, $payload);
    if (!$result['ok']) {
        header('Location: ../pages/settings.php?error=' . urlencode('Profil konnte nicht gespeichert werden.'));
        exit;
    }

    _refresh_profile();
    header('Location: ../pages/settings.php?saved=1');
    exit;
}

if ($action === 'password') {
    $old    = $_POST['old_password'] ?? '';
    $new    = $_POST['new_password'] ?? '';
    $repeat = $_POST['new_password_repeat'] ?? '';

    if (mb_strlen($new) < 8) {
        header('Location: ../pages/settings.php?error=' . urlencode('Neues Passwort muss mindestens 8 Zeichen haben.'));
        exit;
    }
    if ($new !== $repeat) {
        header('Location: ../pages/settings.php?error=' . urlencode('Die neuen Passwörter stimmen nicht überein.'));
        exit;
    }

    $result = omsorgcore_change_password($config, $token, $old, $new);
    if (!$result['ok']) {
        $message = $result['status'] === 401 ? 'Aktuelles Passwort ist falsch.' : 'Passwort konnte nicht geändert werden.';
        header('Location: ../pages/settings.php?error=' . urlencode($message));
        exit;
    }

    // Serverseitig wurden alle Sessions widerrufen - neuer Login mit dem neuen Passwort ist nötig.
    _clear_omsorgcore_session();
    header('Location: ../index.php?pwchanged=1');
    exit;
}

header('Location: ../pages/settings.php');
exit;
