<?php

namespace App\Console\Commands;

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

class UpdateBNRRates extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'currencies:update-bnr
                            {--force : Force update even if rates were updated today}
                            {--currency= : Update specific currency code}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update currency exchange rates from BNR (Banca Națională a României)';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('🏛️ Actualizare cursuri valutare BNR...');

        try {
            $specificCurrency = $this->option('currency');
            $force = $this->option('force');

            if ($specificCurrency) {
                $currency = Currency::where('code', strtoupper($specificCurrency))->first();
                if (!$currency) {
                    $this->error("❌ Moneda cu codul '{$specificCurrency}' nu a fost găsită.");
                    return Command::FAILURE;
                }

                if ($currency->is_base) {
                    $this->warn("⚠️ Moneda {$currency->code} este moneda de bază - nu necesită actualizare.");
                    return Command::SUCCESS;
                }

                $this->info("📊 Actualizez cursul pentru {$currency->name} ({$currency->code})...");
                $updated = Currency::updateBNRRates([$currency->code]);
            } else {
                $this->info('📊 Actualizez toate cursurile valutare...');
                $updated = Currency::updateBNRRates(null, $force);
            }

            if ($updated > 0) {
                $this->info("✅ {$updated} monede au fost actualizate cu succes!");

                // Afișează cursurile actualizate
                $this->table(
                    ['Monedă', 'Cod', 'Curs BNR', 'Actualizat'],
                    Currency::where('is_active', true)
                           ->where('is_base', false)
                           ->whereNotNull('bnr_rate')
                           ->get()
                           ->map(function ($currency) {
                               return [
                                   $currency->name,
                                   $currency->code,
                                   number_format($currency->bnr_rate, 4),
                                   $currency->last_updated ? $currency->last_updated->format('d.m.Y H:i') : '-'
                               ];
                           })
                           ->toArray()
                );
            } else {
                $this->warn('⚠️ Nu au fost actualizate cursuri. Toate cursurile sunt deja la zi.');
            }

            return Command::SUCCESS;
        } catch (\Exception $e) {
            $this->error('❌ Eroare la actualizarea cursurilor BNR: ' . $e->getMessage());
            return Command::FAILURE;
        }
    }
}
