<?php

namespace App\Console\Commands;

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

class CreateCustomerUser extends Command
{
    protected $signature = 'customer:create {email} {name} {password}';
    protected $description = 'Create a customer user account';

    public function handle()
    {
        $email = $this->argument('email');
        $name = $this->argument('name');
        $password = $this->argument('password');

        // Validate inputs
        if (empty($name)) {
            $this->error('Name cannot be empty');
            return 1;
        }

        // Create or find customer record
        $nameParts = explode(' ', $name, 2);
        $firstName = $nameParts[0];
        $lastName = $nameParts[1] ?? '';

        // Check if customer already exists
        $existingCustomer = Customer::where('email', $email)->first();
        if ($existingCustomer) {
            $this->info("Customer with email {$email} already exists.");
            $customer = $existingCustomer;
        } else {
            $customer = Customer::create([
                'first_name' => $firstName,
                'last_name' => $lastName,
                'email' => $email,
                'phone' => '000-000-0000',
                'address' => '123 Main St',
                'city' => 'Anytown',
                'state' => 'CA',
                'zip_code' => '12345',
                'status' => 'active'
            ]);
            $this->info("Customer record created for {$email}");
        }

        // Check if user already exists
        $existingUser = User::where('email', $email)->first();
        if ($existingUser) {
            $this->error("User with email {$email} already exists!");
            return 1;
        }

        // Create user account
        $user = User::create([
            'name' => $name,
            'email' => $email,
            'password' => Hash::make($password),
            'status' => 'active'
        ]);

        $this->info("Customer user created successfully!");
        $this->info("Email: {$email}");
        $this->info("Password: {$password}");
        $this->info("You can now login at /login");
        
        return 0;
    }
}
