<?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 + BROADCAST (Traffic-Driven) ===
// Every user interaction wakes up workers. No cron job needed.
// Uses multi-method trigger for maximum shared hosting compatibility.
try {
    $siteUrl = $config['site_url'] ?? '';
    if ($siteUrl) {
        $cronSecret = $config['cron_secret'] ?? '';
        
        // 1. Trigger process_tasks.php (deferred join requests, scheduled actions)
        $tasksUrl = rtrim($siteUrl, '/') . '/process_tasks.php?key=' . urlencode($cronSecret);
        triggerAsyncUrl($tasksUrl);
        
        // 2. Trigger broadcast processor if there's an active broadcast
        $activeBc = $db->getActiveBroadcast();
        if ($activeBc && in_array($activeBc['status'], ['pending', 'processing'])) {
            $bcUrl = rtrim($siteUrl, '/') . '/process_broadcast.php?key=' . urlencode($cronSecret);
            triggerAsyncUrl($bcUrl);
        }
    }
} catch (\Exception $e) {
    // Ignore trigger errors - don't crash the webhook
}


// =============================================================================
// Multi-method async URL trigger (cURL > fsockopen > file_get_contents)
// =============================================================================
function triggerAsyncUrl(string $url): bool
{
    // Method 1: cURL (most compatible with shared hosting)
    if (function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 1,
            CURLOPT_CONNECTTIMEOUT => 1,
            CURLOPT_NOSIGNAL       => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_FOLLOWLOCATION => true,
        ]);
        @curl_exec($ch);
        curl_close($ch);
        return true;
    }
    
    // Method 2: fsockopen
    $parts  = parse_url($url);
    $host   = $parts['host'] ?? 'localhost';
    $scheme = $parts['scheme'] ?? 'http';
    $port   = $parts['port'] ?? ($scheme === 'https' ? 443 : 80);
    $path   = ($parts['path'] ?? '/') . (isset($parts['query']) ? '?' . $parts['query'] : '');
    
    $fp = @fsockopen(
        ($scheme === 'https' ? 'ssl://' : '') . $host,
        $port, $errno, $errstr, 1
    );
    if ($fp) {
        fwrite($fp, "GET $path HTTP/1.1\r\nHost: $host\r\nConnection: Close\r\n\r\n");
        fclose($fp);
        return true;
    }
    
    // Method 3: file_get_contents with short timeout
    $ctx = stream_context_create([
        'http' => ['timeout' => 1, 'ignore_errors' => true],
        'ssl'  => ['verify_peer' => false, 'verify_peer_name' => false]
    ]);
    @file_get_contents($url, false, $ctx);
    return true;
}
