<?php
/**
 * OTIS Telegram Bot Webhook — Standalone Entry Point
 *
 * URL: https://yourdomain.com/otis/telegram/webhook.php
 * Register with: https://api.telegram.org/bot<TOKEN>/setWebhook?url=<THIS_URL>
 *
 * Security:
 *  - Chat ID whitelist (single allowed sender)
 *  - Accepts only POST requests
 *  - No session, no cookies
 */

// ── Bootstrap ────────────────────────────────────────────────
define('ROOT_PATH', realpath(__DIR__ . '/..'));
define('BASE_URL', '');

// Only accept POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

// Load database config (which also holds ENV parsing optionally, but we'll parse .env directly for the secret)
$envFile = ROOT_PATH . '/config/.env';
$env = [];
if (file_exists($envFile)) {
    foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        if (str_starts_with(trim($line), '#') || !str_contains($line, '=')) continue;
        [$k, $v] = explode('=', $line, 2);
        $env[trim($k)] = trim($v);
    }
}

// Verify Webhook Secret
$expectedSecret = $env['TELEGRAM_WEBHOOK_SECRET'] ?? '';
if (!empty($expectedSecret) && ($_GET['secret'] ?? '') !== $expectedSecret) {
    http_response_code(403);
    exit('Forbidden');
}

// Load database config
$dbConf = require ROOT_PATH . '/config/database.php';

// Composer autoload
if (file_exists(ROOT_PATH . '/vendor/autoload.php')) {
    require_once ROOT_PATH . '/vendor/autoload.php';
} else {
    http_response_code(503);
    exit;
}

// Minimal helpers needed
require_once ROOT_PATH . '/helpers/functions.php';

// ── Instantiate & Run ────────────────────────────────────────
require_once ROOT_PATH . '/core/Database.php';
require_once ROOT_PATH . '/core/Services/TelegramBotService.php';

try {
    $bot = new \Core\Services\TelegramBotService();
    $bot->handleWebhook();
} catch (\Throwable $e) {
    error_log('[TelegramWebhook] Fatal: ' . $e->getMessage());
    http_response_code(200); // Always 200 to Telegram
    exit;
}
