<?php
// Положить рядом с bot.php. Открыть: .../life-crm-bot/diag.php
error_reporting(E_ALL);
ini_set('display_errors', '1');
header('Content-Type: text/plain; charset=utf-8');
$here = __DIR__;

echo "=== ENVIRONMENT ===\n";
echo "PHP: " . PHP_VERSION . "\n";
echo "SAPI: " . PHP_SAPI . "\n";
echo "memory_limit: " . ini_get('memory_limit') . "\n";
echo "max_execution_time: " . ini_get('max_execution_time') . "\n\n";

echo "=== FILESYSTEM ===\n";
echo "bot.php: " . (file_exists("$here/bot.php") ? filesize("$here/bot.php") . ' bytes' : 'NO') . "\n";
echo "data/ writable: " . (is_writable("$here/data") ? 'YES' : 'NO') . "\n";
echo "_error.log: " . (file_exists("$here/data/_error.log") ? filesize("$here/data/_error.log") . ' bytes' : '(нет)') . "\n\n";

echo "=== SYNTAX ===\n";
$out = []; $ret = 0;
@exec('php -l ' . escapeshellarg("$here/bot.php") . ' 2>&1', $out, $ret);
echo "exit: $ret\n" . implode("\n", $out) . "\n\n";

$selfUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')
         . '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/bot.php';

echo "=== LIVE POST {} to bot.php ===\n";
echo "URL: $selfUrl\n";
$ch = curl_init($selfUrl);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => '{}',
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 15,
    CURLOPT_SSL_VERIFYPEER => false,
]);
$t0 = microtime(true);
$body = curl_exec($ch);
$ms = (int)((microtime(true) - $t0) * 1000);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
echo "HTTP $code, {$ms}ms, curl_err: " . ($err ?: 'no') . "\n";
echo "body (" . strlen($body) . " bytes): " . substr($body, 0, 800) . "\n\n";

echo "=== LIVE GET bot.php?diag=... ===\n";
$diagUrl = $selfUrl . '?diag=Rwwwsndsiw';
$ch = curl_init($diagUrl);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 15,
    CURLOPT_SSL_VERIFYPEER => false,
]);
$t0 = microtime(true);
$body = curl_exec($ch);
$ms = (int)((microtime(true) - $t0) * 1000);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
echo "HTTP $code, {$ms}ms, curl_err: " . ($err ?: 'no') . "\n";
echo "body (" . strlen($body) . " bytes):\n" . substr($body, 0, 2500) . "\n\n";

echo "=== _error.log (last 50 lines) ===\n";
if (file_exists("$here/data/_error.log")) {
    $lines = file("$here/data/_error.log", FILE_IGNORE_NEW_LINES);
    echo implode("\n", array_slice($lines, -50));
} else {
    echo "(нет файла)";
}
