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

$id = $argv[1] ?? null;
if (!$id) {
    echo "Usage: php replay_webhook_by_id.php <webhook_log_id>\n";
    exit;
}
$db = Database::getInstance();
$row = $db->fetch('SELECT request_body FROM webhook_logs WHERE id = ?', [$id]);
if (!$row) { echo "Log id $id not found\n"; exit; }

$data = json_decode($row['request_body'], true);
if (!$data) { echo "Invalid JSON in log id $id\n"; exit; }

$webhook = new WhatsAppWebhook();
$ok = $webhook->processPayload($data);
echo "processPayload returned: " . ($ok ? 'true' : 'false') . "\n";

// Try to show messages for the involved phone numbers
$phones = [];
foreach ($data['entry'] as $entry) {
    foreach ($entry['changes'] as $change) {
        $val = $change['value'] ?? [];
        if (isset($val['contacts'])) {
            foreach ($val['contacts'] as $c) if (isset($c['wa_id'])) $phones[] = $c['wa_id'];
        }
        if (isset($val['messages'])) {
            foreach ($val['messages'] as $m) if (isset($m['from'])) $phones[] = $m['from'];
        }
    }
}
$phones = array_unique($phones);
foreach ($phones as $p) {
    $user = $db->fetch('SELECT * FROM users WHERE phone_number = ?', [$p]);
    echo "Phone: $p\n";
    if (!$user) { echo "  No user found\n"; continue; }
    $msgs = $db->fetchAll('SELECT id,message_id,message_type,content,media_url,created_at FROM conversations WHERE user_id = ? ORDER BY created_at DESC LIMIT 5', [$user['id']]);
    echo json_encode($msgs, JSON_PRETTY_PRINT) . "\n";
}
