<?php

namespace App\Console\Commands;

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

class SetupCustomerRoles extends Command
{
    protected $signature = 'setup:customer-roles';
    protected $description = 'Assign customer_portal role to customer users';

    public function handle()
    {
        // Find the customer_portal role
        $customerRole = Role::where('name', 'customer_portal')->first();
        
        if (!$customerRole) {
            $this->error('customer_portal role not found!');
            return 1;
        }

        // Find customer users
        $customerEmails = ['customer@example.com', 'testcustomer@example.com'];
        $users = User::whereIn('email', $customerEmails)->get();

        foreach ($users as $user) {
            if (!$user->hasRole('customer_portal')) {
                $user->roles()->attach($customerRole->id, [
                    'is_active' => true,
                    'assigned_at' => now(),
                    'branch_code' => null,
                    'created_at' => now(),
                    'updated_at' => now()
                ]);
                $this->info("Assigned customer_portal role to: {$user->email}");
            } else {
                $this->info("User {$user->email} already has customer_portal role");
            }
        }

        return 0;
    }
}
