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

class HttpDriver implements SmsDriver {
    public function label(): string { return 'Generic HTTP'; }
    public function helpText(): string { return 'Configure any SMS gateway that accepts HTTP requests.'; }
    public function requiredFields(): array { return ['url'=>'API URL','method'=>'Method (POST/GET)','toParam'=>'"to" param name','msgParam'=>'"message" param name','fromParam'=>'"from" param name','extraParams'=>'Extra params (key=value, comma sep)']; }
    public function send(string $to, string $message, array $config): array {
        $url=$config['url']??''; $method=strtoupper($config['method']??'POST'); $toParam=$config['toParam']??'to'; $msgParam=$config['msgParam']??'message'; $fromParam=$config['fromParam']??'from'; $extra=$config['extraParams']??''; $from=$config['from']??'';
        if(!$url) return ['success'=>false,'error'=>'API URL required.'];
        $params=[$toParam=>$to,$msgParam=>$message];
        if($from&&$fromParam) $params[$fromParam]=$from;
        if($extra) foreach(explode(',',$extra) as $p) if(str_contains($p,'=')){[$k,$v]=explode('=',trim($p),2); $params[trim($k)]=str_replace(['{to}','{message}','{from}'],[$to,$message,$from],trim($v));}
        $body = $method==='GET' ? '' : http_build_query($params);
        if($method==='GET') $url .= (str_contains($url,'?')?'&':'?').http_build_query($params);
        return $this->curl($url, $method, $body);
    }
    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]);
        if($method==='POST'){curl_setopt($ch,CURLOPT_POST,true);curl_setopt($ch,CURLOPT_POSTFIELDS,$body);}
        $r=curl_exec($ch); $http=curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch);
        if($http>=200&&$http<300) return ['success'=>true];
        return ['success'=>false,'error'=>"HTTP $http: ".substr($r,0,200)];
    }
}