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

class Twilio implements SmsDriver {
    public function label(): string { return 'Twilio'; }
    public function helpText(): string { return 'Find your Account SID and Auth Token in the Twilio Console.'; }
    public function requiredFields(): array { return ['accountSid'=>'Account SID','authToken'=>'Auth Token','from'=>'From Number']; }
    public function send(string $to, string $message, array $config): array {
        $sid = $config['accountSid']??''; $token = $config['authToken']??''; $from = $config['from']??'';
        if(!$sid||!$token||!$from) return ['success'=>false,'error'=>'Missing credentials.'];
        $url = "https://api.twilio.com/2010-04-01/Accounts/{$sid}/Messages.json";
        $data = http_build_query(['To'=>$to,'From'=>$from,'Body'=>$message]);
        return $this->curl($url, 'POST', $data, ['Authorization: Basic '.base64_encode("{$sid}:{$token}")]);
    }
    private function curl(string $url, string $method, string $body, array $headers = []): array {
        $ch = curl_init(); curl_setopt_array($ch, [CURLOPT_URL=>$url, CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>15, CURLOPT_HTTPHEADER=>$headers]);
        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)];
    }
}