<?php
session_start();

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

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

foreach ($users as $index => $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();

    $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: /admin/dashboard.php');
    exit;
}

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