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

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

$back       = '../pages/settings.php';
$user       = current_user();
$dir        = dirname(__DIR__) . '/assets/avatars/';
$config     = _omsorgcore_config();
$token      = $_SESSION['omsorgcore_access_token'];
$employeeId = $_SESSION['omsorgcore_profile']['employeeId'] ?? null;

function _set_avatar_file_name(array $config, string $token, string $employeeId, ?string $filename): bool {
    $current = omsorgcore_employees_get($config, $token, $employeeId);
    if (!$current['ok']) {
        return false;
    }
    $payload = $current['data'];
    $payload['avatarFileName'] = $filename;
    unset($payload['id']);

    $result = omsorgcore_employees_update($config, $token, $employeeId, $payload);
    if ($result['ok']) {
        _refresh_profile();
    }
    return $result['ok'];
}

if (!$employeeId) {
    redirect_error($back, 'Kein verknüpfter Mitarbeiter-Datensatz gefunden.');
}

// Remove avatar
if (!empty($_POST['remove_avatar'])) {
    if (!empty($user['avatar'])) {
        $old = $dir . basename($user['avatar']);
        if (is_file($old)) {
            unlink($old);
        }
    }
    _set_avatar_file_name($config, $token, $employeeId, null);
    redirect_ok($back, 'avatar_saved');
}

$up = handle_upload($_FILES['avatar'] ?? [], [
    'allowed'   => UPLOAD_TYPES_IMAGES,
    'dir'       => $dir,
    'naming'    => 'plain',
    'max_bytes' => 3 * 1024 * 1024,
    'messages'  => [
        'missing' => 'Bitte ein Bild auswählen.',
        'upload'  => 'Fehler beim Hochladen des Bildes.',
        'ext'     => 'Nur Bilder erlaubt (JPG, PNG, GIF, WebP).',
        'mime'    => 'Nur Bilder erlaubt (JPG, PNG, GIF, WebP).',
        'size'    => 'Bild ist zu groß (max. 3 MB).',
        'move'    => 'Fehler beim Speichern des Bildes.',
    ],
]);
if (!$up['ok']) {
    redirect_error($back, $up['error']);
}

$safe_name = $up['filename'];

// Delete old avatar after successful upload
if (!empty($user['avatar'])) {
    $old = $dir . basename($user['avatar']);
    if (is_file($old)) {
        unlink($old);
    }
}

_set_avatar_file_name($config, $token, $employeeId, $safe_name);

redirect_ok($back, 'avatar_saved');
