<?php

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

use Dotenv\Dotenv;

// Load environment variables
if (file_exists(__DIR__ . '/.env')) {
    $dotenv = Dotenv::createImmutable(__DIR__);
    $dotenv->safeLoad();
}

$token = $_ENV['BOT_TOKEN'] ?? null;

if (!$token) {
    echo "Error: BOT_TOKEN not found in .env file.\n";
    exit(1);
}

// Check if running in CLI or Web
if (php_sapi_name() === 'cli') {
    if ($argc < 2) {
        echo "Usage: php set_webhook.php <YOUR_URL>\n";
        exit(1);
    }
    $url = $argv[1];
} else {
    // Web Mode (Auto-detect URL)
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'];
    // Remove set_webhook.php from path to get base directory
    $path = str_replace('/set_webhook.php', '', $_SERVER['REQUEST_URI']);
    $url = "$protocol://$host$path/webhook.php";
}

// Ensure URL ends with webhook.php (clean up if CLI user passed just domain)
if (!str_ends_with($url, 'webhook.php')) {
    $url = rtrim($url, '/') . '/webhook.php';
}

echo "Setting webhook to: $url\n";

// Use POST with allowed_updates to receive all required update types
// CRITICAL: 'chat_member' is needed for channel farewell (user leave events)
$apiUrl = "https://api.telegram.org/bot$token/setWebhook";
$postData = [
    'url' => $url,
    'allowed_updates' => json_encode([
        'message',
        'callback_query', 
        'chat_join_request',
        'my_chat_member',
        'chat_member'
    ])
];

$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo "Webhook Response: $response\n";

// Also set bot commands (only called once during setup)
$commands = json_encode([
    ['command' => 'start', 'description' => 'Start the bot and open the main menu']
]);
$commandsUrl = "https://api.telegram.org/bot$token/setMyCommands?commands=" . urlencode($commands);
$commandsResponse = file_get_contents($commandsUrl);

echo "Commands Response: $commandsResponse\n";
