<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Customer;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Hash;

class SetupCustomerAccounts extends Command
{
    protected $signature = 'customers:setup-accounts';
    protected $description = 'Create user accounts for all customers based on their email';

    public function handle()
    {
        $customerRole = Role::firstOrCreate(['name' => 'Customer']);
        $customers = Customer::whereNotNull('email')->get();
        $count = 0;

        foreach ($customers as $customer) {
            $user = User::firstOrCreate(
                ['email' => $customer->email],
                [
                    'name' => $customer->full_name,
                    'password' => Hash::make('1234')
                ]
            );
            
            if (!$user->hasRole('Customer')) {
                $user->assignRole($customerRole);
            }
            $count++;
        }

        $this->info("Successfully created/updated accounts for $count customers.");
    }
}
