<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Plivo\RestClient;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UpdateDidLogs extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'update:did-log';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update DID log with area codes from Plivo';

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

        try {
            $auth_id = env('PLIVO_AUTH_ID');
            $auth_token = env('PLIVO_AUTH_TOKEN');

            $client = new RestClient($auth_id, $auth_token);

            $numbers = $client->numbers->list();

            foreach ($numbers as $number) {
                $this->info("Number: " . $number->number . " | ID: " . $number->id);

                DB::table('did_log')
                    ->where('cli', $number->number)
                    ->update(['area_code' => $number->id]);
            }

            $this->info('DID log update completed successfully.');
        } catch (\Plivo\Exceptions\PlivoRestException $e) {
            $this->error("Error: " . $e->getMessage());
            Log::error("Plivo API error: " . $e->getMessage());
            return 1;
        } catch (\Exception $e) {
            $this->error("Unexpected error: " . $e->getMessage());
            Log::error("Unexpected error in UpdateDidLogCommand: " . $e->getMessage());
            return 1;
        }

        return 0;
    }
}
