<?php
require_once __DIR__ . '/../config.php';

session_name(SESSION_NAME);
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

function get_admin_username(): string
{
    require_once __DIR__ . '/db.php';
    ensure_default_settings();
    $user = setting('admin_username');
    return $user ?: ADMIN_USER;
}

function verify_admin_password(string $password): bool
{
    require_once __DIR__ . '/db.php';
    ensure_default_settings();
    $hash = setting('admin_password_hash');
    if (!$hash) {
        return $password === ADMIN_PASS;
    }
    return password_verify($password, $hash);
}

function is_logged_in(): bool
{
    return !empty($_SESSION['panel_logged_in']);
}

function require_login(): void
{
    if (!is_logged_in()) {
        header('Location: login.php');
        exit;
    }
}

function attempt_login(string $user, string $pass): bool
{
    if ($user === get_admin_username() && verify_admin_password($pass)) {
        $_SESSION['panel_logged_in'] = true;
        $_SESSION['panel_user'] = $user;
        return true;
    }
    return false;
}

function update_admin_credentials(string $currentPassword, string $newUsername, string $newPassword): void
{
    require_once __DIR__ . '/db.php';
    ensure_default_settings();

    if (!verify_admin_password($currentPassword)) {
        throw new RuntimeException('Senha atual incorreta.');
    }

    $newUsername = trim($newUsername);
    if ($newUsername === '') {
        throw new RuntimeException('Informe o novo usuário.');
    }
    if (strlen($newUsername) < 3) {
        throw new RuntimeException('Usuário deve ter pelo menos 3 caracteres.');
    }
    if (strlen($newPassword) < 6) {
        throw new RuntimeException('Nova senha deve ter pelo menos 6 caracteres.');
    }

    set_setting('admin_username', $newUsername);
    set_setting('admin_password_hash', password_hash($newPassword, PASSWORD_DEFAULT));
    $_SESSION['panel_user'] = $newUsername;
}

function logout(): void
{
    $_SESSION = [];
    session_destroy();
}
