<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Api\Sms;
use Throwable;

class SmsTest extends Command
{
    protected $signature = 'sms:test {phone?} {message?}';
    protected $description = 'Send test SMS via Sms class (with deep diagnostics)';

    private function diagPath(): string
    {
        return function_exists('storage_path')
            ? storage_path('logs/sms_test.log')
            : __DIR__ . '/../../../storage/logs/sms_test.log';
    }

    private function dlog(string $level, string $msg, array $ctx = []): void
    {
        $path = $this->diagPath();
        $dir = dirname($path);
        if (!is_dir($dir)) {
            @mkdir($dir, 0777, true);
        }

        $line = json_encode([
            'ts' => date('c'),
            'level' => $level,
            'msg' => $msg,
            'ctx' => $ctx,
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        @file_put_contents($path, $line . PHP_EOL, FILE_APPEND);
    }

    public function handle(): int
    {
        $phone = $this->argument('phone') ?? '+998333013332';
        $message = $this->argument('message') ?? 'Ishladi Polat';
        $phoneDigits = (int)preg_replace('/[^0-9]/', '', (string)$phone);

        $this->info("Sending SMS to: {$phoneDigits}");
        $this->info("Message: {$message}");
        $this->line("Diag log: " . $this->diagPath());

        $this->dlog('info', 'sms:test started', [
            'pid' => getmypid(),
            'cwd' => getcwd(),
            'php' => PHP_VERSION,
            'app_env' => env('APP_ENV'),
            'log_path' => $this->diagPath(),
            'phone' => $phoneDigits,
        ]);

        // ENV snapshot (mask password)
        $envSnap = [
            'SMS_URL' => env('SMS_URL'),
            'SMS_USERNAME' => env('SMS_USERNAME'),
            'SMS_PASSWORD' => env('SMS_PASSWORD') ? '***set***' : null,
        ];
        $this->dlog('info', 'env snapshot', $envSnap);

        try {
            $sms = new Sms();

    
            $result = $sms->send($phoneDigits, $message);

            if (is_array($result)) {
                $ok = (bool)($result['ok'] ?? false);
                $this->dlog($ok ? 'info' : 'error', 'send() returned array', $result);

                $this->line("HTTP: " . ($result['http_code'] ?? 'n/a'));
                $this->line("CURL errno: " . ($result['curl_errno'] ?? 'n/a'));
                $this->line("CURL error: " . ($result['curl_error'] ?? 'n/a'));
                $this->line("Response (head): " . ($result['response_head'] ?? 'n/a'));

                if ($ok) {
                    $this->info("SMS send SUCCESS");
                    return self::SUCCESS;
                }

                $this->error("SMS send FAILED (see sms_test.log)");
                return self::FAILURE;
            }

            $ok = (bool)$result;
            $this->dlog($ok ? 'info' : 'error', 'send() returned bool', ['ok' => $ok]);

            if ($ok) {
                $this->info("SMS send SUCCESS");
                return self::SUCCESS;
            }

            $this->error("SMS send FAILED (see sms_test.log)");
            return self::FAILURE;

        } catch (Throwable $e) {
            $this->dlog('error', 'EXCEPTION', [
                'message' => $e->getMessage(),
                'class' => get_class($e),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => substr($e->getTraceAsString(), 0, 4000),
            ]);

            $this->error("EXCEPTION: " . $e->getMessage());
            $this->line("Where: " . $e->getFile() . ":" . $e->getLine());
            return self::FAILURE;
        }
    }
}