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

echo "<h2>Test API Connection</h2>";

// Test 1: Cek koneksi ke server
echo "<h3>1. Test Koneksi Server</h3>";
$test_url = API_BASE . "login";
echo "URL: " . $test_url . "<br>";

$ch = curl_init($test_url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    CURLOPT_TIMEOUT => 10,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    CURLOPT_POSTFIELDS => json_encode(['username' => 'test', 'password' => 'test'])
]);

$res = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);

echo "HTTP Code: " . $httpCode . "<br>";
echo "Error: " . ($error ?: 'None') . "<br>";
echo "Response: " . htmlspecialchars($res) . "<br>";
echo "CURL Info: " . json_encode($info) . "<br><br>";

// Test 2: Cek dengan credentials yang mungkin benar
echo "<h3>2. Test dengan Credentials</h3>";
$result = api_login('admin', 'admin');
echo "Result: " . json_encode($result, JSON_PRETTY_PRINT) . "<br><br>";

// Test 3: Cek dengan credentials kosong
echo "<h3>3. Test dengan Credentials Kosong</h3>";
$result2 = api_login('', '');
echo "Result: " . json_encode($result2, JSON_PRETTY_PRINT) . "<br><br>";

// Test 4: Cek endpoint lain
echo "<h3>4. Test Endpoint Lain</h3>";
$result3 = api_request('berita');
echo "Berita Result: " . json_encode($result3, JSON_PRETTY_PRINT) . "<br><br>";

echo "<h3>5. Cek Log Error PHP</h3>";
echo "Error log location: " . ini_get('error_log') . "<br>";
echo "Log entries (last 10):<br>";
$log_entries = file_get_contents(ini_get('error_log'));
$lines = explode("\n", $log_entries);
$recent_lines = array_slice($lines, -10);
foreach ($recent_lines as $line) {
    if (trim($line)) {
        echo htmlspecialchars($line) . "<br>";
    }
}
