<?php
/**
 * Telegram Bot - Main Entry Point
 * Version: 2.0
 * PHP: 7.4+
 * 
 * Webhook URL: https://yourdomain.com/bot-v2/index.php
 */

declare(strict_types=1);

// Create logs directory if not exists
if (!is_dir(__DIR__ . '/logs')) {
    @mkdir(__DIR__ . '/logs', 0755, true);
}

// Error handling for debugging
error_reporting(E_ALL);
ini_set('display_errors', '0'); // Don't display errors to Telegram
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/logs/php_errors.log');

// Custom error handler
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    $logFile = __DIR__ . '/logs/php_errors.log';
    $timestamp = date('Y-m-d H:i:s');
    $errorMsg = "[{$timestamp}] Error [{$errno}]: {$errstr}\n";
    $errorMsg .= "File: {$errfile} Line: {$errline}\n\n";
    @file_put_contents($logFile, $errorMsg, FILE_APPEND);
    return false; // Let PHP handle it too
});

// Log incoming request
$logFile = __DIR__ . '/logs/requests.log';
$timestamp = date('Y-m-d H:i:s');
$input = file_get_contents('php://input');
$requestLog = "[{$timestamp}] New Request\n";
$requestLog .= "Input: " . ($input ?: 'EMPTY') . "\n\n";
@file_put_contents($logFile, $requestLog, FILE_APPEND);

try {
    // Load configuration
    require_once 'config.php';
    
    // Load core classes
    require_once 'Database.php';
    require_once 'Telegram.php';
    require_once 'Bot.php';
    
    // Initialize database
    $db = Database::getInstance();
    $db->initTables();
    
    // Create and process bot
    $bot = new Bot();
    $bot->process();
    
    // Log success
    $successLog = "[{$timestamp}] Request processed successfully\n\n";
    @file_put_contents(__DIR__ . '/logs/success.log', $successLog, FILE_APPEND);
    
} catch (Throwable $e) {
    // Log error
    $logFile = __DIR__ . '/logs/fatal_errors.log';
    $timestamp = date('Y-m-d H:i:s');
    $errorMsg = "[{$timestamp}] FATAL ERROR\n";
    $errorMsg .= "Message: " . $e->getMessage() . "\n";
    $errorMsg .= "File: " . $e->getFile() . "\n";
    $errorMsg .= "Line: " . $e->getLine() . "\n";
    $errorMsg .= "Trace:\n" . $e->getTraceAsString() . "\n";
    $errorMsg .= str_repeat("=", 80) . "\n\n";
    
    @file_put_contents($logFile, $errorMsg, FILE_APPEND);
    
    // Return 200 to Telegram to avoid retries
    http_response_code(200);
    echo "OK";
}
