<?php
// test_env.php - Diagnostics for Bot Environment
header('Content-Type: text/plain; charset=utf-8');

echo "=== Environment Diagnostics ===\n";
echo "PHP Version: " . PHP_VERSION . "\n";
echo "Server OS: " . PHP_OS . "\n";
echo "Current Directory: " . __DIR__ . "\n\n";

// 1. Directory Checks
$dirs = array(
    'temp' => __DIR__ . '/temp',
    'data' => __DIR__ . '/data',
    'fonts' => __DIR__ . '/fonts'
);

foreach ($dirs as $name => $path) {
    echo "Directory [$name] ($path):\n";
    if (is_dir($path)) {
        echo "  - Exists: Yes\n";
        $testFile = $path . '/test_write.txt';
        $testData = "Test write at " . date('Y-m-d H:i:s');
        if (@file_put_contents($testFile, $testData) !== false) {
            echo "  - Writable: Yes\n";
            $readData = @file_get_contents($testFile);
            if ($readData === $testData) {
                echo "  - Readable: Yes\n";
            } else {
                echo "  - Readable: No (Content mismatch)\n";
            }
            @unlink($testFile);
        } else {
            echo "  - Writable: No (Failed to write file)\n";
        }
    } else {
        echo "  - Exists: No\n";
        if (@mkdir($path, 0755, true)) {
            echo "  - Created successfully now: Yes\n";
        } else {
            echo "  - Created successfully now: No (Permissions issue)\n";
        }
    }
    echo "\n";
}

// 2. Telegram Webhook info from Server
echo "=== Telegram API Webhook Info ===\n";
$token = '8497137425:AAE0A1aL7i7pO44Up4G8h03jvI-7V3rLdEo';
$url = 'https://api.telegram.org/bot' . $token . '/getWebhookInfo';

echo "Querying URL: https://api.telegram.org/bot<HIDDEN>/getWebhookInfo\n";

if (function_exists('curl_init')) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $response = curl_exec($ch);
    $err = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($response === false) {
        echo "cURL Error: " . $err . "\n";
    } else {
        echo "HTTP Status Code: " . $httpCode . "\n";
        echo "Response:\n" . $response . "\n";
    }
} else {
    echo "cURL is not enabled on this server. Trying file_get_contents...\n";
    $context = stream_context_create(array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
        )
    ));
    $response = @file_get_contents($url, false, $context);
    if ($response === false) {
        echo "file_get_contents failed to fetch URL.\n";
    } else {
        echo "Response:\n" . $response . "\n";
    }
}

// 3. Log Diagnostics
echo "\n=== Log Diagnostics ===\n";
$tempDir = __DIR__ . '/temp';
$webhookLog = $tempDir . '/webhook_last.log';
$errorLog = $tempDir . '/bot_error.log';

if (file_exists($webhookLog)) {
    echo "=== Last 20 Lines of webhook_last.log ===\n";
    $lines = file($webhookLog);
    $lastLines = array_slice($lines, -20);
    echo implode("", $lastLines);
} else {
    echo "webhook_last.log does not exist.\n";
}

echo "\n";

if (file_exists($errorLog)) {
    echo "=== Last 20 Lines of bot_error.log ===\n";
    $lines = file($errorLog);
    $lastLines = array_slice($lines, -20);
    echo implode("", $lastLines);
} else {
    echo "bot_error.log does not exist.\n";
}

// 4. File Version Diagnostics
echo "\n=== Server File Check (Diagnostic) ===\n";
$filesToCheck = array('bot.php', 'config.php', 'points.php', 'owner_panel.php', 'worker.php');
foreach ($filesToCheck as $file) {
    $path = __DIR__ . '/' . $file;
    if (file_exists($path)) {
        echo "File [$file]: Exists (Size: " . filesize($path) . " bytes, Last Modified: " . date('Y-m-d H:i:s', filemtime($path)) . ")\n";
    } else {
        echo "File [$file]: NOT found\n";
    }
}

// 5. .htaccess Check
echo "\n=== .htaccess Check ===\n";
$htaccessPath = __DIR__ . '/.htaccess';
if (file_exists($htaccessPath)) {
    echo ".htaccess Exists. Contents:\n";
    echo file_get_contents($htaccessPath) . "\n";
} else {
    echo ".htaccess does not exist.\n";
}

// 6. Server File Content Peek
echo "\n=== Server File Content Peek ===\n";
$peeks = array('bot.php', 'points.php', 'fonts.php', 'config.php');
foreach ($peeks as $file) {
    $path = __DIR__ . '/' . $file;
    echo "--- Peek inside $file ---\n";
    if (file_exists($path)) {
        $lines = file($path);
        // Print first 40 lines
        for ($i = 0; $i < min(40, count($lines)); $i++) {
            echo ($i + 1) . ": " . $lines[$i];
        }
    } else {
        echo "File NOT found.\n";
    }
    echo "\n";
}

// 7. Active Code Compilation & Load Test
echo "\n=== Include & Compilation Test ===\n";
try {
    // Include bot.php to trigger parse/runtime errors and capture them
    include_once __DIR__ . '/bot.php';
    echo "SUCCESS: bot.php compiled and loaded without errors.\n";
} catch (Throwable $e) {
    echo "CRITICAL ERROR Caught during compile/run:\n";
    echo "Message: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . "\n";
    echo "Line: " . $e->getLine() . "\n";
    echo "Trace:\n" . $e->getTraceAsString() . "\n";
}

// 8. Loopback POST Test
echo "\n=== Loopback POST Test ===\n";
$loopbackUrl = 'https://' . $_SERVER['HTTP_HOST'] . str_replace('test_env.php', 'bot.php', $_SERVER['REQUEST_URI']);
echo "Sending mock POST request to: $loopbackUrl\n";

$testPayload = json_encode(array(
    'update_id' => 123456789,
    'message' => array(
        'message_id' => 1,
        'from' => array(
            'id' => 7554081592,
            'is_bot' => false,
            'first_name' => 'Owner',
            'username' => 'owner'
        ),
        'chat' => array(
            'id' => 7554081592,
            'first_name' => 'Owner',
            'type' => 'private'
        ),
        'date' => 1600000000,
        'text' => '/start'
    )
));

$ch = curl_init($loopbackUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $testPayload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$res = curl_exec($ch);
$err = curl_error($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($res === false) {
    echo "Loopback cURL Error: $err\n";
} else {
    echo "Loopback HTTP Status Code: $code\n";
    echo "Loopback Response Body:\n$res\n";
}
