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

class SmsPasal implements SmsDriver
{
    public function label(): string { return 'SmsPasal (ThemeNepal)'; }
    public function helpText(): string { return 'Enter your API key, campaign ID, route ID, and sender ID from SmsPasal dashboard.'; }

    public function requiredFields(): array
    {
        return [
            'apiKey'   => 'API Key',
            'campaign' => 'Campaign ID',
            'routeid'  => 'Route ID',
            'from'     => 'Sender ID',
        ];
    }

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

        if (empty($apiKey) || empty($campaign) || empty($routeid) || empty($from)) {
            return ['success' => false, 'error' => 'API Key, Campaign ID, Route ID, and Sender ID are required.'];
        }

        // Official endpoint
        $url  = 'https://sms.smspasal.com/smsapi/index.php';
        $data = http_build_query([
            'key'      => $apiKey,
            'campaign' => $campaign,
            'routeid'  => $routeid,
            'type'     => 'text',
            'contacts' => $to,
            'senderid' => $from,
            'msg'      => $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);

        if ($httpCode >= 200 && $httpCode < 300) return ['success' => true];
        return ['success' => false, 'error' => "HTTP {$httpCode}: " . substr($response, 0, 200)];
    }
}