<?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'];
        
        if (!empty($user['company_id'])) {
            $company = fetch("SELECT enabled_modules, currency FROM companies WHERE id = ?", [$user['company_id']]);
            if ($company) {
                $_SESSION['company_modules'] = json_decode($company['enabled_modules'], true) ?: [];
                $_SESSION['company_currency'] = $company['currency'] ?: '$';
            } else {
                $_SESSION['company_modules'] = [];
                $_SESSION['company_currency'] = '$';
            }
        } else {
            $_SESSION['company_modules'] = [];
            $_SESSION['company_currency'] = '$';
        }

        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']]);
}

function isModuleEnabled($module_name) {
    if (hasRole('superadmin')) return true;
    
    static $global_inactive_modules = null;
    if ($global_inactive_modules === null) {
        try {
            $inactive = fetchAll("SELECT module_key FROM system_modules WHERE is_active = 0");
            $global_inactive_modules = $inactive ? array_column($inactive, 'module_key') : [];
        } catch (Exception $e) {
            $global_inactive_modules = [];
        }
    }
    
    if (in_array($module_name, $global_inactive_modules)) {
        return false;
    }
    
    static $cached_modules = null;
    if ($cached_modules === null) {
        $company_id = $_SESSION['company_id'] ?? null;
        if ($company_id) {
            $company = fetch("SELECT enabled_modules, currency FROM companies WHERE id = ?", [$company_id]);
            $cached_modules = ($company && $company['enabled_modules']) ? json_decode($company['enabled_modules'], true) : [];
            $_SESSION['company_modules'] = $cached_modules;
            $_SESSION['company_currency'] = ($company && $company['currency']) ? $company['currency'] : '$';
        } else {
            $cached_modules = [];
            $_SESSION['company_modules'] = [];
            $_SESSION['company_currency'] = '$';
        }
    }
    
    // Fallback for legacy mode: if enabled_modules is empty, allow 'dashboard' by default
    if (empty($cached_modules) && $module_name === 'dashboard') {
        return true;
    }
    
    return in_array($module_name, $cached_modules);
}

function requireModule($module_name) {
    if (!isModuleEnabled($module_name)) {
        header("Location: " . url('dashboard', ['error' => 'module_disabled']));
        exit;
    }
}
