<?php

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

/**
 * Retrieve the active profile based on the session data.
 *
 * This function checks if the session contains 'activeProfileType' and
 * 'activeProfileId'. If both are present, it attempts to find and return
 * the profile using the specified type and ID. If either is missing,
 * it returns null.
 *
 * @return mixed|null The active profile object if found, otherwise null.
 */
if (!function_exists('getActiveProfile')) {
    function getActiveProfile()
    {
        $profileType = Session::get('activeProfileType');
        $profileId = Session::get('activeProfileId');

        if ($profileType && $profileId) {
            return $profileType::find($profileId);
        }

        return null;
    }
}

if (!function_exists('getActiveProfileType')) {
    function getActiveProfileType()
    {
        $profileType = Session::get('activeProfileType');
        $profileTypeName = class_basename($profileType);

        if ($profileType && $profileTypeName) {
            return $profileTypeName;
        }

        return null;
    }
}

/**
 * Check if the currently authenticated web user can create payments as the active profile.
 *
 * Users with the coordinator role (organization-coordinator / bank-coordinator) have
 * full profile access except payment execution. Only manager roles may pay.
 * User profiles are always allowed to pay.
 *
 * @return bool
 */
if (!function_exists('canActiveProfileCreatePayments')) {
    function canActiveProfileCreatePayments(): bool
    {
        $activeType = Session::get('activeProfileType');
        $activeId   = Session::get('activeProfileId');

        if (!$activeType || !$activeId) {
            return false;
        }

        // User profiles can always pay
        if ($activeType === 'App\Models\User') {
            return true;
        }

        $user = Auth::guard('web')->user();
        if (!$user) {
            return false;
        }

        $managerRoles = [
            'App\Models\Organization' => "Organization\\{$activeId}\\organization-manager",
            'App\Models\Bank'         => "Bank\\{$activeId}\\bank-manager",
        ];

        if (!isset($managerRoles[$activeType])) {
            return false;
        }

        return $user->hasRole($managerRoles[$activeType]);
    }
}

/**
 * Check if the system is in maintenance mode.
 *
 * @return bool
 */
if (!function_exists('isMaintenanceMode')) {
    function isMaintenanceMode()
    {
        return \Illuminate\Support\Facades\Cache::remember('system_setting_maintenance_mode', 300, function () {
            $setting = \Illuminate\Support\Facades\DB::table('system_settings')
                ->where('key', 'maintenance_mode')
                ->first();
            return $setting ? $setting->value === 'true' : false;
        });
    }
}