<?php
/**
 * wa_api.php  —  outbound side (your server -> customer's WhatsApp).
 *
 * Set WA_API_MODE in config.php to whichever shape your panel documents:
 *
 *   'json'  -> POST, JSON body, key inside the body      (most resellers)
 *   'form'  -> POST, application/x-www-form-urlencoded   (older panels)
 *   'query' -> GET,  everything in the query string      (simplest panels)
 *   'cloud' -> Meta Cloud API direct, Bearer token       (if you have your own app)
 */

require_once __DIR__ . '/config.php';

/**
 * Send a plain text WhatsApp message.
 *
 * @return array{ok:bool, http:int, message_id:?string, body:string}
 */
function wa_send_text(string $to, string $text): array
{
    $to = preg_replace('/\D+/', '', $to);   // 919876543210 — no +, no spaces

    switch (WA_API_MODE) {

        case 'cloud':
            $url     = rtrim(WA_API_URL, '/');           // .../v20.0/<PHONE_ID>/messages
            $method  = 'POST';
            $headers = ['Content-Type: application/json', 'Authorization: Bearer ' . WA_API_KEY];
            $body    = json_encode([
                'messaging_product' => 'whatsapp',
                'recipient_type'    => 'individual',
                'to'                => $to,
                'type'              => 'text',
                'text'              => ['preview_url' => false, 'body' => $text],
            ], JSON_UNESCAPED_UNICODE);
            break;

        case 'form':
            $url     = WA_API_URL;
            $method  = 'POST';
            $headers = ['Content-Type: application/x-www-form-urlencoded'];
            $body    = http_build_query(wa_reseller_params($to, $text));
            break;

        case 'query':
            $url     = WA_API_URL . (strpos(WA_API_URL, '?') === false ? '?' : '&')
                     . http_build_query(wa_reseller_params($to, $text));
            $method  = 'GET';
            $headers = [];
            $body    = null;
            break;

        case 'json':
        default:
            $url     = WA_API_URL;
            $method  = 'POST';
            $headers = ['Content-Type: application/json', 'Accept: application/json'];
            $body    = json_encode(wa_reseller_params($to, $text), JSON_UNESCAPED_UNICODE);
            break;
    }

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_HTTPHEADER     => $headers,
    ]);
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    }

    $response = curl_exec($ch);
    $http     = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr  = curl_error($ch);
    curl_close($ch);

    if ($response === false) {
        wa_log_api($url, $body, 0, $curlErr);
        return ['ok' => false, 'http' => 0, 'message_id' => null, 'body' => $curlErr];
    }

    wa_log_api($url, $body, $http, $response);

    $decoded = json_decode($response, true);
    $msgId   = null;
    if (is_array($decoded)) {
        $msgId = $decoded['messages'][0]['id']
              ?? $decoded['message_id']
              ?? $decoded['data']['message_id']
              ?? $decoded['id']
              ?? null;
    }

    $ok = ($http >= 200 && $http < 300);

    if ($ok) {
        try {
            db()->prepare(
                "INSERT INTO wa_messages
                   (wa_message_id, direction, wa_to, msg_type, body, status, event_time)
                 VALUES (?, 'out', ?, 'text', ?, 'submitted', NOW())
                 ON DUPLICATE KEY UPDATE body = VALUES(body)"
            )->execute([$msgId ?: 'local_' . uniqid(), $to, $text]);
        } catch (Throwable $e) {
            error_log('wa_send_text db log failed: ' . $e->getMessage());
        }
    }

    return ['ok' => $ok, 'http' => $http, 'message_id' => $msgId, 'body' => $response];
}

/**
 * The parameter names your panel expects. THIS is the block you adjust
 * after reading your provider's send-message documentation.
 */
function wa_reseller_params(string $to, string $text): array
{
    $params = [
        'apikey'  => WA_API_KEY,   // some panels: 'api_key', 'token', 'access_token'
        'to'      => $to,          // some panels: 'number', 'mobile', 'phone', 'receiver'
        'type'    => 'text',
        'message' => $text,        // some panels: 'text', 'body', 'msg', 'content'
    ];
    if (WA_INSTANCE !== '') {
        $params['instance_id'] = WA_INSTANCE;   // or 'channel_id', 'sender_id'
    }
    return $params;
}

/**
 * Records every outbound API call so failures are visible after the fact.
 */
function wa_log_api(string $url, ?string $request, int $http, string $response): void
{
    try {
        db()->prepare(
            "INSERT INTO wa_api_log (url, request, http_code, response) VALUES (?, ?, ?, ?)"
        )->execute([$url, $request, $http, $response]);
    } catch (Throwable $e) {
        error_log('wa_log_api failed: ' . $e->getMessage());
    }
}
