<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;

class SetupAllUserPins extends Command
{
    protected $signature = 'users:setup-pins {--role=* : Specific roles to setup PINs for}';
    protected $description = 'Setup PINs for all active users or specific roles';

    public function handle()
    {
        $this->info('Setting up user PINs...');
        
        $query = User::where('is_active', true);
        
        // Filter by roles if specified
        if ($this->option('role')) {
            $roles = $this->option('role');
            $query->whereIn('role', $roles);
            $this->info("Filtering for roles: " . implode(', ', $roles));
        }
        
        $users = $query->get();
        
        if ($users->isEmpty()) {
            $this->warn('No active users found.');
            return;
        }
        
        $this->info("Found {$users->count()} active users:");
        
        $usedPins = [];
        
        foreach ($users as $user) {
            // Skip if user already has a PIN
            if ($user->pin) {
                $this->line("- {$user->name} ({$user->role}) - Already has PIN: {$user->pin}");
                $usedPins[] = $user->pin;
                continue;
            }
            
            // Generate a unique 4-digit PIN
            do {
                $pin = str_pad(rand(1000, 9999), 4, '0', STR_PAD_LEFT);
            } while (in_array($pin, $usedPins) || User::where('pin', $pin)->exists());
            
            // Update the user with the PIN
            $user->update(['pin' => $pin]);
            $usedPins[] = $pin;
            
            $this->line("- {$user->name} ({$user->role}) - New PIN: {$pin}");
        }
        
        $this->info('User PINs have been set up successfully!');
        $this->info('Users can now login using their PIN on the PIN login screen.');
        
        // Show role-based dashboard mapping
        $this->newLine();
        $this->info('Dashboard Mapping:');
        $this->line('- Admin/Manager → POS Dashboard');
        $this->line('- Waiter → Waiter Dashboard');
        $this->line('- Cashier → POS Dashboard');
        $this->line('- Kitchen → Kitchen Display');
        $this->line('- Inventory Manager → Inventory Page');
        $this->line('- Accountant → Reports Page');
    }
}