<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

class TestSmtp extends Command
{
    protected $signature = 'mail:test {email?}';
    protected $description = 'Test SMTP configuration';

    public function handle()
    {
        $email = $this->argument('email') ?? config('mail.from.address');
        
        $this->info('Current mail configuration:');
        $this->table(
            ['Setting', 'Value'],
            [
                ['Default Mailer', config('mail.default')],
                ['Host', config('mail.mailers.smtp.host')],
                ['Port', config('mail.mailers.smtp.port')],
                ['Encryption', config('mail.mailers.smtp.encryption') ?? 'none'],
                ['Username', config('mail.mailers.smtp.username')],
                ['Password', config('mail.mailers.smtp.password') ? '***SET***' : 'NOT SET'],
                ['From Address', config('mail.from.address')],
                ['From Name', config('mail.from.name')],
            ]
        );

        $this->info("\nSending test email to: {$email}");

        try {
            Mail::raw('This is a test email from CoachPro to verify SMTP configuration.', function ($message) use ($email) {
                $message->to($email)
                    ->subject('CoachPro SMTP Test - ' . now()->format('Y-m-d H:i:s'));
            });

            $this->info('✅ Email sent successfully!');
            return 0;
        } catch (\Exception $e) {
            $this->error('❌ Failed to send email: ' . $e->getMessage());
            
            // Show more details
            if ($this->option('verbose')) {
                $this->line("\nFull error trace:");
                $this->line($e->getTraceAsString());
            }
            
            return 1;
        }
    }
}
