<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RoleController extends Controller
{
    public function index()
    {
        $roles = Role::with('permissions')->get();

        return view('pages.roles.index', compact('roles'));
    }

    public function create()
    {
        $permissions = Permission::orderBy('name')->get();
        $groupedPermissions = $this->groupPermissions($permissions);

        $permissionLabels = $this->permissionLabels();

        return view('pages.roles.form', compact('groupedPermissions', 'permissionLabels'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|unique:roles,name',
            'permissions' => 'array',
            'permissions.*' => 'string|exists:permissions,name',
        ]);

        $role = Role::create(['name' => $validated['name']]);

        $role->syncPermissions($validated['permissions'] ?? []);

        return redirect()->route('roles.index')->with('success', 'Role berhasil dibuat.');
    }

    public function edit(Role $role)
    {
        $permissions = Permission::orderBy('name')->get();
        $groupedPermissions = $this->groupPermissions($permissions);
        $rolePermissions = $role->permissions->pluck('name')->toArray();

        $permissionLabels = $this->permissionLabels();

        return view('pages.roles.form', compact('role', 'groupedPermissions', 'rolePermissions', 'permissionLabels'));
    }

    public function update(Request $request, Role $role)
    {
        $validated = $request->validate([
            'name' => 'required|unique:roles,name,' . $role->id,
            'permissions' => 'array',
            'permissions.*' => 'string|exists:permissions,name',
        ]);

        if ($role->name !== 'developer') {
            $role->update(['name' => $validated['name']]);
        }

        $role->syncPermissions($validated['permissions'] ?? []);

        return redirect()->route('roles.index')->with('success', 'Role berhasil diperbarui.');
    }

    public function destroy(Role $role)
    {
        if ($role->name === 'developer') {
            return back()->with('error', 'Role developer tidak boleh dihapus.');
        }

        $role->delete();

        return redirect()->route('roles.index')->with('success', 'Role berhasil dihapus.');
    }

    private function groupPermissions($permissions)
    {
        $groups = [
            'Dashboard' => [
                'view dashboard',
                'view ai',
            ],

            'Orders' => [
                'view orders',
                'create orders',
                'edit orders',
                'delete orders',
                'print spk',
            ],

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

            'Kasir' => [
                'view cashier bills',
                'view cashier payoff',
                'view cashier history',
                'view cashier pricelist',
                'process payments',
                'manage payments',
                'edit payments',
                'delete payments',
                'refund payments',
            ],

            'Produksi' => [
                'view production queue',
                'view production history',
                'update production',
                'manage production',
                'start production',
                'move production finishing',
                'complete production',
            ],

            'Pembatalan' => [
                'request cancellations',
                'approve cancellations',
                'view cancellations',
            ],

            'Absensi' => [
                'view attendance',
                'view attendance recap',
                'manage attendance settings',
                'manage attendance',
            ],

            'Keuangan' => [
                'view finance',
                'view finance cash',
                'manage deposits',
                'view payment accounts',
                'create payment accounts',
                'edit payment accounts',
                'delete payment accounts',
                'manage payment accounts',
            ],

            'Pembukuan' => [
                'view general journal',
                'view profit loss',
                'view balance sheet',
            ],

            'Laporan' => [
                'view reports',
                '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 & Harga' => [
                'view products',
                'create products',
                'edit products',
                'delete products',
                'view units',
                'manage units',
                'view suppliers',
                'create suppliers',
                'edit suppliers',
                'delete suppliers',
                'manage suppliers',
            ],

            'Bahan & Stok' => [
                'view stock categories',
                'manage stock categories',
                'view materials',
                'create materials',
                'edit materials',
                'delete materials',
                'manage materials',
                'view machines',
                'manage machines',
                'view stock usage',
                'manage stock usage',
                'view damaged stock',
                'manage damaged stock',
                'view stock',
                'manage stock',
                'view stock incoming',
                'manage stock incoming',
            ],

            'Pembelian' => [
                'view purchases',
                'create purchases',
                'edit purchases',
                'delete purchases',
                'manage purchases',
                'view purchase payments',
                'manage purchase payments',
            ],

            'Pengeluaran' => [
                'view expenses',
                'create expenses',
                'edit expenses',
                'delete expenses',
                'manage expenses',
                'view expense categories',
                'manage expense categories',
            ],

            'Master Data' => [
                'view customers',
                'create customers',
                'edit customers',
                'delete customers',
                'manage customers',
                'view vehicles',
                'create vehicles',
                'edit vehicles',
                'delete vehicles',
                'manage vehicles',
                'view tax settings',
                'manage tax settings',
                'view ppn',
                'manage ppn',
            ],

            'User, Role & Karyawan' => [
                'view users',
                'create users',
                'edit users',
                'delete users',
                'manage users',
                'manage roles',
                'manage permissions',
                'view employees',
                'create employees',
                'edit employees',
                'delete employees',
                'view salaries',
                'create salaries',
                'edit salaries',
                'delete salaries',
            ],

            'Backup & Pengaturan' => [
                'manage backups',
                'view settings',
                'edit settings',
                'manage settings',
            ],

            'AI Assistant' => [
                'access ai',
                'manage ai',
                'ai.sales',
                'ai.index',
            ],
        ];

        $result = [];
        $assignedIds = [];

        foreach ($groups as $groupName => $permissionNames) {
            $filtered = $permissions->filter(function ($permission) use ($permissionNames, $groupName) {
                $name = strtolower($permission->name);

                if (in_array($permission->name, $permissionNames, true)) {
                    return true;
                }

                return match ($groupName) {
                    'Surat Jalan & Pengiriman' => str_contains($name, 'delivery') || str_contains($name, 'vehicle') || str_contains($name, 'surat jalan'),
                    'Kasir & Pembayaran' => str_contains($name, 'payment') || str_contains($name, 'kasir') || str_contains($name, 'cashier') || str_contains($name, 'refund'),
                    'Invoice, Nota & PPN' => str_contains($name, 'invoice') || str_contains($name, 'nota') || str_contains($name, 'tax') || str_contains($name, 'ppn'),
                    'Pembelian & Bahan Baku' => str_contains($name, 'purchase') || str_contains($name, 'material') || str_contains($name, 'stock'),
                    'AI Assistant' => str_contains($name, 'ai'),
                    default => false,
                };
            })->values();

            if ($filtered->isNotEmpty()) {
                $result[$groupName] = $filtered;

                foreach ($filtered as $permission) {
                    $assignedIds[] = $permission->id;
                }
            }
        }

        $others = $permissions->whereNotIn('id', array_unique($assignedIds))->values();

        if ($others->isNotEmpty()) {
            $result['Lainnya'] = $others;
        }

        return $result;
    }
    private function permissionLabels()
    {
        return [
            'view dashboard' => 'Dashboard',
            'view ai' => 'Intelligence / AI',
            'view orders' => 'Daftar Order',
            'create orders' => 'Buat Order',
            'edit orders' => 'Edit Order',
            'delete orders' => 'Hapus Order',
            'print spk' => 'Cetak SPK',
            'view delivery notes' => 'Surat Jalan',
            'create delivery notes' => 'Buat Surat Jalan',
            'edit delivery notes' => 'Edit Surat Jalan',
            'delete delivery notes' => 'Batalkan/Hapus Surat Jalan',
            'print delivery notes' => 'Cetak Surat Jalan',
            'manage delivery notes' => 'Kelola Surat Jalan',
            'view cashier bills' => 'Kasir - Tagihan',
            'view cashier payoff' => 'Kasir - Pelunasan',
            'view cashier history' => 'Kasir - Riwayat',
            'view cashier pricelist' => 'Kasir - Pricelist',
            'process payments' => 'Proses Pembayaran',
            'manage payments' => 'Kelola Pembayaran',
            'edit payments' => 'Edit Pembayaran',
            'delete payments' => 'Hapus Pembayaran',
            'refund payments' => 'Refund Pembayaran',
            'view production queue' => 'Produksi - Antrian Cetak',
            'view production history' => 'Produksi - Riwayat',
            'update production' => 'Update Status Produksi',
            'manage production' => 'Kelola Produksi',
            'start production' => 'Mulai Cetak',
            'move production finishing' => 'Lanjut ke Finishing',
            'complete production' => 'Selesaikan Produksi',
            'request cancellations' => 'Ajukan Pembatalan',
            'approve cancellations' => 'Approve Pembatalan',
            'view cancellations' => 'Lihat Pembatalan',
            'view attendance' => 'Absensi',
            'view attendance recap' => 'Rekap Absensi',
            'manage attendance settings' => 'Pengaturan Absensi',
            'manage attendance' => 'Kelola Absensi',
            'view finance' => 'Laporan Keuangan',
            'view finance cash' => 'Laporan Kas',
            'manage deposits' => 'Data Setoran',
            'view payment accounts' => 'Rekening Pembayaran',
            'create payment accounts' => 'Tambah Rekening',
            'edit payment accounts' => 'Edit Rekening',
            'delete payment accounts' => 'Hapus Rekening',
            'manage payment accounts' => 'Kelola Rekening',
            'view general journal' => 'Jurnal Umum',
            'view profit loss' => 'Laba - Rugi',
            'view balance sheet' => 'Neraca',
            'view reports' => 'Semua Laporan',
            'view cash ledger' => 'Buku Besar',
            'view receivables report' => 'Piutang',
            'view sales reports' => 'Omset',
            'view revenue reports' => 'Pendapatan',
            'view purchase debt reports' => 'Hutang',
            'view click reports' => 'Klik',
            'view transaction logs' => 'Log Transaksi',
            'view finance reports' => 'Laporan Finance',
            'view production reports' => 'Laporan Produksi',
            'view expense reports' => 'Laporan Pengeluaran',
            'view products' => 'Produk',
            'create products' => 'Tambah Produk',
            'edit products' => 'Edit Produk',
            'delete products' => 'Hapus Produk',
            'view units' => 'Satuan',
            'manage units' => 'Kelola Satuan',
            'view suppliers' => 'Supplier',
            'create suppliers' => 'Tambah Supplier',
            'edit suppliers' => 'Edit Supplier',
            'delete suppliers' => 'Hapus Supplier',
            'manage suppliers' => 'Kelola Supplier',
            'view stock categories' => 'Kategori Stok',
            'manage stock categories' => 'Kelola Kategori Stok',
            'view materials' => 'Bahan',
            'create materials' => 'Tambah Bahan',
            'edit materials' => 'Edit Bahan',
            'delete materials' => 'Hapus Bahan',
            'manage materials' => 'Kelola Bahan',
            'view machines' => 'Mesin',
            'manage machines' => 'Kelola Mesin',
            'view stock usage' => 'Penggunaan Stok',
            'manage stock usage' => 'Kelola Penggunaan Stok',
            'view damaged stock' => 'Bahan Rusak',
            'manage damaged stock' => 'Kelola Bahan Rusak',
            'view stock' => 'Data Stok',
            'manage stock' => 'Kelola Stok',
            'view stock incoming' => 'Stok Masuk',
            'manage stock incoming' => 'Kelola Stok Masuk',
            'view purchases' => 'Pembelian',
            'create purchases' => 'Tambah Pembelian',
            'edit purchases' => 'Edit Pembelian',
            'delete purchases' => 'Hapus Pembelian',
            'manage purchases' => 'Kelola Pembelian',
            'view purchase payments' => 'Pembayaran Pembelian',
            'manage purchase payments' => 'Kelola Pembayaran Pembelian',
            'view expenses' => 'Data Pengeluaran',
            'create expenses' => 'Tambah Pengeluaran',
            'edit expenses' => 'Edit Pengeluaran',
            'delete expenses' => 'Hapus Pengeluaran',
            'manage expenses' => 'Kelola Pengeluaran',
            'view expense categories' => 'Jenis Pengeluaran',
            'manage expense categories' => 'Kelola Jenis Pengeluaran',
            'view customers' => 'Pelanggan',
            'create customers' => 'Tambah Pelanggan',
            'edit customers' => 'Edit Pelanggan',
            'delete customers' => 'Hapus Pelanggan',
            'manage customers' => 'Kelola Pelanggan',
            'view vehicles' => 'Kendaraan',
            'create vehicles' => 'Tambah Kendaraan',
            'edit vehicles' => 'Edit Kendaraan',
            'delete vehicles' => 'Hapus Kendaraan',
            'manage vehicles' => 'Kelola Kendaraan',
            'view tax settings' => 'PPN / Pajak',
            'manage tax settings' => 'Kelola PPN / Pajak',
            'view ppn' => 'Lihat PPN',
            'manage ppn' => 'Kelola PPN',
            'view users' => 'Users',
            'create users' => 'Tambah User',
            'edit users' => 'Edit User',
            'delete users' => 'Hapus User',
            'manage users' => 'Kelola Users',
            'manage roles' => 'Roles',
            'manage permissions' => 'Permissions',
            'view employees' => 'Karyawan',
            'create employees' => 'Tambah Karyawan',
            'edit employees' => 'Edit Karyawan',
            'delete employees' => 'Hapus Karyawan',
            'view salaries' => 'Gaji & Slip',
            'create salaries' => 'Tambah Gaji',
            'edit salaries' => 'Edit Gaji',
            'delete salaries' => 'Hapus Gaji',
            'manage backups' => 'Backup DB',
            'view settings' => 'Pengaturan',
            'edit settings' => 'Edit Pengaturan',
            'manage settings' => 'Kelola Pengaturan',
            'access ai' => 'Akses AI',
            'manage ai' => 'Kelola AI',
            'ai.sales' => 'AI Sales',
            'ai.index' => 'AI Index',
        ];
    }
}

