<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class PermissionMiddleware
{
    /**
     * Handle an incoming request.
     *
     * Check if user has ANY of the specified permissions dynamically
     * from Spatie Permission package.
     *
     * Catatan:
     * - Developer tetap akses semua.
     * - Permission lama tetap aman.
     * - Permission submenu baru bisa membuka route lama yang masih pakai permission induk.
     */
    public function handle(Request $request, Closure $next, string ...$permissions): Response
    {
        if (!$request->user()) {
            return redirect()->route('login');
        }

        if (!$request->user()->is_active) {
            auth()->logout();

            return redirect()->route('login')
                ->with('error', 'Akun Anda telah dinonaktifkan.');
        }

        // Developer has access to everything
        if (method_exists($request->user(), 'isDeveloper') && $request->user()->isDeveloper()) {
            return $next($request);
        }

        if (!empty($permissions)) {
            $expandedPermissions = $this->expandPermissions($permissions);

            $hasPermission = false;

            foreach ($expandedPermissions as $permission) {
                if ($request->user()->can($permission)) {
                    $hasPermission = true;
                    break;
                }
            }

            if (!$hasPermission) {
                abort(403, 'Anda tidak memiliki akses ke halaman ini.');
            }
        }

        return $next($request);
    }

    /**
     * Tambahkan alias permission agar menu/submenu role baru tetap bisa membuka
     * route lama yang masih memakai permission induk.
     */
    private function expandPermissions(array $permissions): array
    {
        $aliases = [
            /*
            |--------------------------------------------------------------------------
            | Orders
            |--------------------------------------------------------------------------
            */
            'view orders' => [
                'view orders',
                'create orders',
                'edit orders',
                'print spk',
            ],

            /*
            |--------------------------------------------------------------------------
            | Surat Jalan
            |--------------------------------------------------------------------------
            */
            'view delivery notes' => [
                'view delivery notes',
                'create delivery notes',
                'edit delivery notes',
                'print delivery notes',
                'manage delivery notes',
            ],
            'create delivery notes' => [
                'create delivery notes',
                'manage delivery notes',
            ],
            'edit delivery notes' => [
                'edit delivery notes',
                'manage delivery notes',
            ],
            'delete delivery notes' => [
                'delete delivery notes',
                'manage delivery notes',
            ],
            'print delivery notes' => [
                'print delivery notes',
                'manage delivery notes',
            ],

            /*
            |--------------------------------------------------------------------------
            | Kasir / Pembayaran
            | Route lama biasanya pakai "process payments".
            |--------------------------------------------------------------------------
            */
            'process payments' => [
                'process payments',
                'view cashier bills',
                'view cashier payoff',
                'view cashier history',
                'view cashier pricelist',
                'view payments',
                'manage payments',
                'edit payments',
                'delete payments',
                'refund payments',
            ],
            'manage payments' => [
                'manage payments',
                'process payments',
                'view payments',
                'view cashier history',
            ],
            'view payments' => [
                'view payments',
                'process payments',
                'manage payments',
            ],

            /*
            |--------------------------------------------------------------------------
            | Produksi
            | Route lama biasanya pakai "update production".
            |--------------------------------------------------------------------------
            */
            'update production' => [
                'update production',
                'view production',
                'view production queue',
                'view production history',
                'start production',
                'move production finishing',
                'complete production',
                'manage production',
            ],
            'view production' => [
                'view production',
                'view production queue',
                'view production history',
                'update production',
                'manage production',
            ],
            'manage production' => [
                'manage production',
                'update production',
                'view production',
                'view production queue',
                'view production history',
            ],

            /*
            |--------------------------------------------------------------------------
            | Pembatalan
            |--------------------------------------------------------------------------
            */
            'approve cancellations' => [
                'approve cancellations',
                'view cancellations',
            ],
            'view cancellations' => [
                'view cancellations',
                'approve cancellations',
            ],

            /*
            |--------------------------------------------------------------------------
            | Absensi / Karyawan
            |--------------------------------------------------------------------------
            */
            'view employees' => [
                'view employees',
                'view attendance',
                'view attendance recap',
            ],
            'manage attendance' => [
                'manage attendance',
                'view attendance',
                'view attendance recap',
                'manage attendance settings',
            ],

            /*
            |--------------------------------------------------------------------------
            | Keuangan
            |--------------------------------------------------------------------------
            */
            'view finance' => [
                'view finance',
                'view finance cash',
                'manage deposits',
            ],
            'manage deposits' => [
                'manage deposits',
                'view finance',
            ],

            /*
            |--------------------------------------------------------------------------
            | Pembukuan / Laporan
            |--------------------------------------------------------------------------
            */
            'view reports' => [
                'view reports',
                'view general journal',
                'view profit loss',
                'view balance sheet',
                'view cash ledger',
                'view receivables report',
                'view sales reports',
                'view revenue reports',
                'view purchase debt reports',
                'view click reports',
                'view transaction logs',
                'view finance reports',
                'view production reports',
                'view expense reports',
            ],

            /*
            |--------------------------------------------------------------------------
            | Produk / Supplier / Satuan
            |--------------------------------------------------------------------------
            */
            'view products' => [
                'view products',
                'create products',
                'edit products',
                'delete products',
            ],
            'view units' => [
                'view units',
                'manage units',
            ],
            'view suppliers' => [
                'view suppliers',
                'create suppliers',
                'edit suppliers',
                'delete suppliers',
                'manage suppliers',
            ],
            'manage suppliers' => [
                'manage suppliers',
                'view suppliers',
                'create suppliers',
                'edit suppliers',
                'delete suppliers',
            ],

            /*
            |--------------------------------------------------------------------------
            | Bahan / Stock / Pembelian
            |--------------------------------------------------------------------------
            */
            'view materials' => [
                'view materials',
                'create materials',
                'edit materials',
                'delete materials',
                'manage materials',
            ],
            'manage materials' => [
                'manage materials',
                'view materials',
                'create materials',
                'edit materials',
                'delete materials',
            ],
            'view stock' => [
                'view stock',
                'manage stock',
                'view stock categories',
                'manage stock categories',
                'view stock usage',
                'manage stock usage',
                'view damaged stock',
                'manage damaged stock',
                'view stock incoming',
                'manage stock incoming',
                'view purchases',
                'create purchases',
                'edit purchases',
                'manage purchases',
            ],
            'manage stock' => [
                'manage stock',
                'view stock',
                'view stock categories',
                'manage stock categories',
                'view stock usage',
                'manage stock usage',
                'view damaged stock',
                'manage damaged stock',
                'view stock incoming',
                'manage stock incoming',
            ],
            'view machines' => [
                'view machines',
                'manage machines',
            ],
            'view purchases' => [
                'view purchases',
                'create purchases',
                'edit purchases',
                'delete purchases',
                'manage purchases',
                'view purchase payments',
                'manage purchase payments',
            ],
            'manage purchases' => [
                'manage purchases',
                'view purchases',
                'create purchases',
                'edit purchases',
                'delete purchases',
                'view purchase payments',
                'manage purchase payments',
            ],

            /*
            |--------------------------------------------------------------------------
            | Pengeluaran
            |--------------------------------------------------------------------------
            */
            'view expenses' => [
                'view expenses',
                'create expenses',
                'edit expenses',
                'delete expenses',
                'manage expenses',
                'view expense categories',
                'manage expense categories',
            ],
            'manage expenses' => [
                'manage expenses',
                'view expenses',
                'create expenses',
                'edit expenses',
                'delete expenses',
                'view expense categories',
                'manage expense categories',
            ],

            /*
            |--------------------------------------------------------------------------
            | Master Data
            |--------------------------------------------------------------------------
            */
            'manage customers' => [
                'manage customers',
                'view customers',
                'create customers',
                'edit customers',
                'delete customers',
            ],
            'manage vehicles' => [
                'manage vehicles',
                'view vehicles',
                'create vehicles',
                'edit vehicles',
                'delete vehicles',
            ],
            'manage payment accounts' => [
                'manage payment accounts',
                'view payment accounts',
                'create payment accounts',
                'edit payment accounts',
                'delete payment accounts',
            ],
            'manage users' => [
                'manage users',
                'view users',
                'create users',
                'edit users',
                'delete users',
                'manage roles',
                'manage permissions',
            ],

            /*
            |--------------------------------------------------------------------------
            | PPN / Setting
            |--------------------------------------------------------------------------
            */
            'manage settings' => [
                'manage settings',
                'view settings',
                'edit settings',
                'manage attendance settings',
                'view tax settings',
                'manage tax settings',
                'view ppn',
                'manage ppn',
            ],
            'manage tax settings' => [
                'manage tax settings',
                'view tax settings',
                'view ppn',
                'manage ppn',
            ],
            'manage ppn' => [
                'manage ppn',
                'view ppn',
                'view tax settings',
                'manage tax settings',
            ],

            /*
            |--------------------------------------------------------------------------
            | Gaji
            |--------------------------------------------------------------------------
            */
            'view salaries' => [
                'view salaries',
                'create salaries',
                'edit salaries',
                'delete salaries',
            ],

            /*
            |--------------------------------------------------------------------------
            | AI
            |--------------------------------------------------------------------------
            */
            'view ai' => [
                'view ai',
                'access ai',
                'ai.sales',
                'ai.index',
            ],
            'access ai' => [
                'access ai',
                'view ai',
                'ai.sales',
                'ai.index',
            ],
        ];

        $expanded = [];

        foreach ($permissions as $permission) {
            $permission = trim((string) $permission);

            if ($permission === '') {
                continue;
            }

            $expanded[] = $permission;

            if (isset($aliases[$permission])) {
                foreach ($aliases[$permission] as $alias) {
                    $expanded[] = $alias;
                }
            }
        }

        return array_values(array_unique($expanded));
    }
}
