<?php

declare(strict_types=1);

final class Mnotify
{
    public static function sendSms(array $cfg, string $to, string $message): array
    {
        $to = trim($to);
        if ($to === '') {
            throw new InvalidArgumentException('Recipient phone is required');
        }

        $key = (string)($cfg['api_key'] ?? '');
        $senderId = (string)($cfg['sender_id'] ?? '');
        if (trim($key) === '') {
            throw new InvalidArgumentException('mNotify API key is required');
        }
        if (trim($senderId) === '') {
            throw new InvalidArgumentException('mNotify sender_id is required');
        }

        $payload = [
            'recipient' => [$to],
            'sender' => $senderId,
            'message' => $message,
            'is_schedule' => false,
            'schedule_date' => '',
        ];

        $url = 'https://api.mnotify.com/api/sms/quick?key=' . rawurlencode($key);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS => json_encode($payload),
        ]);

        $resp = curl_exec($ch);
        if ($resp === false) {
            $err = curl_error($ch);
            curl_close($ch);
            throw new RuntimeException('mNotify error: ' . $err);
        }
        $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $decoded = null;
        try {
            $decoded = json_decode((string)$resp, true, 512, JSON_THROW_ON_ERROR);
        } catch (Throwable $e) {
            $decoded = null;
        }

        if ($status >= 400) {
            $msg = is_array($decoded) && isset($decoded['message']) ? (string)$decoded['message'] : (string)$resp;
            throw new RuntimeException('mNotify HTTP ' . $status . ': ' . $msg);
        }
        if (is_array($decoded) && (($decoded['status'] ?? null) === 'error')) {
            $code = isset($decoded['code']) ? (string)$decoded['code'] : '';
            $msg = isset($decoded['message']) ? (string)$decoded['message'] : 'mNotify error';
            throw new RuntimeException('mNotify ' . ($code !== '' ? ($code . ': ') : '') . $msg);
        }

        return ['http_status' => $status, 'raw' => $resp, 'decoded' => $decoded, 'payload' => $payload];
    }
}
