<?php
// includes/auth.php — Autentikasi sederhana berbasis session
// Default: username=admin, password=admin123 (ubah di Settings)

function isLoggedIn(): bool {
    return isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true;
}

function login(string $username, string $password): bool {
    $adminUser = getConfig('admin_user', 'admin');
    $adminPass = getConfig('admin_pass', '');

    // Default password jika belum dikonfigurasi
    if (empty($adminPass)) {
        $adminPass = 'admin123';
    }

    if ($username === $adminUser && $password === $adminPass) {
        $_SESSION['logged_in'] = true;
        $_SESSION['user'] = ['name' => $username, 'role' => 'admin'];
        $_SESSION['login_time'] = time();
        writeLog("Login berhasil: $username dari " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
        return true;
    }
    writeLog("Login gagal: $username dari " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'), 'warn');
    return false;
}

function getCurrentUser(): array {
    return $_SESSION['user'] ?? ['name' => 'Admin', 'role' => 'admin'];
}

function requireAdmin(): void {
    if (!isLoggedIn()) {
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        exit;
    }
}
