<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json; charset=utf-8');

$config = __DIR__ . '/config.php';
if (!is_file($config)) {
    echo json_encode(['ok'=>false,'error'=>'config.php not found'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}
require_once $config;

if (!defined('API_KEY')) {
    echo json_encode(['ok'=>false,'error'=>'API_KEY is not defined in config.php'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}

$token = preg_replace('/\s+/', '', trim((string) API_KEY));
if ($token === '' || $token === '[*[TOK]*]' || !preg_match('/^\d+:[A-Za-z0-9_\-]+$/', $token)) {
    echo json_encode([
        'ok'=>false,
        'error'=>'API_KEY format is invalid',
        'token_length'=>strlen($token),
        'token_preview'=>$token ? substr($token,0,8).'...'.substr($token,-6) : ''
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}

$webhookUrl = $_GET['url'] ?? '';
$webhookUrl = trim($webhookUrl);
if ($webhookUrl === '') {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    $dir = rtrim(str_replace('\\','/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
    $webhookUrl = $scheme . '://' . $host . $dir . '/bot.php';
}
if (!filter_var($webhookUrl, FILTER_VALIDATE_URL) || stripos($webhookUrl, 'https://') !== 0) {
    echo json_encode(['ok'=>false,'error'=>'webhook url must be valid https URL','webhook_url'=>$webhookUrl], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}

$apiUrl = 'https://api.telegram.org/bot' . $token . '/setWebhook';
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $apiUrl,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [
        'url' => $webhookUrl,
        // chat_member برای جریمه درجا هنگام خروج کاربر از کانال/گروه لازم است.
        'allowed_updates' => json_encode(['message','callback_query','inline_query','channel_post','chat_member'], JSON_UNESCAPED_UNICODE),
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT => 20,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
]);
$response = curl_exec($ch);
$error = curl_error($ch);
$errno = curl_errno($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo json_encode([
    'ok' => $response !== false,
    'http_code' => $httpCode,
    'webhook_url' => $webhookUrl,
    'curl_errno' => $errno,
    'curl_error' => $error,
    'api_url_preview' => 'https://api.telegram.org/bot' . substr($token,0,8) . '.../setWebhook',
    'telegram_response' => json_decode((string)$response, true),
    'raw_response' => $response,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
