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

$json = '{
    "object": "whatsapp_business_account",
    "entry": [
        {
            "id": "639871912520412",
            "changes": [
                {
                    "value": {
                        "messaging_product": "whatsapp",
                        "metadata": {
                            "display_phone_number": "573053370116",
                            "phone_number_id": "959898150536936"
                        },
                        "contacts": [
                            {
                                "profile": {
                                    "name": "Lizan"
                                },
                                "wa_id": "573022548060"
                            }
                        ],
                        "messages": [
                            {
                                "from": "573022548060",
                                "id": "wamid.HBgMNTczMDIyNTQ4MDYwFQIAEhgUM0EyMzM2QUI0MEZDMUI1OTdEMDkA",
                                "timestamp": "1771676075",
                                "type": "image",
                                "image": {
                                    "mime_type": "image/jpeg",
                                    "sha256": "249zHFtLK2eVmLmw1UhwydtmFsEeIeE0nFOwOaYJ55w=",
                                    "id": "899050479612656",
                                    "url": "https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=899050479612656&source=webhook&ext=1771676376&hash=ARkxbmHesPbiWE1keW9GrRo6jYIQEU10BmhsamUWYIVe3w"
                                }
                            }
                        ]
                    },
                    "field": "messages"
                }
            ]
        }
    ]
}';

$data = json_decode($json, true);

$webhook = new WhatsAppWebhook();
$result = $webhook->processPayload($data);
echo "processPayload returned: ";
var_export($result);

// show last conversation record for user phone
$db = Database::getInstance();
$user = $db->fetch('SELECT * FROM users WHERE phone_number = ?', ['573022548060']);
if ($user) {
    echo "\nUser found: ";
    var_export($user);
    $convs = $db->fetchAll('SELECT * FROM conversations WHERE user_id = ? ORDER BY id DESC LIMIT 5', [$user['id']]);
    echo "\nRecent conversations:";
    var_export($convs);
} else {
    echo "\nUser not found.\n";
}

// show media_queue entries
$mqs = $db->fetchAll('SELECT * FROM media_queue ORDER BY id DESC LIMIT 5');
echo "\nMedia queue entries: "; var_export($mqs);
