<?php
/**
 * Tavros Connect — WhatsApp Business API client for PHP 7.0+ (needs the curl + json extensions).
 * Download page / API keys: https://tavrosconnect.com/developers.php
 *
 * Every message sent through this client also appears in your Tavros Connect Chats,
 * and every incoming message / delivery status is forwarded to your webhook.
 *
 * SENDING
 *   require 'TavrosConnect.php';
 *   $tc = new TavrosConnect('tc_live_xxx', 'PHONE_NUMBER_ID');            // both from Developers page
 *   $r  = $tc->sendTemplate('9876543210', 'payment_receipt_v1', array('Priya', '2499', '07 Oct 2026', 'RCPT-1042'));
 *   if ($r['ok']) { $wamid = $r['wamid']; } else { error_log($r['error']); }
 *
 *   $tc->sendText('919876543210', 'Your order is ready');                  // only within 24 h of their last message
 *   $up = $tc->uploadMedia('/path/receipt.pdf');                           // → $up['id']
 *   $tc->sendTemplate($to, 'receipt_pdf', $params, 'en', array('header_document' => array('id' => $up['id'], 'filename' => 'Receipt.pdf')));
 *   $tc->send(array('to' => $to, 'type' => 'interactive', 'interactive' => array(...)));   // any Cloud API body
 *
 * CUSTOMER NAMES (so Tavros Connect Chats show names instead of bare numbers)
 *   $tc->withName('Rahul Patil')->sendTemplate('9876543210', ...);          // name travels with this one message
 *   $tc->saveContact('9876543210', 'Rahul Patil', array('members'));        // or save/update anytime
 *   $tc->saveContacts(array(array('phone' => '9876543210', 'name' => 'Rahul Patil'), ...));   // bulk, ≤ 1000 per call
 *
 *   Every call returns: array('ok' => bool, 'status' => HTTP code, 'wamid' => ?string, 'id' => ?string,
 *                             'error' => ?string, 'error_code' => ?int, 'data' => decoded response)
 *   Calls never throw.
 *
 * RECEIVING (your webhook URL — see webhook_example.php)
 *   TavrosConnect::handleWebhook('YOUR_VERIFY_TOKEN', 'YOUR_SIGNING_SECRET', function (array $e) {
 *       if ($e['type'] === 'message') { ... $e['from'], $e['text'], $e['message'] ... }
 *       if ($e['type'] === 'status')  { ... $e['wamid'], $e['status'] (sent|delivered|read|failed), $e['error'] ... }
 *   });
 */
class TavrosConnect
{
    const DEFAULT_BASE_URL = 'https://tavrosconnect.com/api/v1/';
    const VERSION = '1.2';

    /** @var int Retries after a 429 "rate_limited" (waits Retry-After each time). 0 = never retry. */
    public $maxRetries = 3;
    /** @var int Longest Retry-After (seconds) worth waiting for; longer ones are returned as errors. */
    public $maxRetryWait = 30;

    private $nextName = null;
    private $apiKey;
    private $phoneNumberId;
    private $baseUrl;
    private $timeout;

    /**
     * @param string      $apiKey        Tavros Connect API key (tc_live_…, or tc_test_… for test mode: nothing is sent)
     * @param string      $phoneNumberId WhatsApp phone number ID (Developers page)
     * @param string|null $baseUrl       Override only for testing
     * @param int         $timeout       Seconds per request
     */
    public function __construct($apiKey, $phoneNumberId, $baseUrl = null, $timeout = 20)
    {
        $this->apiKey = (string) $apiKey;
        $this->phoneNumberId = (string) $phoneNumberId;
        $this->baseUrl = rtrim($baseUrl ? (string) $baseUrl : self::DEFAULT_BASE_URL, '/') . '/';
        $this->timeout = (int) $timeout;
    }

    // ------------------------------------------------------------------ sending

    /** Send any WhatsApp Cloud API message body ("to", "type", …). */
    public function send(array $message)
    {
        if (isset($message['to'])) {
            $p = self::normalizePhone($message['to']);
            if ($p === null) { $this->nextName = null; return self::fail('Invalid phone number: ' . $message['to']); }
            $message['to'] = $p;
        }
        $message = array_merge(array('messaging_product' => 'whatsapp', 'recipient_type' => 'individual'), $message);
        return $this->request('POST', $this->phoneNumberId . '/messages', $message);
    }

    /** Free-text message (delivered only within 24 hours of the customer's last message). */
    public function sendText($to, $text, $previewUrl = true)
    {
        return $this->send(array('to' => $to, 'type' => 'text', 'text' => array('body' => (string) $text, 'preview_url' => (bool) $previewUrl)));
    }

    /**
     * Approved template message.
     * $bodyParams: values for {{1}}, {{2}}, … in order.
     * $options:
     *   'header_text'     => 'value for the {{1}} in a text header'
     *   'header_image'    => 'https://…' | array('id' => mediaId)
     *   'header_video'    => 'https://…' | array('id' => mediaId)
     *   'header_document' => array('id' => mediaId, 'filename' => 'Receipt.pdf') | array('link' => 'https://…', 'filename' => …)
     *   'button_url'      => 'suffix for a dynamic URL button' | array(buttonIndex => suffix, …)
     */
    public function sendTemplate($to, $name, array $bodyParams = array(), $language = 'en', array $options = array())
    {
        $components = array();
        foreach (array('image', 'video', 'document') as $kind) {
            if (empty($options['header_' . $kind])) continue;
            $media = $options['header_' . $kind];
            if (is_string($media)) $media = array('link' => $media);
            $components[] = array('type' => 'header', 'parameters' => array(array('type' => $kind, $kind => $media)));
        }
        if (isset($options['header_text']) && $options['header_text'] !== '') {
            $components[] = array('type' => 'header', 'parameters' => array(array('type' => 'text', 'text' => self::cleanParam($options['header_text']))));
        }
        if ($bodyParams) {
            $params = array();
            foreach ($bodyParams as $v) $params[] = array('type' => 'text', 'text' => self::cleanParam($v));
            $components[] = array('type' => 'body', 'parameters' => $params);
        }
        if (isset($options['button_url'])) {
            $buttons = is_array($options['button_url']) ? $options['button_url'] : array(0 => $options['button_url']);
            foreach ($buttons as $index => $suffix) {
                $components[] = array('type' => 'button', 'sub_type' => 'url', 'index' => (string) $index,
                    'parameters' => array(array('type' => 'text', 'text' => (string) $suffix)));
            }
        }
        $template = array('name' => (string) $name, 'language' => array('code' => (string) $language));
        if ($components) $template['components'] = $components;
        return $this->send(array('to' => $to, 'type' => 'template', 'template' => $template));
    }

    /**
     * Image / video / audio / document / sticker (free-form: 24-hour window applies).
     * $media: media id from uploadMedia(), or a public https link.
     */
    public function sendMedia($to, $type, $media, $caption = null, $filename = null)
    {
        $obj = preg_match('/^\d+$/', (string) $media) ? array('id' => (string) $media) : array('link' => (string) $media);
        if ($caption !== null && $caption !== '' && $type !== 'audio' && $type !== 'sticker') $obj['caption'] = (string) $caption;
        if ($filename !== null && $type === 'document') $obj['filename'] = (string) $filename;
        return $this->send(array('to' => $to, 'type' => $type, $type => $obj));
    }

    /** Show blue ticks for a message you received (and optionally a typing indicator). */
    public function markRead($wamid, $showTyping = false)
    {
        $body = array('messaging_product' => 'whatsapp', 'status' => 'read', 'message_id' => (string) $wamid);
        if ($showTyping) $body['typing_indicator'] = array('type' => 'text');
        return $this->request('POST', $this->phoneNumberId . '/messages', $body);
    }

    // ------------------------------------------------------------------ media & templates

    /** Upload a local file; returns ['ok', 'id', …]. Media ids stay valid for 30 days. */
    public function uploadMedia($filePath, $mime = null, $filename = null)
    {
        if (!is_readable($filePath)) return self::fail('File not readable: ' . $filePath);
        if (!$mime) $mime = function_exists('mime_content_type') ? mime_content_type($filePath) : 'application/octet-stream';
        $fields = array(
            'messaging_product' => 'whatsapp',
            'type' => $mime,
            'file' => new CURLFile($filePath, $mime, $filename ? $filename : basename($filePath)),
        );
        return $this->request('POST', $this->phoneNumberId . '/media', $fields, true);
    }

    /** Upload bytes held in memory (e.g. a generated PDF). */
    public function uploadMediaBytes($bytes, $filename, $mime)
    {
        $tmp = tempnam(sys_get_temp_dir(), 'tcm');
        file_put_contents($tmp, $bytes);
        try {
            return $this->uploadMedia($tmp, $mime, $filename);
        } finally {
            @unlink($tmp);
        }
    }

    /** Info about received media: ['ok', 'data' => ['url', 'mime_type', 'file_size', …]]. */
    public function mediaInfo($mediaId)
    {
        return $this->request('GET', rawurlencode((string) $mediaId));
    }

    /** Download received media; returns ['ok', 'body' => bytes, 'mime' => …]. */
    public function downloadMedia($mediaId)
    {
        $ch = curl_init($this->baseUrl . rawurlencode((string) $mediaId) . '/download');
        curl_setopt_array($ch, array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array('Authorization: Bearer ' . $this->apiKey),
            CURLOPT_TIMEOUT => max(60, $this->timeout),
            CURLOPT_CONNECTTIMEOUT => 10,
        ));
        $raw = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $mime = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        $err = curl_error($ch);
        curl_close($ch);
        if ($raw === false || $status !== 200) {
            $j = json_decode((string) $raw, true);
            return self::fail(isset($j['error']['message']) ? $j['error']['message'] : ($err ? $err : 'HTTP ' . $status), $status);
        }
        return array('ok' => true, 'status' => $status, 'body' => $raw, 'mime' => $mime, 'error' => null);
    }

    /** Template list of a WhatsApp Business Account: ['ok', 'data' => ['data' => [...], 'paging' => …]]. */
    public function templates($wabaId, array $query = array())
    {
        $query = array_merge(array('fields' => 'name,status,category,language,rejected_reason,components', 'limit' => 100), $query);
        return $this->request('GET', rawurlencode((string) $wabaId) . '/message_templates?' . http_build_query($query));
    }

    // ------------------------------------------------------------------ contacts

    /** Name of the person the NEXT message goes to (shown in Tavros Connect Chats): $tc->withName('Rahul')->sendTemplate(...). */
    public function withName($name)
    {
        $name = trim((string) $name);
        $this->nextName = $name !== '' ? $name : null;
        return $this;
    }

    /** Save or update one customer's name (and optional tags) in Tavros Connect. */
    public function saveContact($phone, $name, array $tags = array())
    {
        return $this->saveContacts(array(array('phone' => $phone, 'name' => $name, 'tags' => $tags)));
    }

    /**
     * Save or update many customers (≤ 1000 per call): array(array('phone' => …, 'name' => …, 'tags' => array(…)), …).
     * Result 'data': ['created' => n, 'updated' => n, 'invalid' => n, 'contacts' => [['phone', 'status'], …]].
     */
    public function saveContacts(array $contacts)
    {
        $list = array();
        foreach ($contacts as $c) {
            $p = self::normalizePhone(isset($c['phone']) ? $c['phone'] : '');
            $list[] = array('phone' => $p !== null ? $p : (string) (isset($c['phone']) ? $c['phone'] : ''),
                            'name' => isset($c['name']) ? (string) $c['name'] : null,
                            'tags' => isset($c['tags']) ? array_values((array) $c['tags']) : array());
        }
        return $this->request('POST', 'contacts', array('contacts' => $list));
    }

    // ------------------------------------------------------------------ webhooks

    /** True if $signatureHeader (X-Hub-Signature-256) matches $rawBody signed with $secret. */
    public static function verifySignature($rawBody, $signatureHeader, $secret)
    {
        if ($secret === '' || $signatureHeader === '') return false;
        return hash_equals('sha256=' . hash_hmac('sha256', (string) $rawBody, (string) $secret), (string) $signatureHeader);
    }

    /**
     * Complete webhook endpoint: answers the GET verification, checks the signature,
     * calls $onEvent once per event, then replies 200. Use it as the whole body of your webhook file.
     *
     * $onEvent receives one of:
     *   ['type' => 'message', 'phone_number_id', 'from', 'name', 'wamid', 'text', 'message_type', 'timestamp', 'message' => raw]
     *   ['type' => 'status',  'phone_number_id', 'wamid', 'status', 'recipient', 'error', 'timestamp', 'raw' => raw]
     *   ['type' => <other field, e.g. 'message_template_status_update'>, 'value' => raw]
     */
    public static function handleWebhook($verifyToken, $signingSecret, $onEvent)
    {
        $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
        if ($method === 'GET') {
            // PHP turns "hub.mode" into "hub_mode"
            $mode = isset($_GET['hub_mode']) ? $_GET['hub_mode'] : '';
            $token = isset($_GET['hub_verify_token']) ? (string) $_GET['hub_verify_token'] : '';
            if ($mode === 'subscribe' && $verifyToken !== '' && hash_equals((string) $verifyToken, $token)) {
                header('Content-Type: text/plain');
                echo isset($_GET['hub_challenge']) ? $_GET['hub_challenge'] : '';
                exit;
            }
            http_response_code(403);
            exit;
        }
        $raw = (string) file_get_contents('php://input');
        $sig = isset($_SERVER['HTTP_X_HUB_SIGNATURE_256']) ? $_SERVER['HTTP_X_HUB_SIGNATURE_256'] : '';
        if (!self::verifySignature($raw, $sig, $signingSecret)) {
            error_log('TavrosConnect webhook: bad signature');
            http_response_code(403);
            exit;
        }
        foreach (self::parseWebhook($raw) as $event) {
            try {
                call_user_func($onEvent, $event);
            } catch (Exception $e) {
                error_log('TavrosConnect webhook handler: ' . $e->getMessage());
            } catch (Error $e) {
                error_log('TavrosConnect webhook handler: ' . $e->getMessage());
            }
        }
        http_response_code(200);
        echo 'EVENT_RECEIVED';
        exit;
    }

    /** Flatten a webhook body into simple events (see handleWebhook). */
    public static function parseWebhook($rawBody)
    {
        $data = json_decode((string) $rawBody, true);
        $events = array();
        if (!isset($data['entry']) || !is_array($data['entry'])) return $events;
        foreach ($data['entry'] as $entry) {
            if (empty($entry['changes'])) continue;
            foreach ($entry['changes'] as $change) {
                $field = isset($change['field']) ? $change['field'] : '';
                $value = isset($change['value']) ? $change['value'] : array();
                if ($field !== 'messages') {
                    $events[] = array('type' => $field, 'value' => $value);
                    continue;
                }
                $pnid = isset($value['metadata']['phone_number_id']) ? $value['metadata']['phone_number_id'] : null;
                $names = array();
                if (!empty($value['contacts'])) {
                    foreach ($value['contacts'] as $c) {
                        if (isset($c['wa_id'])) $names[$c['wa_id']] = isset($c['profile']['name']) ? $c['profile']['name'] : null;
                    }
                }
                if (!empty($value['messages'])) {
                    foreach ($value['messages'] as $m) {
                        $type = isset($m['type']) ? $m['type'] : '';
                        $text = null;
                        if ($type === 'text' && isset($m['text']['body'])) $text = $m['text']['body'];
                        elseif ($type === 'button' && isset($m['button']['text'])) $text = $m['button']['text'];
                        elseif ($type === 'interactive') {
                            if (isset($m['interactive']['button_reply']['title'])) $text = $m['interactive']['button_reply']['title'];
                            elseif (isset($m['interactive']['list_reply']['title'])) $text = $m['interactive']['list_reply']['title'];
                        } elseif (isset($m[$type]['caption'])) $text = $m[$type]['caption'];
                        $from = isset($m['from']) ? $m['from'] : null;
                        $events[] = array(
                            'type' => 'message', 'phone_number_id' => $pnid, 'from' => $from,
                            'name' => ($from !== null && isset($names[$from])) ? $names[$from] : null,
                            'wamid' => isset($m['id']) ? $m['id'] : null, 'text' => $text, 'message_type' => $type,
                            'timestamp' => isset($m['timestamp']) ? (int) $m['timestamp'] : null, 'message' => $m,
                        );
                    }
                }
                if (!empty($value['statuses'])) {
                    foreach ($value['statuses'] as $s) {
                        $err = null;
                        if (!empty($s['errors'][0])) {
                            $e0 = $s['errors'][0];
                            $err = trim((isset($e0['code']) ? $e0['code'] . ' ' : '') . (isset($e0['title']) ? $e0['title'] : '')
                                . (isset($e0['error_data']['details']) ? ' — ' . $e0['error_data']['details'] : ''));
                        }
                        $events[] = array(
                            'type' => 'status', 'phone_number_id' => $pnid,
                            'wamid' => isset($s['id']) ? $s['id'] : null, 'status' => isset($s['status']) ? $s['status'] : null,
                            'recipient' => isset($s['recipient_id']) ? $s['recipient_id'] : null, 'error' => $err,
                            'timestamp' => isset($s['timestamp']) ? (int) $s['timestamp'] : null, 'raw' => $s,
                        );
                    }
                }
            }
        }
        return $events;
    }

    // ------------------------------------------------------------------ helpers

    /** "98765 43210" / "+91-98765-43210" / "098765 43210" → "919876543210" (10-digit numbers get $countryCode). */
    public static function normalizePhone($phone, $countryCode = '91')
    {
        $d = preg_replace('/\D+/', '', (string) $phone);
        if (strlen($d) === 11 && $d[0] === '0') $d = substr($d, 1);
        if (strlen($d) === 10) $d = $countryCode . $d;
        return (strlen($d) >= 11 && strlen($d) <= 15) ? $d : null;
    }

    /** Template values can't contain new lines, tabs or 4+ spaces, and can't be empty. */
    private static function cleanParam($v)
    {
        $v = trim(preg_replace('/\s+/', ' ', (string) $v));
        return $v === '' ? '-' : $v;
    }

    private static function fail($message, $status = 0)
    {
        return array('ok' => false, 'status' => $status, 'wamid' => null, 'id' => null, 'error' => $message, 'error_code' => null, 'error_type' => null, 'retry_after' => null, 'data' => array());
    }

    /**
     * One API call. On 429 "rate_limited" (your package's messages/sec or read calls/min) it waits Retry-After seconds
     * and tries again, up to $maxRetries times. "daily_api_quota_exceeded" (unique recipients per day) is returned
     * at once — retrying won't help before midnight India time.
     */
    private function request($method, $path, $body = null, $multipart = false)
    {
        for ($try = 0; ; $try++) {
            $r = $this->requestOnce($method, $path, $body, $multipart);
            if ($r['status'] !== 429 || $r['error_type'] !== 'rate_limited' || $try >= $this->maxRetries) return $r;
            $wait = $r['retry_after'] !== null ? (int) $r['retry_after'] : 1;
            if ($wait > $this->maxRetryWait) return $r;
            sleep(max(1, $wait));
        }
    }

    private function requestOnce($method, $path, $body = null, $multipart = false)
    {
        $headers = array('Authorization: Bearer ' . $this->apiKey, 'Accept: application/json', 'User-Agent: TavrosConnect-PHP/' . self::VERSION);
        if ($this->nextName !== null && substr($path, -9) === '/messages') $headers[] = 'X-Contact-Name: ' . rawurlencode($this->nextName);
        $this->nextName = null;
        $ch = curl_init($this->baseUrl . ltrim($path, '/'));
        $opts = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_TIMEOUT => $this->timeout,
            CURLOPT_CONNECTTIMEOUT => 8,
        );
        if ($body !== null) {
            if ($multipart) {
                $opts[CURLOPT_POSTFIELDS] = $body;
            } else {
                $opts[CURLOPT_POSTFIELDS] = json_encode($body);
                $headers[] = 'Content-Type: application/json';
            }
        }
        $opts[CURLOPT_HTTPHEADER] = $headers;
        $retryAfter = null;
        $opts[CURLOPT_HEADERFUNCTION] = function ($c, $line) use (&$retryAfter) {
            if (preg_match('/^Retry-After:\s*(\d+)/i', $line, $m)) $retryAfter = (int) $m[1];
            return strlen($line);
        };
        curl_setopt_array($ch, $opts);
        $raw = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $cerr = curl_error($ch);
        curl_close($ch);

        if ($raw === false) return self::fail('Could not reach Tavros Connect: ' . $cerr);
        $data = json_decode((string) $raw, true);
        if (!is_array($data)) $data = array();
        $ok = $status >= 200 && $status < 300 && !isset($data['error']);
        return array(
            'ok' => $ok,
            'status' => $status,
            'wamid' => isset($data['messages'][0]['id']) ? $data['messages'][0]['id'] : null,
            'id' => isset($data['id']) ? (string) $data['id'] : null,
            'error' => $ok ? null : (isset($data['error']['message']) ? $data['error']['message'] : 'HTTP ' . $status),
            'error_code' => isset($data['error']['code']) ? (int) $data['error']['code'] : null,
            'error_type' => isset($data['error']['type']) ? (string) $data['error']['type'] : null,   // rate_limited | daily_api_quota_exceeded | …
            'retry_after' => $retryAfter,
            'data' => $data,
        );
    }
}
