<?php

namespace App\Console\Commands;

use App\Models\Client;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class UpdateClosedCustomerUseridCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'update:closed-customer-userid';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update userid of closed customers older than 2 months by appending client ID';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('Starting to update closed customer userids...');

        // Calculate the date 2 months ago
        $twoMonthsAgo = Carbon::now()->subMonths(2);

        // Get closed customers that are 2 months or older
        $closedCustomers = Client::withTrashed()
            ->whereNotNull('deleted_at')
            ->where('deleted_at', '<=', $twoMonthsAgo)
            ->get();

        $this->info("Found {$closedCustomers->count()} closed customers older than 2 months.");

        $updated = 0;
        $skipped = 0;
        $errors = 0;

        foreach ($closedCustomers as $customer) {
            try {
                // Check if userid already ends with the client ID
                $clientIdSuffix = '_' . $customer->id;
                if (substr($customer->userid, -strlen($clientIdSuffix)) === $clientIdSuffix) {
                    $this->warn("Skipping customer ID {$customer->id} - userid already ends with client ID: {$customer->userid}");
                    $skipped++;
                    continue;
                }

                // Create new userid by appending client ID
                $newUserid = $customer->userid . '_' . $customer->id;

                // Check if the new userid already exists
                $existingCustomer = Client::withTrashed()
                    ->where('userid', $newUserid)
                    ->where('id', '!=', $customer->id)
                    ->first();

                if ($existingCustomer) {
                    $this->warn("Skipping customer ID {$customer->id} - userid '{$newUserid}' already exists for customer ID {$existingCustomer->id}");
                    $skipped++;
                    continue;
                }

                // Update the userid
                DB::table('clients')
                    ->where('id', $customer->id)
                    ->update(['userid' => $newUserid]);

                $this->info("Updated customer ID {$customer->id}: {$customer->userid} -> {$newUserid}");
                $updated++;

            } catch (\Exception $e) {
                $this->error("Error updating customer ID {$customer->id}: " . $e->getMessage());
                $errors++;
            }
        }

        $this->info("\n=== Summary ===");
        $this->info("Total processed: {$closedCustomers->count()}");
        $this->info("Updated: {$updated}");
        $this->info("Skipped: {$skipped}");
        $this->info("Errors: {$errors}");

        return Command::SUCCESS;
    }
}

