<?php

require_once __DIR__ . '/vendor/autoload.php';

use Bot\Database;
use Bot\Bot;

// Load Config
$config = require __DIR__ . '/config.php';

// Initialize Database
$db = new Database($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);

// Initialize Bot
$bot = new Bot(
    $config['bot_token'], 
    $db, 
    $config['admins'], 
    $config['owner_id']
);

// Handle Incoming Update
$bot->handleUpdates();

// === TRIGGER SCHEDULED TASKS (Traffic-Driven Cron) ===
// This replaces the need for a system cron job.
// Every user interaction wakes up the worker to process deferred requests/actions.
try {
    $siteUrl = $config['site_url'] ?? '';
    if ($siteUrl) {
        $parts = parse_url($siteUrl);
        $host = $parts['host'] ?? 'localhost';
        $scheme = $parts['scheme'] ?? 'http';
        $port = $parts['port'] ?? ($scheme === 'https' ? 443 : 80);
        $path = rtrim($parts['path'] ?? '/', '/') . '/process_tasks.php';
        $query = "?key=" . ($config['cron_secret'] ?? '');
        
        // Timeout 0.5s - minimal impact on user experience
        $fp = @fsockopen(($scheme === 'https' ? 'ssl://' : '') . $host, $port, $errno, $errstr, 0.5);
        if ($fp) {
            $out = "GET " . $path . $query . " HTTP/1.1\r\n";
            $out .= "Host: " . $host . "\r\n";
            $out .= "Connection: Close\r\n\r\n";
            fwrite($fp, $out);
            fclose($fp);
        }
    }
} catch (\Exception $e) {
    // Ignore trigger errors
}
