<?php
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/functions.php';

function login($username, $password) {
    $user = fetch("SELECT * FROM users WHERE username = ? OR email = ?", [$username, $username]);
    
    if ($user && password_verify($password, $user['password'])) {
        if (isset($user['is_active']) && $user['is_active'] == 0) {
            return 'inactive';
        }
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['user_role'] = $user['role'];
        $_SESSION['company_id'] = $user['company_id'];
        logAudit('LOGIN', 'User logged into the system');
        return true;
    }
    return false;
}

function logout() {
    logAudit('LOGOUT', 'User logged out of the system');
    session_destroy();
    header("Location: " . url('login'));
    exit;
}

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

function requireLogin() {
    if (!isLoggedIn()) {
        header("Location: " . url('login'));
        exit;
    }
}

function hasRole($roles) {
    if (!isLoggedIn()) return false;
    if (is_string($roles)) $roles = [$roles];
    $userRole = strtolower(trim($_SESSION['user_role']));
    $roles = array_map(function($r) { return strtolower(trim($r)); }, $roles);
    return in_array($userRole, $roles);
}

function requireRole($roles) {
    requireLogin();
    if (!hasRole($roles)) {
        header("Location: " . url('dashboard', ['error' => 'unauthorized']));
        exit;
    }
}

function getCurrentUser() {
    if (!isLoggedIn()) return null;
    return fetch("SELECT * FROM users WHERE id = ?", [$_SESSION['user_id']]);
}
