<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Customer;
use App\Models\User;
use App\Models\Role;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;

class TestCustomerCreation extends Command
{
    protected $signature = 'test:customer-creation';
    protected $description = 'Test customer creation process exactly like the form';

    public function handle()
    {
        $this->info('Testing customer creation process...');

        // Generate test data
        $email = 'formtest' . time() . '@example.com';
        $plainPassword = Str::random(12);
        $firstName = 'Form';
        $lastName = 'Test';
        $phone = '555-0123';
        
        $this->info("Creating customer with email: {$email}");
        $this->info("Generated password: {$plainPassword}");

        try {
            DB::transaction(function () use ($email, $plainPassword, $firstName, $lastName, $phone) {
                // Create user account exactly like the form
                $user = User::create([
                    'name' => $firstName . ' ' . $lastName,
                    'email' => $email,
                    'password' => Hash::make($plainPassword),
                    'phone' => $phone,
                    'status' => 'active',
                ]);

                $this->info("User created with ID: {$user->id}");
                $this->info("Password hash: " . substr($user->password, 0, 20) . "...");

                // Assign customer_portal role
                $customerRole = Role::where('name', 'customer_portal')->first();
                if ($customerRole) {
                    $user->roles()->attach($customerRole->id, [
                        'is_active' => true,
                        'assigned_at' => now(),
                    ]);
                    $this->info("Customer role assigned");
                } else {
                    $this->error("Customer role not found!");
                }

                // Create customer record
                $customer = Customer::create([
                    'user_id' => $user->id,
                    'first_name' => $firstName,
                    'last_name' => $lastName,
                    'email' => $email,
                    'phone' => $phone,
                    'address' => '123 Test St',
                    'city' => 'Test City',
                    'state' => 'CA',
                    'zip_code' => '12345',
                    'status' => 'active',
                ]);

                $this->info("Customer created with ID: {$customer->id}");
            });

            // Now test authentication immediately
            $this->info("\n--- Testing authentication immediately ---");
            
            $user = User::where('email', $email)->first();
            if ($user) {
                $this->info("User found: {$user->name} ({$user->email})");
                $this->info("User ID: {$user->id}");
                $this->info("User Status: {$user->status}");
                $this->info("Password Hash: " . substr($user->password, 0, 30) . "...");
                
                // Check password
                if (Hash::check($plainPassword, $user->password)) {
                    $this->info("✅ Password matches!");
                } else {
                    $this->error("❌ Password does NOT match!");
                }
                
                // Check roles
                $roles = $user->roles()->where('user_roles.is_active', true)->pluck('name')->toArray();
                $this->info("Roles: " . implode(', ', $roles));
                
                // Test Laravel authentication
                if (Auth::attempt(['email' => $email, 'password' => $plainPassword])) {
                    $this->info("✅ Authentication successful!");
                    Auth::logout(); // Clean up
                } else {
                    $this->error("❌ Authentication failed!");
                }
            } else {
                $this->error("User not found!");
            }

        } catch (\Exception $e) {
            $this->error("Error: " . $e->getMessage());
            $this->error("Trace: " . $e->getTraceAsString());
        }
    }
}
