<?php
/*
 * Test WhatsApp Gateway Connection
 * Debug tool untuk cek koneksi ke gateway
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h1>WhatsApp Gateway Connection Test</h1>";
echo "<hr>";

// Test 1: Check whatsapp_config.php
echo "<h2>Test 1: Check Configuration File</h2>";
if (file_exists('include/whatsapp_config.php')) {
    echo "✅ whatsapp_config.php exists<br>";
    include('include/whatsapp_config.php');
    
    if (defined('SELFHOSTED_API_URL')) {
        echo "✅ SELFHOSTED_API_URL: " . SELFHOSTED_API_URL . "<br>";
    } else {
        echo "❌ SELFHOSTED_API_URL not defined<br>";
    }
    
    if (defined('SELFHOSTED_API_KEY')) {
        echo "✅ SELFHOSTED_API_KEY: " . substr(SELFHOSTED_API_KEY, 0, 10) . "...<br>";
    } else {
        echo "❌ SELFHOSTED_API_KEY not defined<br>";
    }
} else {
    echo "❌ whatsapp_config.php not found<br>";
}

echo "<hr>";

// Test 2: Check Gateway Running
echo "<h2>Test 2: Check Gateway Running</h2>";
$gatewayUrl = defined('SELFHOSTED_API_URL') ? SELFHOSTED_API_URL : 'http://localhost:3000/api/send';
$baseUrl = str_replace('/api/send', '', $gatewayUrl);
$healthUrl = $baseUrl . '/health';

echo "Health URL: $healthUrl<br>";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $healthUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    echo "❌ Connection Error: $error<br>";
    echo "<strong>Gateway NOT running!</strong><br>";
    echo "<br><strong>Cara Start Gateway:</strong><br>";
    echo "1. Buka terminal/command prompt<br>";
    echo "2. cd mikhmon/whatsapp-gateway<br>";
    echo "3. npm start<br>";
} elseif ($httpCode === 200) {
    echo "✅ Gateway is running!<br>";
    echo "Response: <pre>" . htmlspecialchars($response) . "</pre>";
} else {
    echo "❌ Gateway returned HTTP $httpCode<br>";
    echo "Response: <pre>" . htmlspecialchars($response) . "</pre>";
}

echo "<hr>";

// Test 3: Check API Status
echo "<h2>Test 3: Check API Status</h2>";
$statusUrl = $baseUrl . '/api/status';
$apiKey = defined('SELFHOSTED_API_KEY') ? SELFHOSTED_API_KEY : '';

echo "Status URL: $statusUrl<br>";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $statusUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-API-Key: ' . $apiKey,
    'Content-Type: application/json'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    echo "❌ Connection Error: $error<br>";
} elseif ($httpCode === 200) {
    echo "✅ API Status OK!<br>";
    $data = json_decode($response, true);
    echo "<pre>" . print_r($data, true) . "</pre>";
    
    if (isset($data['connected']) && $data['connected']) {
        echo "<strong style='color: green;'>✅ WhatsApp Connected!</strong><br>";
        echo "Phone: " . ($data['phone'] ?? 'N/A') . "<br>";
    } else {
        echo "<strong style='color: orange;'>⚠️ WhatsApp Not Connected</strong><br>";
        echo "Status: " . ($data['status'] ?? 'unknown') . "<br>";
        echo "Need to scan QR code!<br>";
    }
} else {
    echo "❌ API returned HTTP $httpCode<br>";
    echo "Response: <pre>" . htmlspecialchars($response) . "</pre>";
}

echo "<hr>";

// Test 4: Check Dependencies
echo "<h2>Test 4: Check Dependencies</h2>";
$nodeModules = __DIR__ . '/whatsapp-gateway/node_modules';
if (file_exists($nodeModules)) {
    echo "✅ node_modules exists<br>";
    
    $packages = ['@whiskeysockets/baileys', 'express', 'qrcode', 'pino'];
    foreach ($packages as $package) {
        $packagePath = $nodeModules . '/' . $package;
        if (file_exists($packagePath)) {
            echo "✅ $package installed<br>";
        } else {
            echo "❌ $package NOT installed<br>";
        }
    }
} else {
    echo "❌ node_modules not found<br>";
    echo "<strong>Run: cd whatsapp-gateway && npm install</strong><br>";
}

echo "<hr>";

// Test 5: Check .env
echo "<h2>Test 5: Check .env File</h2>";
$envFile = __DIR__ . '/whatsapp-gateway/.env';
if (file_exists($envFile)) {
    echo "✅ .env file exists<br>";
    $envContent = file_get_contents($envFile);
    if (strpos($envContent, 'API_KEY=') !== false) {
        echo "✅ API_KEY configured<br>";
    } else {
        echo "❌ API_KEY not found in .env<br>";
    }
} else {
    echo "❌ .env file not found<br>";
    echo "<strong>Run installer: <a href='install_whatsapp_gateway.php'>install_whatsapp_gateway.php</a></strong><br>";
}

echo "<hr>";
echo "<h2>Summary</h2>";
echo "<a href='settings/whatsapp_gateway_admin.php' style='padding: 10px 20px; background: #667eea; color: white; text-decoration: none; border-radius: 5px;'>Open Admin Panel</a> ";
echo "<a href='install_whatsapp_gateway.php' style='padding: 10px 20px; background: #10b981; color: white; text-decoration: none; border-radius: 5px;'>Run Installer</a>";
?>
