<?php
session_start();
require_once __DIR__ . '/../includes/auth_paths.php';
$users = ah_load_users();
$username = trim((string)($_POST['username'] ?? ''));
$password = (string)($_POST['password'] ?? '');
$matched = false;
foreach ($users as $index => $user) {
    if (!is_array($user)) continue;
    $user = ah_normalize_user_record($user);
    if (($user['username'] ?? '') !== $username) continue;
    $matched = true;
    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();
    $needsSave = false;
    if (($user['role'] ?? '') === 'dj') {
        $users[$index]['role'] = 'viewer';
        $needsSave = true;
    }
    if (password_get_info((string)($user['password'] ?? ''))['algo'] === 0) {
        $users[$index]['password'] = password_hash($password, PASSWORD_DEFAULT);
        $needsSave = true;
    }
    if ($needsSave) {
        $users[$index] = array_merge($users[$index], [
            'role' => $_SESSION['role'],
            'permissions' => $_SESSION['permissions'],
        ]);
        ah_save_users($users);
    }
    header('Location: ' . ah_admin_dashboard_url());
    exit;
}
// local fallback so test installs are never locked out
if (!$matched && ah_is_local_env() && $username === 'admin' && $password === 'admin') {
    $_SESSION['username'] = 'admin';
    $_SESSION['user'] = 'admin';
    $_SESSION['role'] = 'master';
    $_SESSION['permissions'] = [];
    $_SESSION['last_activity'] = time();
    header('Location: ' . ah_admin_dashboard_url());
    exit;
}
$_SESSION['login_error'] = 'Invalid login.';
header('Location: ' . ah_login_url());
exit;
