<?php

namespace App\Console\Commands;

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

class FixPhoneNumbersCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'users:fix-phone-numbers {--dry-run : Show what would be changed without making actual changes}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix phone numbers by adding + prefix to numbers starting with 966';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $dryRun = $this->option('dry-run');

        if ($dryRun) {
            $this->info('Running in DRY RUN mode - no changes will be made');
        }

        $this->info('Starting phone number fix process...');

        // Get users with phone numbers starting with '966' but not with '+966'
        $users = User::where('phone_number', 'like', '966%')
            ->where('phone_number', 'not like', '+966%')
            ->get();

        if ($users->isEmpty()) {
            $this->info('No phone numbers need fixing.');

            return Command::SUCCESS;
        }

        $this->info("Found {$users->count()} phone numbers to fix:");

        $progressBar = $this->output->createProgressBar($users->count());
        $progressBar->start();

        $updated = 0;
        $errors = 0;

        foreach ($users as $user) {
            try {
                $oldPhoneNumber = $user->phone_number;
                $newPhoneNumber = '+'.$oldPhoneNumber;

                $this->newLine();
                $this->line("User ID {$user->id}: '{$oldPhoneNumber}' → '{$newPhoneNumber}'");

                if (! $dryRun) {
                    $user->update(['phone_number' => $newPhoneNumber]);
                    $updated++;
                } else {
                    $updated++; // Count what would be updated in dry run
                }

                $progressBar->advance();
            } catch (\Exception $e) {
                $errors++;
                $this->newLine();
                $this->error("Error updating user {$user->id}: ".$e->getMessage());
                $progressBar->advance();
            }
        }

        $progressBar->finish();
        $this->newLine(2);

        if ($dryRun) {
            $this->info('DRY RUN RESULTS:');
            $this->info("Would update: {$updated} phone numbers");
            $this->info("Errors encountered: {$errors}");
            $this->info('Run without --dry-run to apply changes');
        } else {
            $this->info('RESULTS:');
            $this->info("Updated: {$updated} phone numbers");
            $this->info("Errors: {$errors}");
        }

        return Command::SUCCESS;
    }
}
