<?php
/**
 * whatsapp_lib.php
 * Thin PHP client for the self-hosted Node.js WhatsApp gateway
 * (whatsapp-gateway/server.js). Every WhatsApp action goes through this -
 * PHP never talks to WhatsApp directly.
 */

function wa_gateway_settings($conn) {
    $res = mysqli_query($conn, "SELECT whatsapp_gateway_url, whatsapp_gateway_api_key, whatsapp_notifications_enabled FROM site_settings LIMIT 1");
    return $res ? mysqli_fetch_assoc($res) : [];
}

function wa_gateway_configured($conn) {
    $s = wa_gateway_settings($conn);
    return !empty($s['whatsapp_gateway_url']) && !empty($s['whatsapp_gateway_api_key']);
}

/**
 * Low-level call to the Node gateway. Returns decoded JSON array, or
 * ['ok' => false, 'message' => '...'] on any failure - callers should
 * always check ['ok'] before trusting the rest of the response.
 */
function wa_gateway_call($conn, $method, $path, $body = null) {
    $s = wa_gateway_settings($conn);
    if (empty($s['whatsapp_gateway_url']) || empty($s['whatsapp_gateway_api_key'])) {
        return ['ok' => false, 'message' => 'WhatsApp gateway not configured yet.'];
    }

    $url = rtrim($s['whatsapp_gateway_url'], '/') . $path;
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'x-api-key: ' . $s['whatsapp_gateway_api_key'],
        ],
    ]);
    if ($body !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    }

    $response = curl_exec($ch);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($response === false) {
        return ['ok' => false, 'message' => "Could not reach WhatsApp gateway: {$curlError}"];
    }

    $decoded = json_decode($response, true);
    if (!is_array($decoded)) {
        return ['ok' => false, 'message' => 'Gateway returned an unexpected response.'];
    }
    return $decoded;
}

function wa_list_accounts($conn) {
    return wa_gateway_call($conn, 'GET', '/accounts');
}

function wa_start_connect($conn, $accountId, $method, $phoneNumber = null) {
    return wa_gateway_call($conn, 'POST', '/accounts/' . urlencode($accountId) . '/connect', [
        'method' => $method, // 'qr' or 'code'
        'phone_number' => $phoneNumber,
    ]);
}

function wa_check_status($conn, $accountId) {
    return wa_gateway_call($conn, 'GET', '/accounts/' . urlencode($accountId) . '/status');
}

function wa_disconnect($conn, $accountId) {
    return wa_gateway_call($conn, 'POST', '/accounts/' . urlencode($accountId) . '/disconnect');
}

/**
 * Sends a WhatsApp message. Leaves account selection to the gateway
 * (random connected account) unless a specific one is given - this is
 * the load-balancing across multiple numbers Mohit asked for.
 */
function send_whatsapp_message($conn, $toPhone, $message, $accountId = null) {
    $s = wa_gateway_settings($conn);
    if (empty($s['whatsapp_notifications_enabled'])) {
        return ['ok' => false, 'message' => 'WhatsApp notifications are turned off.'];
    }
    $body = ['to' => $toPhone, 'message' => $message];
    if ($accountId) $body['account_id'] = $accountId;
    return wa_gateway_call($conn, 'POST', '/send', $body);
}
