<?php
/**
 * WhatsApp Cloud API webhook.
 *   GET  — Meta verification handshake (hub.challenge).
 *   POST — inbound events: records the sender's 24h window and flushes any
 *          queued full-text messages to them.
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/whatsapp_lib.php';

// ── Verification handshake ────────────────────────────────────────────────
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'GET') {
    $mode      = $_GET['hub_mode']         ?? '';
    $token     = $_GET['hub_verify_token'] ?? '';
    $challenge = $_GET['hub_challenge']    ?? '';
    $expected  = wa_config('wa_verify_token');
    if ($mode === 'subscribe' && $expected !== '' && hash_equals($expected, (string) $token)) {
        header('Content-Type: text/plain');
        echo $challenge;
        exit;
    }
    http_response_code(403);
    echo 'Verification failed';
    exit;
}

// ── Inbound events ────────────────────────────────────────────────────────
$raw     = file_get_contents('php://input');
$payload = json_decode($raw, true) ?: [];

foreach (($payload['entry'] ?? []) as $entry) {
    foreach (($entry['changes'] ?? []) as $change) {
        $value = $change['value'] ?? [];
        if (!empty($value['messages'])) {
            foreach ($value['messages'] as $msg) {
                $from = $msg['from'] ?? '';
                if ($from !== '') {
                    wa_record_inbound($from);
                    wa_flush_pending($from);
                }
            }
        }
    }
}

http_response_code(200);
echo 'ok';
