<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../api/webhook.php';

$since_hours = $argv[1] ?? 24; // look back window
$db = Database::getInstance();
$cutoff = date('Y-m-d H:i:s', strtotime("-{$since_hours} hours"));
$rows = $db->fetchAll('SELECT id, request_body FROM webhook_logs WHERE created_at >= ? ORDER BY id ASC', [$cutoff]);
$webhook = new WhatsAppWebhook();
$replayed = 0;
foreach ($rows as $row) {
    $data = json_decode($row['request_body'], true);
    if (empty($data) || !isset($data['entry'])) continue;
    $needReplay = false;
    foreach ($data['entry'] as $entry) {
        foreach ($entry['changes'] as $change) {
            $value = $change['value'] ?? [];
            $messages = $value['messages'] ?? [];
            foreach ($messages as $m) {
                $mid = $m['id'] ?? null;
                if ($mid && !$db->fetch('SELECT id FROM conversations WHERE message_id = ?', [$mid])) {
                    $needReplay = true; break 3;
                }
            }
        }
    }
    if ($needReplay) {
        echo "Replaying webhook_log id={$row['id']}\n";
        $ok = $webhook->processPayload($data);
        echo "  -> processPayload returned: " . ($ok ? 'true' : 'false') . "\n";
        $replayed++;
    }
}

echo "Completed. Replayed $replayed logs.\n";
