<?php
require_once dirname(__DIR__) . '/app/bootstrap.php';

header('Content-Type: application/json');

$rules = \App\Core\Database::select("SELECT * FROM chatbot_rules");
foreach ($rules as &$rule) {
    if (!empty($rule['gemini_api_key'])) {
        $rule['gemini_api_key_set'] = true;
        unset($rule['gemini_api_key']);
    } else {
        $rule['gemini_api_key_set'] = false;
    }
}

$logs = \App\Core\Database::select("SELECT * FROM messages_log ORDER BY id DESC LIMIT 20");

$sessions = \App\Core\Database::select("SELECT * FROM whatsapp_sessions");

// Check Node.js gateway status from the PHP environment
$gatewayUrl = rtrim(getenv('WHATSAPP_GATEWAY_URL') ?: 'http://localhost:3722', '/');
$ch = curl_init($gatewayUrl . '/health');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$healthResponse = curl_exec($ch);
$healthHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$healthError = curl_error($ch);
curl_close($ch);

// Test message sending endpoint to see what response it gives (404, 403, etc)
$sendUrl = $gatewayUrl . '/api/messages/send';
$payload = json_encode([
    'session_key' => 'mock_test_session',
    'phone' => '1234567890',
    'message' => 'test'
]);
$ch = curl_init($sendUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'X-Webhook-Secret: ' . getenv('WEBHOOK_SECRET')
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$sendResponse = curl_exec($ch);
$sendHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$sendError = curl_error($ch);
curl_close($ch);

echo json_encode([
    'env' => [
        'WHATSAPP_GATEWAY_URL' => getenv('WHATSAPP_GATEWAY_URL'),
        'WEBHOOK_SECRET_SET' => !empty(getenv('WEBHOOK_SECRET')),
        'APP_URL' => getenv('APP_URL')
    ],
    'gateway_health' => [
        'url' => $gatewayUrl . '/health',
        'http_code' => $healthHttpCode,
        'response' => json_decode($healthResponse, true) ?: $healthResponse,
        'error' => $healthError
    ],
    'gateway_send_test' => [
        'url' => $sendUrl,
        'http_code' => $sendHttpCode,
        'response' => json_decode($sendResponse, true) ?: $sendResponse,
        'error' => $sendError
    ],
    'chatbot_rules' => $rules,
    'messages_log' => $logs,
    'whatsapp_sessions' => $sessions
], JSON_PRETTY_PRINT);
