<?php
declare(strict_types=1);

require_once __DIR__ . '/telegram_lib.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/telegram_invite_lib.php';
require_once __DIR__ . '/telegram_auth_lib.php';
require_once __DIR__ . '/level_lib.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'OK';
    exit;
}

header('Content-Type: text/plain; charset=utf-8');

if (!mocker_telegram_is_configured()) {
    http_response_code(200);
    echo 'OK';
    exit;
}

$secret = mocker_telegram_webhook_secret();
if ($secret !== '') {
    $hdr = (string) ($_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '');
    if (!hash_equals($secret, $hdr)) {
        http_response_code(403);
        exit;
    }
}

$raw = (string) file_get_contents('php://input');
$update = json_decode($raw, true);
if (!is_array($update)) {
    http_response_code(200);
    echo 'OK';
    exit;
}

$pdo = null;
try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    $pdo = null;
}

if (isset($update['chat_member']) && is_array($update['chat_member']) && $pdo instanceof PDO) {
    try {
        mocker_telegram_invite_handle_chat_member($pdo, $update['chat_member']);
    } catch (Throwable $e) {

    }
    http_response_code(200);
    echo 'OK';
    exit;
}

$msg = $update['message'] ?? $update['edited_message'] ?? null;
if (!is_array($msg)) {
    http_response_code(200);
    echo 'OK';
    exit;
}

$chat = $msg['chat'] ?? [];
$chatType = (string) ($chat['type'] ?? '');
$from = isset($msg['from']) && is_array($msg['from']) ? $msg['from'] : [];
$tgUid = isset($from['id']) ? (int) $from['id'] : 0;
$updateId = isset($update['update_id']) ? (int) $update['update_id'] : 0;

if ($chatType !== 'private') {
    if (($chatType === 'group' || $chatType === 'supergroup') && $tgUid > 0 && $updateId > 0 && $pdo instanceof PDO) {
        $text = isset($msg['text']) ? trim((string) $msg['text']) : '';
        $isServiceMessage = isset($msg['new_chat_members']) || isset($msg['left_chat_member']) || isset($msg['pinned_message']);
        if (!$isServiceMessage && ($text === '' || !str_starts_with($text, '/'))) {
            try {
                mocker_level_award_telegram_message($pdo, $tgUid, $updateId);
            } catch (Throwable $e) {
                /* ignore */
            }
        }
    }
    http_response_code(200);
    echo 'OK';
    exit;
}

$chatId = isset($chat['id']) ? (int) $chat['id'] : 0;
$tgUsername = isset($from['username']) ? trim((string) $from['username']) : '';
if ($tgUsername === '' && isset($from['first_name'])) {
    $tgUsername = trim((string) $from['first_name']);
}

if (!$pdo instanceof PDO) {
    try {
        $pdo = mocker_db();
    } catch (Throwable $e) {
        http_response_code(200);
        echo 'OK';
        exit;
    }
}

if ($tgUid > 0 && $chatId !== 0) {
    try {
        mocker_telegram_bot_subscriber_upsert($pdo, $tgUid, $chatId, $tgUsername !== '' ? $tgUsername : null);
    } catch (Throwable $e) {

    }
}

$text = isset($msg['text']) ? trim((string) $msg['text']) : '';
$rawToken = mocker_telegram_parse_start_token($text);
if ($rawToken === null) {
    http_response_code(200);
    echo 'OK';
    exit;
}

if ($rawToken === '') {
    if ($chatId > 0) {
        mocker_telegram_send_message(
            $chatId,
            "Merhaba! Giriş veya kayıt için sitede «Telegram ile giriş yap» / «Telegram ile kayıt ol» butonuna bas.\n\n"
            . "Profil doğrulaması için: Profil → Telegram Davet → «Telegram ile doğrula»."
        );
    }
    http_response_code(200);
    echo 'OK';
    exit;
}

$token = mocker_telegram_normalize_verify_token($rawToken);
if ($token === null) {
    if ($chatId > 0) {
        mocker_telegram_send_message(
            $chatId,
            'Bu kod doğrulama kodu değil. Sitede Profil → Telegram Davet → «Telegram ile doğrula» ile yeni bağlantı al.'
        );
    }
    http_response_code(200);
    echo 'OK';
    exit;
}

if (mocker_telegram_auth_handle_bot_start($pdo, $token, $tgUid, $from, $chatId)) {
    http_response_code(200);
    echo 'OK';
    exit;
}

$hash = mocker_telegram_hash_token($token);
$now = time();

$pdo->beginTransaction();
try {
    $st = $pdo->prepare(
        'SELECT id FROM users WHERE telegram_pending_token_hash = :h
         AND telegram_pending_expires > :now
         LIMIT 1'
    );
    $st->execute([':h' => $hash, ':now' => $now]);
    $row = $st->fetch();
    if (!$row) {
        $pdo->rollBack();
        if ($chatId > 0) {
            mocker_telegram_send_message(
                $chatId,
                'Bağlantı kodu geçersiz veya süresi doldu. Siteden profil → Telegram ile yeni link al.'
            );
        }
        http_response_code(200);
        echo 'OK';
        exit;
    }

    $userId = (int) $row['id'];
    if ($tgUid <= 0) {
        $pdo->rollBack();
        http_response_code(200);
        echo 'OK';
        exit;
    }

    $tgUsername = isset($from['username']) ? trim((string) $from['username']) : '';
    if ($tgUsername === '' && isset($from['first_name'])) {
        $tgUsername = trim((string) $from['first_name']);
    }

    $dup = $pdo->prepare('SELECT id FROM users WHERE telegram_user_id = :tid AND id != :uid LIMIT 1');
    $dup->execute([':tid' => $tgUid, ':uid' => $userId]);
    if ($dup->fetch()) {
        $pdo->rollBack();
        if ($chatId > 0) {
            mocker_telegram_send_message($chatId, 'Bu Telegram hesabı başka bir site kullanıcısına zaten bağlı.');
        }
        http_response_code(200);
        echo 'OK';
        exit;
    }

    $upd = $pdo->prepare(
        'UPDATE users SET
            telegram_user_id = :tid,
            telegram_username = :tu,
            telegram_verified_at = :tv,
            telegram_pending_token_hash = NULL,
            telegram_pending_expires = NULL
         WHERE id = :id'
    );
    $upd->execute([
        ':tid' => $tgUid,
        ':tu' => $tgUsername !== '' ? $tgUsername : null,
        ':tv' => $now,
        ':id' => $userId,
    ]);
    $pdo->commit();

    if ($chatId > 0) {
        $line = $tgUsername !== '' ? ('@' . $tgUsername) : 'Hesabın';
        mocker_telegram_send_message(
            $chatId,
            "Telegram doğrulandı ({$line}). Mocker sitesine dönüp davet linkini oluşturabilirsin."
        );
    }
} catch (Throwable $e) {
    if ($pdo instanceof PDO && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
}

http_response_code(200);
echo 'OK';
