<?php
session_start();

function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function getUserRole() {
    return $_SESSION['role'] ?? null;
}

function requireLogin() {
    if (!isLoggedIn()) {
        header("Location: /spk-komputer/login.php");
        exit;
    }
}

function requireRole($roles) {
    if (!is_array($roles)) {
        $roles = [$roles];
    }
    
    requireLogin();
    
    if (!in_array($_SESSION['role'], $roles)) {
        header("Location: /spk-komputer/403.php");
        exit;
    }
}

function login($username, $password) {
    $db = getDB();
    $stmt = $db->prepare("SELECT id, username, password, role FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['role'] = $user['role'];
        return true;
    }
    return false;
}

function logout() {
    session_destroy();
    header("Location: /spk-komputer/login.php");
    exit;
}