<?php
/**
 * WisChat · SDK PHP mínimo (sin dependencias).
 *   $wc = new WisChat("http://v2.wis.chat", "TU_TOKEN", "TID"); // TID = phone_number_id o id de la línea
 *   $wc->texto("593999999999", "Hola 👋");
 *   $wc->plantilla("593999999999", "mi_plantilla", ["Juan","#123"]);
 */
class WisChat
{
    public function __construct(private string $baseUrl, private string $token, private string $tid) {}

    public function texto(string $to, string $body): array
    {
        return $this->enviar(["to" => $to, "type" => "text", "text" => ["body" => $body]]);
    }

    public function plantilla(string $to, string $nombre, array $vars = [], string $idioma = "es"): array
    {
        $params = array_map(fn($v) => ["type" => "text", "text" => $v], $vars);
        $tpl = ["name" => $nombre, "language" => ["code" => $idioma]];
        if ($params) $tpl["components"] = [["type" => "body", "parameters" => $params]];
        return $this->enviar(["to" => $to, "type" => "template", "template" => $tpl]);
    }

    public function enviar(array $payload): array
    {
        $ch = curl_init(rtrim($this->baseUrl, "/") . "/api/v22.0/" . $this->tid . "/messages");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $this->token, "Content-Type: application/json"],
        ]);
        $resp = curl_exec($ch);
        $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return ["http" => $http, "body" => json_decode($resp, true)];
    }
}