<?php
/**
 * Telegram Webhook Setup - Run once to register the webhook
 * Open in browser: https://your-domain.com/panel/set_webhook.php
 */
session_start();
require __DIR__ . '/includes/panel_auth.php';
panelRequireLogin();
require "classes/admin.class.php";

$admin = new Admin;
$admin->setDataFile(__DIR__ . "/data/admin.json");
$raw_bot = $admin->getData()["settings"]["telegram_bot"] ?? '';
$maybe = base64_decode($raw_bot, true);
$bot_token = ($maybe !== false && strpos($maybe, ':') !== false) ? $maybe : $raw_bot;

if (empty($bot_token)) {
    die("❌ Bot token not found in admin.json");
}

// Build webhook URL
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? '';
$scriptDir = dirname($_SERVER['SCRIPT_NAME'] ?? '/panel/set_webhook.php');
$webhookUrl = $protocol . "://" . $host . $scriptDir . "/telegram_webhook.php";

// Optional: force HTTPS for webhook (Telegram requires HTTPS)
if ($protocol === 'http' && $host !== 'localhost' && $host !== '127.0.0.1') {
    $webhookUrl = "https://" . $host . $scriptDir . "/telegram_webhook.php";
}

$setUrl = "https://api.telegram.org/bot" . $bot_token . "/setWebhook?url=" . urlencode($webhookUrl);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $setUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$data = json_decode($result, true);

header('Content-Type: text/html; charset=utf-8');
echo "<!DOCTYPE html><html><head><meta charset='utf-8'><title>Webhook Setup</title></head><body style='font-family:Arial;padding:20px;'>";
echo "<h2>Telegram Webhook Setup</h2>";
echo "<p><strong>Webhook URL:</strong> " . htmlspecialchars($webhookUrl) . "</p>";

if (isset($data['ok']) && $data['ok'] === true) {
    echo "<p style='color:green;'>✅ <strong>Success!</strong> Webhook registered. Buttons will work.</p>";
} else {
    echo "<p style='color:red;'>❌ <strong>Error:</strong> " . htmlspecialchars($data['description'] ?? $result) . "</p>";
    echo "<p><strong>Note:</strong> Telegram requires HTTPS for webhook (except localhost).</p>";
}

echo "<p><a href='set_webhook.php'>Retry</a> | <a href='settings.php'>Settings</a></p>";
echo "</body></html>";
