<?php
session_start();

require_once __DIR__ . '/../includes/auth_paths.php';

$config = ah_load_auth_config();
$users = ah_load_users();
$username = trim((string)($_POST['username'] ?? ''));
$password = (string)($_POST['password'] ?? '');
$isLocal = ah_is_local_env();

$tempEnabled = $isLocal && (($config['temp_local_login'] ?? true) !== false);
$tempUser = (string)($config['temp_local_username'] ?? 'admin');
$tempPass = (string)($config['temp_local_password'] ?? 'temp123');
$tempRole = (string)($config['temp_local_role'] ?? 'admin');
$tempPerms = $config['temp_local_permissions'] ?? ['all' => 'full'];
if (!is_array($tempPerms)) {
    $tempPerms = ['all' => 'full'];
}

if ($tempEnabled && hash_equals($tempUser, $username) && hash_equals($tempPass, $password)) {
    $_SESSION['username'] = $tempUser;
    $_SESSION['user'] = $tempUser;
    $_SESSION['role'] = $tempRole;
    $_SESSION['permissions'] = $tempPerms;
    $_SESSION['last_activity'] = time();
    $_SESSION['local_override_login'] = true;

    header('Location: /admin/dashboard.php');
    exit;
}

foreach ($users as $user) {
    if (!is_array($user)) {
        continue;
    }

    $user = ah_normalize_user_record($user);
    if (($user['username'] ?? '') !== $username) {
        continue;
    }

    if (!ah_verify_password($password, $user['password'] ?? '')) {
        continue;
    }

    $_SESSION['username'] = $user['username'];
    $_SESSION['user'] = $user['username'];
    $_SESSION['role'] = $user['role'];
    $_SESSION['permissions'] = $user['permissions'];
    $_SESSION['last_activity'] = time();
    unset($_SESSION['local_override_login']);

    if (password_get_info((string)($user['password'] ?? ''))['algo'] === 0) {
        $needsSave = false;
        foreach ($users as &$rewriteUser) {
            if (is_array($rewriteUser) && ($rewriteUser['username'] ?? '') === $username) {
                $rewriteUser['password'] = password_hash($password, PASSWORD_DEFAULT);
                $needsSave = true;
                break;
            }
        }
        unset($rewriteUser);
        if ($needsSave) {
            ah_save_users($users);
        }
    }

    header('Location: /admin/dashboard.php');
    exit;
}

$_SESSION['login_error'] = 'Invalid login.';
header('Location: index.php');
exit;
