<?php
declare(strict_types=1);
namespace PpPhp\Plugins\SmsDrivers;
use PpPhp\Core\SmsDriver;

class NepalSparrow implements SmsDriver
{
    public function label(): string { return 'Sparrow SMS (Nepal)'; }
    public function helpText(): string { return 'Get your API token from Sparrow SMS dashboard. Identity is required. Base URL: api.sparrowsms.com/v2/'; }

    public function requiredFields(): array
    {
        return [
            'token'    => 'Auth Token',
            'identity' => 'Identity',
            'from'     => 'Sender ID',
        ];
    }

    public function send(string $to, string $message, array $config): array
    {
        $token    = $config['token']    ?? '';
        $identity = $config['identity'] ?? '';
        $from     = $config['from']     ?? '';

        if (empty($token) || empty($identity) || empty($from)) {
            return ['success' => false, 'error' => 'Token, Identity, and Sender ID are required.'];
        }

        // Official endpoint: http://api.sparrowsms.com/v2/sms/
        $url  = 'http://api.sparrowsms.com/v2/sms/';
        $data = http_build_query([
            'token'    => $token,
            'identity' => $identity,
            'from'     => $from,
            'to'       => $to,
            'text'     => $message,
        ]);

        return $this->curl($url, 'POST', $data);
    }

    private function curl(string $url, string $method, string $body): array
    {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $body,
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode >= 200 && $httpCode < 300) return ['success' => true];
        return ['success' => false, 'error' => "HTTP {$httpCode}: " . substr($response, 0, 200)];
    }
}