<?php
/**
 * API: إرسال رسالة
 * 
 * يرسل الرسالة لـ wt_webhook بنفس الصيغة اللي wifi2fm يرسلها
 * من الـ debug log، wifi2fm يرسل حدثين لكل رسالة واردة:
 *   1. received_message (صيغة wifi2fm الخاصة)
 *   2. messages.upsert مع type:"notify" (صيغة WhatsApp Web)
 * نرسل الاثنين لضمان أن البوت يتفاعل
 */

session_start();
header('Content-Type: application/json');

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['error' => 'Method not allowed'], 405);
}

if (!isset($_SESSION['whatsapp_number']) || !isset($_SESSION['whatsapp_verified'])) {
    jsonResponse(['error' => 'لا توجد جلسة نشطة. الرجاء تسجيل الدخول.'], 401);
}

$phone = $_SESSION['whatsapp_number'];

$input = json_decode(file_get_contents('php://input'), true);
$body  = sanitizeMessage($input['message'] ?? '');

if (empty($body)) {
    jsonResponse(['error' => 'لا يمكن إرسال رسالة فارغة'], 400);
}

if (isRateLimited($phone)) {
    jsonResponse(['error' => 'رسائل كثيرة جداً. انتظر لحظة.'], 429);
}

// تخزين الرسالة الصادرة
$outgoing = createMessage('outgoing', $body, $phone);
$outgoing['source'] = 'web';
saveMessage($phone, $outgoing);
recordRateLimit($phone);

$botWebhookUrl = defined('WA_ORIGINAL_WEBHOOK_URL') ? WA_ORIGINAL_WEBHOOK_URL : '';
$relaySuccess = false;
$msgId = strtoupper(bin2hex(random_bytes(12)));

if (!empty($botWebhookUrl)) {
    
    // ██ الصيغة 1: received_message (الصيغة اللي البوت يفهمها من wifi2fm) ██
    $receivedMessagePayload = json_encode([
        'instance_id' => WA_INSTANCE_ID,
        'data' => [
            'event' => 'received_message',
            'message' => [
                'body_message' => [
                    'content' => $body,
                    'type' => 'textMessage',
                    'messages' => [
                        'conversation' => $body,
                    ],
                ],
                'message_key' => [
                    'remoteJid' => $phone . '@s.whatsapp.net',
                    'remoteJidAlt' => $phone . '@s.whatsapp.net',
                    'fromMe' => false,
                    'id' => $msgId,
                    'participant' => '',
                    'addressingMode' => 'lid',
                ],
                'push_name' => 'Web User',
                'from_contact' => $phone,
            ],
        ],
    ]);
    
    $result1 = sendToWebhook($botWebhookUrl, $receivedMessagePayload);
    
    // ██ الصيغة 2: messages.upsert مع type:"notify" ██
    $upsertPayload = json_encode([
        'instance_id' => WA_INSTANCE_ID,
        'data' => [
            'event' => 'messages.upsert',
            'data' => [
                'messages' => [
                    [
                        'key' => [
                            'remoteJid' => $phone . '@s.whatsapp.net',
                            'remoteJidAlt' => $phone . '@s.whatsapp.net',
                            'fromMe' => false,
                            'id' => $msgId,
                            'participant' => '',
                            'addressingMode' => 'lid',
                        ],
                        'messageTimestamp' => time(),
                        'pushName' => 'Web User',
                        'broadcast' => false,
                        'message' => [
                            'conversation' => $body,
                        ],
                    ],
                ],
                'type' => 'notify',
            ],
        ],
    ]);
    
    $result2 = sendToWebhook($botWebhookUrl, $upsertPayload);
    
    $relaySuccess = ($result1 || $result2);
    
    logEvent('bot_relay', [
        'phone'    => $phone,
        'body'     => mb_substr($body, 0, 50),
        'result1'  => $result1 ? 'ok' : 'fail',
        'result2'  => $result2 ? 'ok' : 'fail',
    ]);
}

jsonResponse([
    'success' => true,
    'message' => [
        'id'        => $outgoing['id'],
        'body'      => htmlspecialchars($outgoing['body'], ENT_QUOTES, 'UTF-8'),
        'timestamp' => $outgoing['timestamp'],
        'direction' => 'outgoing',
        'status'    => $relaySuccess ? 'delivered' : 'sent',
    ],
    'bot_notified' => $relaySuccess,
]);


// ── دالة إرسال لـ webhook ──────────────────────────────
function sendToWebhook(string $url, string $payload): bool {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Accept: application/json',
        ],
        CURLOPT_SSL_VERIFYPEER => true,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error    = curl_error($ch);
    curl_close($ch);

    if ($error) {
        logEvent('webhook_send_error', ['url' => $url, 'error' => $error]);
        return false;
    }

    logEvent('webhook_send_result', [
        'url'       => $url,
        'http_code' => $httpCode,
        'response'  => substr($response, 0, 200),
    ]);

    return ($httpCode >= 200 && $httpCode < 300);
}
