<?php
// ============================================================
// Auth helpers - works with the EXISTING `users` table:
// id, username, password, role, department_id, must_change_password, can_add_staff
// ============================================================

function current_user() {
    return $_SESSION['user'] ?? null;
}

function is_logged_in() {
    return isset($_SESSION['user']);
}

function require_login() {
    if (!is_logged_in()) {
        header('Location: ' . BASE_URL . 'login.php');
        exit;
    }
    if (!empty($_SESSION['user']['must_change_password']) &&
        basename($_SERVER['PHP_SELF']) !== 'change_password.php') {
        header('Location: ' . BASE_URL . 'change_password.php');
        exit;
    }
}

// Roles allowed to fully administer master data & users
function is_admin_role($role = null) {
    $role = $role ?? (current_user()['role'] ?? null);
    return in_array($role, ['superadmin', 'admin']);
}

// Restrict a page to a set of roles. superadmin always passes.
function require_role(array $roles) {
    require_login();
    $role = current_user()['role'];
    if ($role === 'superadmin') return;
    if (!in_array($role, $roles)) {
        http_response_code(403);
        die('<div style="font-family:sans-serif;padding:40px">
              <h2>403 - Access Denied</h2>
              <p>Your role (' . htmlspecialchars($role) . ') does not have permission to view this page.</p>
              <a href="' . BASE_URL . 'dashboard.php">Back to dashboard</a>
             </div>');
    }
}

function login_attempt(PDO $pdo, $username, $password) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? LIMIT 1");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if (!$user) return false;

    // Support both password_hash() hashes and legacy plain-text (auto-upgrades on success)
    $valid = password_verify($password, $user['password']) || $password === $user['password'];
    if (!$valid) return false;

    if ($password === $user['password'] && strlen($user['password']) < 60) {
        // legacy plain text password - upgrade to a proper hash
        $newHash = password_hash($password, PASSWORD_DEFAULT);
        $upd = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
        $upd->execute([$newHash, $user['id']]);
    }

    unset($user['password']);
    $_SESSION['user'] = $user;
    return true;
}

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