<?php

namespace App\Console\Commands;

use App\Models\Permission;
use App\Models\Role;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;

class FixPermissions extends Command
{
    protected $signature = 'permissions:fix {--force : Force fix without confirmation}';

    protected $description = 'Fix permission system and update to correct naming format';

    public function handle()
    {
        $this->info('🔧 Privasee Permission System Fix');
        $this->newLine();

        // Step 1: Check current state
        $this->info('📊 Checking current permission state...');
        $oldPermissions = Permission::where('name', 'LIKE', '%.%')->count();
        $newPermissions = Permission::where('name', 'LIKE', '%-%')->count();

        $this->table(
            ['Type', 'Count', 'Status'],
            [
                ['Old (dot notation)', $oldPermissions, $oldPermissions > 0 ? '⚠️  Found' : '✅ None'],
                ['New (hyphen notation)', $newPermissions, $newPermissions > 0 ? '✅ Good' : '⚠️  Missing'],
            ]
        );
        $this->newLine();

        if ($newPermissions > 0) {
            $this->info('✅ New permissions already exist!');

            if (!$this->option('force')) {
                if (!$this->confirm('Do you want to re-run seeders anyway?', false)) {
                    $this->info('Aborted. No changes made.');
                    return 0;
                }
            }
        }

        // Step 2: Run seeders
        $this->info('🌱 Running permission seeders...');
        $this->newLine();

        $this->warn('Running AdminPermissionsSeeder...');
        Artisan::call('db:seed', ['--class' => 'AdminPermissionsSeeder']);
        $this->info('✅ Admin permissions seeded');

        $this->warn('Running BusinessPermissionsSeeder...');
        Artisan::call('db:seed', ['--class' => 'BusinessPermissionsSeeder']);
        $this->info('✅ Business permissions seeded');
        $this->newLine();

        // Step 3: Verify
        $this->info('✅ Verification...');
        $totalPermissions = Permission::count();
        $hyphenPermissions = Permission::where('name', 'LIKE', '%-%')->count();

        $this->table(
            ['Metric', 'Value'],
            [
                ['Total Permissions', $totalPermissions],
                ['Hyphen Format', $hyphenPermissions],
                ['Unique Groups', Permission::distinct('group')->count()],
            ]
        );
        $this->newLine();

        // Step 4: Check roles
        $this->info('🔐 Checking role assignments...');
        $roles = Role::withCount('permissions')->get();

        $roleData = [];
        foreach ($roles as $role) {
            $roleData[] = [
                $role->name,
                $role->display_name,
                $role->permissions_count,
                $role->permissions_count > 0 ? '✅' : '⚠️',
            ];
        }

        $this->table(['Role Name', 'Display Name', 'Permissions', 'Status'], $roleData);
        $this->newLine();

        // Step 5: Offer to remove old permissions
        if ($oldPermissions > 0) {
            $this->warn("⚠️  Found {$oldPermissions} old permissions with dot notation.");

            if ($this->confirm('Do you want to remove old dot-notation permissions?', false)) {
                $this->info('🗑️  Removing old permissions...');
                $deleted = Permission::where('name', 'LIKE', '%.%')->delete();
                $this->info("✅ Removed {$deleted} old permissions");
                $this->newLine();
            }
        }

        // Step 6: Clear caches
        $this->info('🧹 Clearing caches...');
        Artisan::call('cache:clear');
        Artisan::call('config:clear');
        Artisan::call('view:clear');
        $this->info('✅ Caches cleared');
        $this->newLine();

        // Success message
        $this->info('🎉 Permission system fixed successfully!');
        $this->newLine();

        // Show next steps
        $this->info('📝 Next Steps:');
        $this->line('1. Test permissions: php artisan tinker');
        $this->line('   $user = User::find(1);');
        $this->line('   $user->hasPermission("manage-users");');
        $this->line('');
        $this->line('2. View admin panel and verify sidebar items appear correctly');
        $this->line('');
        $this->line('3. Assign roles to users if needed:');
        $this->line('   $user->assignRole("super_admin");');
        $this->newLine();

        $this->info('✅ All done! Your permission system is ready.');

        return 0;
    }
}
