<?php

namespace App\Console\Commands;

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

class ShowCustomerUserIntegration extends Command
{
    protected $signature = 'show:customer-user-integration';
    protected $description = 'Show how customers and users are integrated';

    public function handle()
    {
        $this->info('=== CUSTOMER-USER INTEGRATION REPORT ===');
        $this->newLine();

        // Show customers with user accounts
        $customersWithUsers = Customer::whereNotNull('user_id')->with('user')->get();
        $this->info("Customers with User Accounts ({$customersWithUsers->count()}):");
        foreach ($customersWithUsers as $customer) {
            $this->line("  • {$customer->full_name} ({$customer->email}) → User ID: {$customer->user_id}");
        }
        $this->newLine();

        // Show customers without user accounts
        $customersWithoutUsers = Customer::whereNull('user_id')->get();
        $this->warn("Customers without User Accounts ({$customersWithoutUsers->count()}):");
        foreach ($customersWithoutUsers->take(5) as $customer) {
            $this->line("  • {$customer->full_name} ({$customer->email})");
        }
        if ($customersWithoutUsers->count() > 5) {
            $this->line("  ... and " . ($customersWithoutUsers->count() - 5) . " more");
        }
        $this->newLine();

        // Show users with customer portal role
        $customerUsers = User::whereHas('roles', function($q) {
            $q->where('name', 'customer_portal');
        })->with('customer')->get();
        
        $this->info("Users with Customer Portal Role ({$customerUsers->count()}):");
        foreach ($customerUsers as $user) {
            $customerInfo = $user->customer ? 
                "→ Customer: {$user->customer->full_name}" : 
                "→ No Customer Record";
            $this->line("  • {$user->name} ({$user->email}) {$customerInfo}");
        }
        $this->newLine();

        // Show statistics
        $this->info('=== STATISTICS ===');
        $this->table(['Metric', 'Count'], [
            ['Total Customers', Customer::count()],
            ['Customers with User Accounts', Customer::whereNotNull('user_id')->count()],
            ['Users with Customer Role', User::whereHas('roles', fn($q) => $q->where('name', 'customer_portal'))->count()],
            ['Total Users', User::count()],
        ]);

        return 0;
    }
}
