<?php

namespace App\Http\Middleware;

use App\Support\AppBasePath;
use App\Support\BranchScope;
use Database\Seeders\PermissionSeeder;
use Illuminate\Http\Request;
use Inertia\Middleware;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that's loaded on the first page visit.
     *
     * @see https://inertiajs.com/server-side-setup#root-template
     *
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determines the current asset version.
     *
     * @see https://inertiajs.com/asset-versioning
     */
    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    /**
     * Define the props that are shared by default.
     *
     * @see https://inertiajs.com/shared-data
     *
     * @return array<string, mixed>
     */
    public function share(Request $request): array
    {
        $rawLocale = (string) app()->getLocale();
        $uiLocale = str_starts_with(strtolower($rawLocale), 'fa') ? 'fa' : 'en';

        $user = $request->user();

        return [
            ...parent::share($request),
            'basePath' => AppBasePath::fromAppUrl(),
            'name' => config('app.name'),
            'locale' => $uiLocale,
            'direction' => $uiLocale === 'fa' ? 'rtl' : 'ltr',
            'status' => $request->session()->get('status'),
            'auth' => [
                'user' => $user,
                'canViewDashboard' => (bool) $user?->can('dashboard.view'),
                'isMasterAdmin' => BranchScope::isMasterAdmin($user),
                'canViewUsers' => (bool) $user?->can('users.view'),
                'canViewUserAudits' => (bool) $user?->can('users.audit'),
                'canViewLoginHistories' => (bool) $user?->can('users.login-history'),
                'canCreateUsers' => (bool) $user?->can('users.create'),
                'canManageUserPermissions' => (bool) $user?->can('users.update'),
                'canViewRoles' => (bool) $user?->can('roles.view'),
                'canCreateRoles' => (bool) $user?->can('roles.create'),
                'canUpdateRoles' => (bool) $user?->can('roles.update'),
                'canViewDesignations' => (bool) $user?->can('designations.view'),
                'canCreateDesignations' => (bool) $user?->can('designations.create'),
                'canUpdateDesignations' => (bool) $user?->can('designations.update'),
                'canDeleteDesignations' => (bool) $user?->can('designations.delete'),
                'canViewPermanentEmployees' => (bool) $user?->can('permanent-employees.view'),
                'canCreatePermanentEmployees' => (bool) $user?->can('permanent-employees.create'),
                'canUpdatePermanentEmployees' => (bool) $user?->can('permanent-employees.update'),
                'canViewPermanentSalaries' => (bool) $user?->can('permanent-salaries.view'),
                'canManagePermanentSalaries' => (bool) $user?->can('permanent-salaries.manage'),
                'canViewPermanentPunishments' => (bool) $user?->can('permanent-punishments.view'),
                'canCreatePermanentPunishments' => (bool) $user?->can('permanent-punishments.create'),
                'canUpdatePermanentPunishments' => (bool) $user?->can('permanent-punishments.update'),
                'canViewPermanentAdvances' => (bool) $user?->can('permanent-advances.view'),
                'canCreatePermanentAdvances' => (bool) $user?->can('permanent-advances.create'),
                'canUpdatePermanentAdvances' => (bool) $user?->can('permanent-advances.update'),
                'canViewTemporaryEmployees' => (bool) $user?->can('temporary-employees.view'),
                'canCreateTemporaryEmployees' => (bool) $user?->can('temporary-employees.create'),
                'canUpdateTemporaryEmployees' => (bool) $user?->can('temporary-employees.update'),
                'canViewTemporaryContracts' => (bool) $user?->can('temporary-contracts.view'),
                'canCreateTemporaryContracts' => (bool) $user?->can('temporary-contracts.create'),
                'canUpdateTemporaryContracts' => (bool) $user?->can('temporary-contracts.update'),
                'canPayTemporaryContracts' => (bool) $user?->can('temporary-contracts.pay'),
                'canViewAttendance' => (bool) $user?->can('attendance.view'),
                'canCreateAttendance' => (bool) $user?->can('attendance.create'),
                'canViewAttendanceDevices' => (bool) $user?->can('attendance-devices.view'),
                'canCreateAttendanceDevices' => (bool) $user?->can('attendance-devices.create'),
                'canUpdateAttendanceDevices' => (bool) $user?->can('attendance-devices.update'),
                'canViewAttendanceEnrollments' => (bool) $user?->can('attendance-enrollments.view'),
                'canCreateAttendanceEnrollments' => (bool) $user?->can('attendance-enrollments.create'),
                'canDeleteAttendanceEnrollments' => (bool) $user?->can('attendance-enrollments.delete'),
                'canViewAttendanceLeaves' => (bool) $user?->can('attendance-leaves.view'),
                'canCreateAttendanceLeaves' => (bool) $user?->can('attendance-leaves.create'),
                'canUpdateAttendanceLeaves' => (bool) $user?->can('attendance-leaves.update'),
                'canDeleteAttendanceLeaves' => (bool) $user?->can('attendance-leaves.delete'),
                'canAccessStaffManagement' => $user !== null && collect(PermissionSeeder::staffManagementPermissionNames())
                    ->contains(fn (string $permission): bool => $user->can($permission)),
                'canViewCustomers' => (bool) $user?->can('customers.view'),
                'canCreateCustomers' => (bool) $user?->can('customers.create'),
                'canUpdateCustomers' => (bool) $user?->can('customers.update'),
                'canViewCustomerPayments' => (bool) $user?->can('customer-payments.view'),
                'canCreateCustomerPayments' => (bool) $user?->can('customer-payments.create'),
                'canViewCustomerLedger' => (bool) $user?->can('customer-ledger.view'),
                'canViewCustomerLoans' => (bool) $user?->can('customer-loans.view'),
                'canCreateCustomerLoans' => (bool) $user?->can('customer-loans.create'),
                'canUpdateCustomerLoans' => (bool) $user?->can('customer-loans.update'),
                'canRepayCustomerLoans' => (bool) $user?->can('customer-loans.repay'),
                'canAccessCustomerManagement' => $user !== null && collect(PermissionSeeder::customerManagementPermissionNames())
                    ->contains(fn (string $permission): bool => $user->can($permission)),
                'canViewPurchaseUnits' => (bool) $user?->can('purchase-units.view'),
                'canCreatePurchaseUnits' => (bool) $user?->can('purchase-units.create'),
                'canUpdatePurchaseUnits' => (bool) $user?->can('purchase-units.update'),
                'canViewPurchaseProducts' => (bool) $user?->can('purchase-products.view'),
                'canCreatePurchaseProducts' => (bool) $user?->can('purchase-products.create'),
                'canUpdatePurchaseProducts' => (bool) $user?->can('purchase-products.update'),
                'canViewPurchases' => (bool) $user?->can('purchases.view'),
                'canCreatePurchases' => (bool) $user?->can('purchases.create'),
                'canUpdatePurchases' => (bool) $user?->can('purchases.update'),
                'canViewPurchaseSuppliers' => (bool) $user?->can('purchase-suppliers.view'),
                'canCreatePurchaseSuppliers' => (bool) $user?->can('purchase-suppliers.create'),
                'canUpdatePurchaseSuppliers' => (bool) $user?->can('purchase-suppliers.update'),
                'canViewSupplierPayments' => (bool) $user?->can('supplier-payments.view'),
                'canCreateSupplierPayments' => (bool) $user?->can('supplier-payments.create'),
                'canAccessPurchaseManagement' => $user !== null && collect(PermissionSeeder::purchaseManagementPermissionNames())
                    ->contains(fn (string $permission): bool => $user->can($permission)),
                'canViewFactoryUnits' => (bool) $user?->can('factory-units.view'),
                'canCreateFactoryUnits' => (bool) $user?->can('factory-units.create'),
                'canUpdateFactoryUnits' => (bool) $user?->can('factory-units.update'),
                'canViewFactoryProducts' => (bool) $user?->can('factory-products.view'),
                'canCreateFactoryProducts' => (bool) $user?->can('factory-products.create'),
                'canUpdateFactoryProducts' => (bool) $user?->can('factory-products.update'),
                'canViewProductionFormulas' => (bool) $user?->can('production-formulas.view'),
                'canCreateProductionFormulas' => (bool) $user?->can('production-formulas.create'),
                'canUpdateProductionFormulas' => (bool) $user?->can('production-formulas.update'),
                'canViewAllProductionFormulas' => $user !== null && $user->hasRole('Master Admin', 'web'),
                'canAccessFactoryManagement' => $user !== null && collect(PermissionSeeder::factoryManagementPermissionNames())
                    ->contains(fn (string $permission): bool => $user->can($permission)),
                'canViewCustomerOrders' => (bool) $user?->can('customer-orders.view'),
                'canCreateCustomerOrders' => (bool) $user?->can('customer-orders.create'),
                'canUpdateCustomerOrders' => (bool) $user?->can('customer-orders.update'),
                'canManageCustomerOrders' => (bool) ($user?->can('customer-orders.update') || $user?->can('customer-orders.create')),
                'canViewProductionOrders' => (bool) $user?->can('production-orders.view'),
                'canViewDoughUsageReport' => (bool) $user?->can('dough-usage.view'),
                'canCompleteProductionOrders' => (bool) $user?->can('production-orders.complete'),
                'canAccessCustomerOrderManagement' => $user !== null && collect(PermissionSeeder::customerOrderPermissionNames())
                    ->contains(fn (string $permission): bool => $user->can($permission)),
                'canViewSales' => (bool) $user?->can('sales.view'),
                'canCreateSales' => (bool) $user?->can('sales.create'),
                'canUpdateSales' => (bool) $user?->can('sales.update'),
                'canRecordSalePayments' => (bool) $user?->can('sales.payment'),
                'canReturnSales' => (bool) $user?->can('sales.return'),
                'canExchangeSales' => (bool) ($user?->can('sales.exchange') || $user?->can('sales.return')),
                'canAccessSalesManagement' => $user !== null && collect(PermissionSeeder::salesManagementPermissionNames())
                    ->contains(fn (string $permission): bool => $user->can($permission)),
                'canViewExpenses' => (bool) $user?->can('expenses.view'),
                'canCreateExpenses' => (bool) $user?->can('expenses.create'),
                'canEditExpenses' => (bool) $user?->can('expenses.edit'),
                'canDeleteExpenses' => (bool) $user?->can('expenses.delete'),
                'canManageExpenseCategories' => (bool) $user?->can('expense-categories.manage'),
                'canViewExpenseReports' => (bool) $user?->can('expense-reports.view'),
                'canAccessExpenseManagement' => $user !== null && collect(PermissionSeeder::expenseManagementPermissionNames())
                    ->contains(fn (string $permission): bool => $user->can($permission)),
                'canViewCashHandovers' => (bool) $user?->can('cash-handovers.view'),
                'canCreateCashHandovers' => (bool) ($user?->can('cash-handovers.create') || $user?->can('cash-handovers.settle')),
                'canSettleCashHandovers' => (bool) $user?->can('cash-handovers.settle'),
                'canRecordOwnerWithdrawals' => (bool) ($user?->can('cash-handovers.create') || $user?->can('cash-handovers.settle')),
                'canAccessCashHandovers' => $user !== null && collect(PermissionSeeder::cashHandoverPermissionNames())
                    ->contains(fn (string $permission): bool => $user->can($permission)),
                'canViewSarafs' => (bool) $user?->can('sarafs.view'),
                'canCreateSarafs' => (bool) $user?->can('sarafs.create'),
                'canUpdateSarafs' => (bool) $user?->can('sarafs.update'),
                'canAccessSarafiManagement' => $user !== null && collect(PermissionSeeder::sarafiManagementPermissionNames())
                    ->contains(fn (string $permission): bool => $user->can($permission)),
                'canViewMoraqebatMachines' => (bool) $user?->can('moraqebat-machines.view'),
                'canCreateMoraqebatMachines' => (bool) $user?->can('moraqebat-machines.create'),
                'canUpdateMoraqebatMachines' => (bool) $user?->can('moraqebat-machines.update'),
                'canViewMoraqebatChecklists' => (bool) $user?->can('moraqebat-checklists.view'),
                'canCreateMoraqebatChecklists' => (bool) $user?->can('moraqebat-checklists.create'),
                'canAccessMoraqebatManagement' => $user !== null && collect(PermissionSeeder::moraqebatManagementPermissionNames())
                    ->contains(fn (string $permission): bool => $user->can($permission)),
            ],
            'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
        ];
    }
}
