<?php

declare(strict_types=1);



class Telegram
{
    private const EVENT_DEFAULTS = [
        'contact' => '1',
        'report'  => '1',
        'user'    => '0',
        'comment' => '0',
    ];

    public static function isConfigured(): bool
    {
        return Setting::get('telegram_enabled', '0') === '1'
            && trim((string) Setting::get('telegram_bot_token', '')) !== ''
            && trim((string) Setting::get('telegram_chat_id', '')) !== '';
    }

    public static function eventEnabled(string $event): bool
    {
        $def = self::EVENT_DEFAULTS[$event] ?? '0';
        return Setting::get('telegram_event_' . $event, $def) === '1';
    }

     
    public static function notify(string $event, string $html): bool
    {
        if (!self::isConfigured() || !self::eventEnabled($event)) {
            return false;
        }
        try {
            return self::sendMessage($html);
        } catch (\Throwable $e) {
            error_log('Telegram notify failed: ' . $e->getMessage());
            return false;
        }
    }

     

    public static function notifyContact(array $d): void
    {
        $text = "\u{1F4EC} <b>New contact message</b>\n"
            . 'From: ' . self::esc((string) ($d['name'] ?? '')) . ' &lt;' . self::esc((string) ($d['email'] ?? '')) . "&gt;\n"
            . 'Subject: ' . self::esc((string) ($d['subject'] ?? '')) . ' (' . self::esc((string) ($d['subject_type'] ?? '')) . ")\n"
            . 'IP: ' . self::esc((string) ($d['ip'] ?? '')) . "\n\n"
            . self::esc(mb_substr((string) ($d['message'] ?? ''), 0, 600));
        self::notify('contact', $text);
    }

    public static function notifyReport(array $d): void
    {
        $text = "\u{1F6A9} <b>New content report</b>\n"
            . 'Video: ' . self::esc((string) ($d['video_title'] ?? '')) . "\n"
            . 'Reason: ' . self::esc((string) ($d['reason'] ?? '')) . "\n"
            . 'Reporter: ' . self::esc((string) ($d['reporter_email'] ?? '') ?: '—') . "\n"
            . 'IP: ' . self::esc((string) ($d['ip'] ?? '')) . "\n";
        $details = trim((string) ($d['details'] ?? ''));
        if ($details !== '') {
            $text .= "\n" . self::esc(mb_substr($details, 0, 600));
        }
        if (!empty($d['video_url'])) {
            $text .= "\n" . self::esc((string) $d['video_url']);
        }
        self::notify('report', $text);
    }

    public static function notifyUser(array $d): void
    {
        $text = "\u{1F464} <b>New registration</b>\n"
            . 'Username: ' . self::esc((string) ($d['username'] ?? '')) . "\n"
            . 'Email: ' . self::esc((string) ($d['email'] ?? ''));
        self::notify('user', $text);
    }

    public static function notifyComment(array $d): void
    {
        $text = "\u{1F4AC} <b>New comment</b>" . (!empty($d['pending']) ? ' (awaiting moderation)' : '') . "\n"
            . 'By: ' . self::esc((string) ($d['author'] ?? 'Anonymous')) . "\n"
            . 'On: ' . self::esc((string) ($d['video_title'] ?? ('#' . ($d['video_id'] ?? '')))) . "\n\n"
            . self::esc(mb_substr((string) ($d['body'] ?? ''), 0, 500));
        self::notify('comment', $text);
    }

     

    public static function sendMessage(string $html, ?string $token = null, ?string $chatId = null): bool
    {
        $token  = $token !== null ? trim($token) : trim((string) Setting::get('telegram_bot_token', ''));
        $chatId = $chatId !== null ? trim($chatId) : trim((string) Setting::get('telegram_chat_id', ''));
        if ($token === '' || $chatId === '') {
            throw new \RuntimeException('Telegram bot token and chat ID are required.');
        }

        $url = 'https://api.telegram.org/bot' . $token . '/sendMessage';
        $payload = json_encode([
            'chat_id' => $chatId,
            'text' => $html,
            'parse_mode' => 'HTML',
            'disable_web_page_preview' => true,
        ], JSON_UNESCAPED_UNICODE);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_TIMEOUT => 12,
            CURLOPT_CONNECTTIMEOUT => 6,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_USERAGENT => 'TubePress',
        ]);
        $resp = curl_exec($ch);
        if ($resp === false) {
            $err = curl_error($ch);
            curl_close($ch);
            throw new \RuntimeException('Connection error: ' . $err);
        }
        $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($code !== 200) {
            $msg = 'Telegram API HTTP ' . $code;
            $j = json_decode((string) $resp, true);
            if (is_array($j) && isset($j['description'])) {
                $msg .= ': ' . $j['description'];
            }
            throw new \RuntimeException($msg);
        }
        return true;
    }

    public static function esc(string $s): string
    {
        return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
    }
}
