<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use Spatie\Permission\Models\Role;

class CheckAdminAccess extends Command
{
    protected $signature = 'admin:check-access';
    protected $description = 'Check and fix admin user access';

    public function handle(): int
    {
        $this->info('Checking admin access...');
        $this->newLine();

        // Check if admin role exists
        $adminRole = Role::where('name', 'admin')->first();
        if (!$adminRole) {
            $this->error('Admin role does not exist!');
            $this->info('Run: php artisan db:seed --class=RolesAndPermissionsSeeder');
            return Command::FAILURE;
        }
        $this->info('✓ Admin role exists');

        // Check admin user
        $admin = User::where('mobile', '9999999999')->first();
        if (!$admin) {
            $this->error('Admin user (mobile: 9999999999) does not exist!');
            $this->info('Run: php artisan db:seed --class=AdminUserSeeder');
            return Command::FAILURE;
        }
        $this->info('✓ Admin user exists');

        // Check if admin has role and user_type
        if (!$admin->hasRole('admin')) {
            $this->warn('Admin user does not have admin role. Assigning...');
            $admin->assignRole('admin');
            $this->info('✓ Admin role assigned');
        } else {
            $this->info('✓ Admin user has admin role');
        }
        
        // Check and set user_type
        if ($admin->user_type !== 'admin') {
            $this->warn('Admin user does not have admin user_type. Setting...');
            $admin->user_type = 'admin';
            $admin->save();
            $this->info('✓ Admin user_type set');
        } else {
            $this->info('✓ Admin user has admin user_type');
        }

        // Display admin info
        $this->newLine();
        $this->info('Admin User Details:');
        $this->line('  Name: ' . $admin->name);
        $this->line('  Mobile: ' . $admin->mobile);
        $this->line('  Email: ' . ($admin->email ?? 'Not set'));
        $this->line('  Roles: ' . $admin->roles->pluck('name')->implode(', '));

        $this->newLine();
        $this->info('To login:');
        $this->line('  1. Go to /login');
        $this->line('  2. Enter mobile: 9999999999');
        $this->line('  3. Request OTP');
        $this->line('  4. Check Laravel logs for OTP (in development mode)');
        $this->line('  5. Enter OTP to login');
        $this->line('  6. Access admin panel at /admin');

        return Command::SUCCESS;
    }
}
