<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class GenerateModulePermissions extends Command
{
    protected $signature = 'permissions:generate';

    protected $description = 'Generate permissions for all modules based on predefined actions and groups';

    public function handle()
    {
        $this->showBrandHeader();

        // Groups with their modules
        $groups = [
            'HRM' => [
                'employee',
                'attendance',
                'attendancelog',
                'allowance',
                'compensation',
                'leave',
                'payroll',
                'advance',
                'deduction',
                'cnssdeclaration',
                'absence'
            ],
            'PRODUCT' => [
                'product',
                'category',
                'brand',
                'unit',
                'tax'
            ],
            'CRM' => [
                'supplier',
                'client'
            ],
            'OPERATION' => [
                'pricerequest',
                'purchaseorder',
                'receiptnote',
                'invoicepurchase',
                'returnpurchase',
                'exitnote',
                'entrynote',
                'estimate',
                'deliverynote',
                'invoicesale',
                'returnsale',
                'orderprod',
                'generateprod',
                'transfernote',
                'adjustmentnote',
                'possale',
                'pos'
            ],
            'STOCK' => [
                'warehouse',
                'stocklog',
                'immobilisation'
            ],
            'MEDIA' => [
                'media',
            ],
            'ACCOUNTING' => [
                'expense',
                'account',
                'journal',
                'accountingentry',
                'bankaccount',
                'bankoperation',
                'payment',
                'receipt',
                'paymentmethod'
            ],
            'ADMIN' => [
                'user',
                'role',
                'permission',
                'language',
                'column',
                'setting',
                'audit'
            ],
        ];

        // Common CRUD + extra actions
        $actions = [
            'view',
            'create',
            'update',
            'delete',
            'clone',
            'export',
            'import',
            'upload',
            'download'
        ];

        $createdCount = 0;

        foreach ($groups as $group => $modules) {
            $this->info("🔹 Generating permissions for group: {$group}");

            foreach ($modules as $module) {
                foreach ($actions as $action) {
                    // Permission name with group prefix
                    $permissionName = strtolower("{$module}-{$action}");

                    if (!Permission::where('name', $permissionName)->exists()) {
                        Permission::create([
                            'name' => $permissionName,
                            'group' => $group
                        ]);
                        $this->info("   ✅ Created: {$permissionName}");
                        $createdCount++;
                    } else {
                        $this->alert("   ⚠️ Exists: {$permissionName}");
                    }
                }
            }

            $this->newLine();
        }

        $this->assignAdminPermissions();

        $this->newLine();
        $this->info("🎯 Done! {$createdCount} new permissions created.");
        $this->newLine();
        $this->line("<fg=cyan>✨ Keep building amazing things with Proxy Work!</>");
    }

    private function assignAdminPermissions()
    {
        $adminRole = Role::firstOrCreate(['name' => 'admin']);

        $groups = ['ADMIN', 'HRM', 'PRODUCT', 'OPERATION', 'CRM','MEDIA','STOCK'];

        $allPermissions = [];

        foreach ($groups as $group) {
            $permissions = Permission::where('group', $group)->pluck('name')->toArray();
            $allPermissions = array_merge($allPermissions, $permissions);

            $this->info("   🔹 Found " . count($permissions) . " {$group} permissions");
        }

        $adminRole->syncPermissions($allPermissions);

        $this->newLine();
        $this->info("🔑 Assigned " . count($allPermissions) . " total permissions to Admin role ✅");
    }


    /**
     * Show ASCII brand header like Laravel
     */
    private function showBrandHeader()
    {
        $this->line("<fg=cyan>
__   ____ _  __  ____
\\ \\ / /_ | |/ / |___ \\
 \\ V / | | ' /    __) |
  > <  | | . \\   / __/
 / . \\ |_|_|\\_\\ |_____|
/_/
</>");
        $this->line("");
        $this->line("=====================================");
        $this->line("🚀  PROXY WORK PERMISSION GENERATOR  ");
        $this->line("=====================================");
        $this->line(" Empowering your entreprise projects 🚀 ");
        $this->line(" Made it with love❤️ by zakaria ");
        $this->line("");
    }
}
