<?php

namespace App\Console\Commands;

use App\Models\Setting;
use App\Services\PaymentService;
use Illuminate\Console\Command;

class DiagnosePayments extends Command
{
    protected $signature = 'payments:diagnose {--fix : Intentar arreglar problemas comunes}';

    protected $description = 'Diagnostica la configuración de métodos de pago';

    public function handle(): int
    {
        $this->info('🔍 Diagnóstico de Configuración de Pagos');
        $this->line('');

        // 1. Check database settings
        $this->info('📦 Configuración en Base de Datos:');
        $this->line('');
        
        $paymentSettings = Setting::where('group', 'payment')->get();
        
        if ($paymentSettings->isEmpty()) {
            $this->error('❌ No hay configuraciones de pago en la base de datos.');
            $this->warn('   Debes configurar los métodos de pago en /admin/settings -> Pasarelas de Pago');
            return 1;
        }
        
        $settingsTable = [];
        foreach ($paymentSettings as $setting) {
            $value = $setting->value;
            $displayValue = $value;
            
            // Mask secrets for display
            if (str_contains($setting->key, 'secret')) {
                if (!empty($value)) {
                    // Try to decrypt
                    try {
                        $decrypted = decrypt($value);
                        $displayValue = '🔐 [ENCRYPTED - ' . strlen($decrypted) . ' chars]';
                    } catch (\Exception $e) {
                        $displayValue = '⚠️ [RAW - ' . strlen($value) . ' chars]';
                    }
                } else {
                    $displayValue = '❌ [VACÍO]';
                }
            } elseif (is_bool($value)) {
                $displayValue = $value ? '✅ Sí' : '❌ No';
            } elseif (is_null($value) || $value === '') {
                $displayValue = '❌ [VACÍO]';
            } elseif (str_contains($setting->key, 'client_id') || str_contains($setting->key, 'key')) {
                // Mask part of keys for security
                if (strlen($value) > 15) {
                    $displayValue = substr($value, 0, 12) . '...' . substr($value, -4);
                }
            }
            
            $settingsTable[] = [$setting->key, $displayValue];
        }
        
        $this->table(['Setting', 'Value'], $settingsTable);
        $this->line('');

        // 2. Check PaymentService
        $this->info('🔧 Estado del PaymentService:');
        $this->line('');
        
        $paymentService = app(PaymentService::class);
        $config = $paymentService->verifyConfiguration();
        
        foreach ($config as $gateway => $status) {
            $icon = $status['enabled'] ? ($status['configured'] ? '✅' : '⚠️') : '⭕';
            $enabledText = $status['enabled'] ? 'Habilitado' : 'Deshabilitado';
            $configuredText = $status['configured'] ? 'Configurado' : 'Sin configurar';
            
            $this->line("  {$icon} {$gateway}: {$enabledText}, {$configuredText}");
            
            if ($status['error']) {
                $this->error("     └── Error: {$status['error']}");
            }
        }
        $this->line('');

        // 3. Check available methods
        $this->info('💳 Métodos de Pago Disponibles:');
        $methods = $paymentService->getAvailableMethods();
        
        if (empty($methods)) {
            $this->error('❌ No hay métodos de pago disponibles para los usuarios.');
            $this->warn('   Los usuarios no podrán completar pagos.');
        } else {
            foreach ($methods as $method) {
                $this->line("  ✅ {$method['name']} ({$method['id']})");
            }
        }
        $this->line('');

        // 4. Try actual initialization
        $this->info('🧪 Prueba de Inicialización:');
        $this->line('');
        
        // Test Stripe
        if ($config['stripe']['enabled']) {
            $this->line('  Probando Stripe...');
            try {
                $stripeSecret = Setting::get('stripe_secret');
                if ($stripeSecret) {
                    $decrypted = null;
                    try {
                        $decrypted = decrypt($stripeSecret);
                        $this->info('    ✅ Secret descifrado correctamente');
                    } catch (\Exception $e) {
                        $this->warn('    ⚠️ No se pudo descifrar, probando valor directo');
                        $decrypted = $stripeSecret;
                    }
                    
                    if (str_starts_with($decrypted, 'sk_')) {
                        $this->info('    ✅ Formato de clave válido (sk_...)');
                    } else {
                        $this->error('    ❌ Formato de clave inválido. Debe empezar con sk_test_ o sk_live_');
                    }
                }
            } catch (\Exception $e) {
                $this->error('    ❌ Error: ' . $e->getMessage());
            }
        }
        
        // Test PayPal
        if ($config['paypal']['enabled']) {
            $this->line('  Probando PayPal...');
            try {
                $paypalClientId = Setting::get('paypal_client_id');
                $paypalSecret = Setting::get('paypal_secret');
                
                if ($paypalClientId) {
                    $this->info('    ✅ Client ID presente (' . strlen($paypalClientId) . ' chars)');
                }
                
                if ($paypalSecret) {
                    try {
                        $decrypted = decrypt($paypalSecret);
                        $this->info('    ✅ Secret descifrado correctamente (' . strlen($decrypted) . ' chars)');
                    } catch (\Exception $e) {
                        $this->warn('    ⚠️ No se pudo descifrar el secret: ' . $e->getMessage());
                    }
                }
            } catch (\Exception $e) {
                $this->error('    ❌ Error: ' . $e->getMessage());
            }
        }
        
        $this->line('');

        // 5. Recommendations
        $this->info('💡 Recomendaciones:');
        $this->line('');
        
        $hasIssues = false;
        
        if (!$config['stripe']['enabled'] && !$config['paypal']['enabled'] && !$config['bank_transfer']['enabled']) {
            $this->warn('  • Habilita al menos un método de pago en /admin/settings');
            $hasIssues = true;
        }
        
        if ($config['stripe']['enabled'] && !$config['stripe']['configured']) {
            $this->warn('  • Stripe está habilitado pero falta configuración.');
            $this->warn('    Ingresa tu clave pública (pk_...) y secreta (sk_...) en /admin/settings');
            $hasIssues = true;
        }
        
        if ($config['paypal']['enabled'] && !$config['paypal']['configured']) {
            $this->warn('  • PayPal está habilitado pero falta configuración.');
            $this->warn('    Ingresa tu Client ID y Secret de PayPal en /admin/settings');
            $hasIssues = true;
        }
        
        if (!$hasIssues) {
            $this->info('  ✅ La configuración parece correcta.');
        }
        
        $this->line('');
        
        // Fix option
        if ($this->option('fix')) {
            $this->fixCommonIssues();
        }
        
        return 0;
    }
    
    protected function fixCommonIssues(): void
    {
        $this->info('🔧 Intentando corregir problemas comunes...');
        $this->line('');
        
        // Ensure bank transfer is enabled as fallback
        $bankTransferEnabled = Setting::get('bank_transfer_enabled');
        if ($bankTransferEnabled === null) {
            Setting::set('bank_transfer_enabled', true, 'payment');
            $this->info('  ✅ Habilitada transferencia bancaria como respaldo');
        }
        
        $this->line('');
        $this->info('Listo. Ejecuta de nuevo sin --fix para verificar.');
    }
}
