<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckStoreSession
{
    public function handle(Request $request, Closure $next)
    {
        //route yg boleh tanpa session store
        $allowedRoutes = [
            'home.index',
            'logout.perform',
            'login.perform',
            'login',
            'change.store', // endpoint AJAX
            'reports.system_logs',
            'reports.system_errors',
        ];

        $allowedModules = [
            // User & Permission Management (Global)
            'permissions',
            'roles',
            'users', 
            
            // System Configuration (Global)
            'parameter_globals',
            
            // Master Data - Global (Reference Data)
            'stores',                   // Store management
            'raw_materials',            // Item master (global)
            'item_conversions',         // Conversion master (global)
            'menus',                    // Menu master (global)
            'range_dois',               // DOI range (global)
            'fstrs',                    // FSTR (global)
            'reason_adjustments',       // Reason adjustment (global)
            'sales_types',              // Sales type (global)
            'armada_types',             // Armada type (global)
            'periods',                  // Period (global)
            'holidays',                 // Holiday (global)
            'shipment_suppliers',       // Supplier (global)
            'shipment_deliveries',      // Delivery schedule (global)
            'numbering_formats',        // Numbering format (global)
            
            // Master Data - Mapping (Uses multi-store filtering)
            'store_raw_materials',      // Store-Item mapping (filtered by user's stores)
            'target_sisa_malam',        // Target sisa malam (filtered by user's stores)
            
            // QAD Integration (Global)
            'qad_sync',                 // QAD synchronization
            'forecasts'
        ];

        // if (!session()->has('store_selected') && !in_array($request->route()->getName(), $allowedRoutes)) {
        $routeName = $request->route()->getName();
        if (
            !session()->has('store_selected') &&
            !in_array($routeName, $allowedRoutes) &&
            !collect($allowedModules)->contains(fn($module) => str_contains($routeName, $module))
        ) {
            return redirect()->route('home.index')->with('info', 'Please select a store first !');
        }

        return $next($request);
    }
}
