<?php

namespace App\Modules\Twilio\Commands;

use Illuminate\Console\Command;
use App\Modules\Twilio\Services\TwilioServiceInterface;
use App\Modules\Twilio\Services\TwilioAuthService;

class TestTwilioSMS extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'twilio:test-sms {number} {message?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Test Twilio SMS functionality';

    /**
     * Execute the console command.
     */
    public function handle(TwilioServiceInterface $twilioService, TwilioAuthService $authService)
    {
        $phoneNumber = $this->argument('number');
        $message = $this->argument('message') ?? 'This is a test SMS from Seraph3 Twilio module.';

        $this->info('Testing Twilio SMS functionality...');
        $this->line('Phone Number: ' . $phoneNumber);
        $this->line('Message: ' . $message);

        // Check if Twilio is enabled
        if (!$authService->isEnabled()) {
            $this->error('Twilio is not enabled or credentials are invalid.');
            $this->line('Please check your Twilio configuration in the admin settings.');
            return 1;
        }

        $this->info('Twilio is enabled. Testing connection...');

        // Test connection
        $connectionResult = $authService->testConnection();
        if (!$connectionResult['success']) {
            $this->error('Twilio connection failed: ' . $connectionResult['error']);
            return 1;
        }

        $this->info('Twilio connection successful!');
        $this->line('Account: ' . ($connectionResult['account']['friendly_name'] ?? 'Unknown'));

        // Validate phone number
        if (!$twilioService->validatePhoneNumber($phoneNumber)) {
            $this->error('Invalid phone number format: ' . $phoneNumber);
            return 1;
        }

        $formattedNumber = $twilioService->formatPhoneNumber($phoneNumber);
        $this->info('Phone number validated and formatted: ' . $formattedNumber);

        // Send test SMS
        $this->info('Sending test SMS...');
        $result = $twilioService->testSMS($phoneNumber, $message);

        if ($result['success']) {
            $this->info('SMS sent successfully!');
            $this->line('Message SID: ' . $result['message_sid']);
            $this->line('Status: ' . $result['status']);
            $this->line('To: ' . $result['to']);
            $this->line('From: ' . $result['from']);
            return 0;
        } else {
            $this->error('Failed to send SMS: ' . $result['error']);
            return 1;
        }
    }
} 