<?php
class TwilioWhatsApp
{
  private $sid;
  private $token;

  public function __construct()
  {
    $this->sid = TWILIO_ACCOUNT_SID;
    $this->token = TWILIO_AUTH_TOKEN;
  }

  public function send($toE164, $message, $mediaUrl = null)
  {
    $url = "https://api.twilio.com/2010-04-01/Accounts/{$this->sid}/Messages.json";

    $data = [
      'From' => TWILIO_WHATSAPP_FROM,
      'To' => "whatsapp:$toE164",
      'Body' => $message,
      'StatusCallback' => rtrim(BASE_URL, '/') . '/webhooks/status'
    ];
    if ($mediaUrl) {
      $data['MediaUrl'] = $mediaUrl;
    }

    $ch = curl_init($url);
    curl_setopt_array($ch, [
      CURLOPT_POST => true,
      CURLOPT_POSTFIELDS => http_build_query($data),
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_USERPWD => $this->sid . ":" . $this->token
    ]);
    $res = curl_exec($ch);
    if ($res === false)
      throw new Exception('cURL error: ' . curl_error($ch));
    $http = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);

    if ($http < 200 || $http >= 300)
      throw new Exception("Twilio HTTP $http: $res");
    return json_decode($res, true);
  }
}
