<?php
/**
 * API - Obtener timestamp del último webhook recibido
 */
require_once '../config/config.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

try {
    $db = Database::getInstance();
    $row = $db->fetch('SELECT created_at, request_body FROM webhook_logs ORDER BY created_at DESC LIMIT 1');
    if (!$row) {
        echo json_encode(['success' => true, 'last_webhook' => null]);
        exit;
    }

    // Intentar extraer teléfonos afectados del request_body (opcional)
    $phones = [];
    $req = json_decode($row['request_body'], true);
    if ($req && isset($req['entry']) && is_array($req['entry'])) {
        foreach ($req['entry'] as $entry) {
            if (isset($entry['changes']) && is_array($entry['changes'])) {
                foreach ($entry['changes'] as $change) {
                    $val = $change['value'] ?? [];
                    // buscar en contacts
                    if (isset($val['contacts']) && is_array($val['contacts'])) {
                        foreach ($val['contacts'] as $c) {
                            if (isset($c['wa_id'])) $phones[] = $c['wa_id'];
                        }
                    }
                    // buscar en messages
                    if (isset($val['messages']) && is_array($val['messages'])) {
                        foreach ($val['messages'] as $m) {
                            if (isset($m['from'])) $phones[] = $m['from'];
                        }
                    }
                }
            }
        }
    }

    $phones = array_values(array_unique($phones));

    echo json_encode(['success' => true, 'last_webhook' => $row['created_at'], 'phones' => $phones]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Error interno del servidor']);
}
