<?php
require_once __DIR__ . '/../config/config_enhanced.php';
require_once __DIR__ . '/../classes/Database.php';

try {
    $db = Database::getInstance();
    $rows = $db->fetchAll('SELECT id, request_body, created_at FROM webhook_logs ORDER BY created_at DESC LIMIT 50');
    $missing = [];
    foreach ($rows as $r) {
        $data = json_decode($r['request_body'], true);
        if (!$data) continue;
        if (!empty($data['entry'])) {
            foreach ($data['entry'] as $entry) {
                if (!empty($entry['changes'])) {
                    foreach ($entry['changes'] as $change) {
                        $val = $change['value'] ?? [];
                        if (!empty($val['conversations'])) {
                            foreach ($val['conversations'] as $m) {
                                $mid = $m['id'] ?? null;
                                $from = $m['from'] ?? null;
                                if ($mid) {
                                    $exists = $db->fetch("SELECT id FROM conversations WHERE message_id = ? LIMIT 1", [$mid]);
                                    if (!$exists) {
                                        $missing[] = ['message_id' => $mid, 'from' => $from, 'log_id' => $r['id'], 'log_time' => $r['created_at']];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    if (empty($missing)) {
        echo "All recent conversations found in conversations.\n";
    } else {
        echo "Missing conversations (not found in conversations):\n";
        foreach ($missing as $m) {
            echo json_encode($m) . PHP_EOL;
        }
    }
} catch (Exception $e) {
    echo 'ERROR: ' . $e->getMessage() . PHP_EOL;
}
