<?php
// telegram_webhook_chat.php
// Inbound Telegram Group -> Web Chat
// Simpan file ini di root domain testing.itcprogram.com

declare(strict_types=1);

error_reporting(E_ALL);
ini_set('log_errors', '1');
ini_set('display_errors', '0');

$root = __DIR__;

function tg_inbound_log($msg): void {
    $file = __DIR__ . '/telegram_webhook_chat.log';
    @file_put_contents($file, '[' . date('Y-m-d H:i:s') . '] ' . $msg . PHP_EOL, FILE_APPEND);
}

try {
    require_once $root . '/config/database.php';
    if (file_exists($root . '/config/telegram.php')) {
        require_once $root . '/config/telegram.php';
    }

    $raw = file_get_contents('php://input');
    tg_inbound_log('RAW: ' . ($raw ?: '[empty]'));

    if (!$raw) {
        http_response_code(200);
        echo 'OK empty';
        exit;
    }

    $update = json_decode($raw, true);
    if (!is_array($update)) {
        tg_inbound_log('Invalid JSON');
        http_response_code(200);
        echo 'OK invalid json';
        exit;
    }

    $message = $update['message'] ?? $update['edited_message'] ?? null;
    if (!$message) {
        tg_inbound_log('No message object');
        http_response_code(200);
        echo 'OK no message';
        exit;
    }

    $chat = $message['chat'] ?? [];
    $chatId = (string)($chat['id'] ?? '');
    $allowedChatId = defined('TELEGRAM_CHAT_ID_KEPERAWATAN') ? (string)TELEGRAM_CHAT_ID_KEPERAWATAN : '';

    // Jika chat_id config tersedia, hanya terima dari grup tersebut.
    if ($allowedChatId !== '' && $chatId !== $allowedChatId) {
        tg_inbound_log('Ignored different chat_id: ' . $chatId . ' allowed=' . $allowedChatId);
        http_response_code(200);
        echo 'OK ignored chat';
        exit;
    }

    $from = $message['from'] ?? [];
    $fromName = trim(
        (string)($from['first_name'] ?? '') . ' ' . (string)($from['last_name'] ?? '')
    );
    if ($fromName === '') {
        $fromName = (string)($from['username'] ?? 'User Telegram');
    }

    $text = (string)($message['text'] ?? $message['caption'] ?? '');
    if ($text === '') {
        // Untuk sticker/foto/file tanpa caption.
        $text = '[Pesan Telegram non-teks / lampiran]';
    }

    $telegramMessageId = (int)($message['message_id'] ?? 0);
    $telegramFromId = (string)($from['id'] ?? '');

    $conn = null;
    if (function_exists('getConnection')) {
        $conn = getConnection();
    } elseif (class_exists('Database')) {
        $db = new Database();
        $conn = $db->getConnection();
    }

    if (!$conn) {
        throw new Exception('Database connection not found');
    }

    // Pastikan tabel/kolom minimal ada.
    if ($conn instanceof mysqli) {
        $conn->query("CREATE TABLE IF NOT EXISTS group_chat_messages (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NULL,
            user_name VARCHAR(150) NULL,
            user_role VARCHAR(80) NULL,
            message TEXT NOT NULL,
            source VARCHAR(30) NOT NULL DEFAULT 'web',
            telegram_chat_id VARCHAR(80) NULL,
            telegram_message_id BIGINT NULL,
            telegram_from_id VARCHAR(80) NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_created_at (created_at),
            INDEX idx_source (source),
            INDEX idx_telegram_message_id (telegram_message_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

        $cols = [];
        $res = $conn->query("SHOW COLUMNS FROM group_chat_messages");
        if ($res) {
            while ($r = $res->fetch_assoc()) $cols[$r['Field']] = true;
        }
        $add = [
            'user_id' => "ALTER TABLE group_chat_messages ADD COLUMN user_id INT NULL",
            'user_name' => "ALTER TABLE group_chat_messages ADD COLUMN user_name VARCHAR(150) NULL",
            'user_role' => "ALTER TABLE group_chat_messages ADD COLUMN user_role VARCHAR(80) NULL",
            'source' => "ALTER TABLE group_chat_messages ADD COLUMN source VARCHAR(30) NOT NULL DEFAULT 'web'",
            'telegram_chat_id' => "ALTER TABLE group_chat_messages ADD COLUMN telegram_chat_id VARCHAR(80) NULL",
            'telegram_message_id' => "ALTER TABLE group_chat_messages ADD COLUMN telegram_message_id BIGINT NULL",
            'telegram_from_id' => "ALTER TABLE group_chat_messages ADD COLUMN telegram_from_id VARCHAR(80) NULL",
            'created_at' => "ALTER TABLE group_chat_messages ADD COLUMN created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP",
        ];
        foreach ($add as $c => $sql) {
            if (!isset($cols[$c])) @$conn->query($sql);
        }

        // Cegah dobel dari webhook retry Telegram.
        if ($telegramMessageId > 0) {
            $check = $conn->prepare("SELECT id FROM group_chat_messages WHERE source='telegram' AND telegram_message_id=? AND telegram_chat_id=? LIMIT 1");
            if ($check) {
                $check->bind_param("is", $telegramMessageId, $chatId);
                $check->execute();
                $exists = $check->get_result()->fetch_assoc();
                $check->close();
                if ($exists) {
                    tg_inbound_log('Duplicate ignored message_id=' . $telegramMessageId);
                    http_response_code(200);
                    echo 'OK duplicate';
                    exit;
                }
            }
        }

        $displayName = 'Telegram - ' . $fromName;
        $role = 'telegram';

        $stmt = $conn->prepare("INSERT INTO group_chat_messages
            (user_id, user_name, user_role, message, source, telegram_chat_id, telegram_message_id, telegram_from_id, created_at)
            VALUES (NULL, ?, ?, ?, 'telegram', ?, ?, ?, NOW())");
        if (!$stmt) {
            throw new Exception('Prepare insert failed: ' . $conn->error);
        }
        $stmt->bind_param("ssssis", $displayName, $role, $text, $chatId, $telegramMessageId, $telegramFromId);
        if (!$stmt->execute()) {
            throw new Exception('Execute insert failed: ' . $stmt->error);
        }
        $stmt->close();

        tg_inbound_log('Inserted Telegram message_id=' . $telegramMessageId . ' from=' . $displayName);
    } else {
        throw new Exception('Only mysqli supported in this patch');
    }

    http_response_code(200);
    echo 'OK';
} catch (Throwable $e) {
    tg_inbound_log('ERROR: ' . $e->getMessage());
    http_response_code(200); // Telegram tidak retry terlalu agresif, error dicatat di log.
    echo 'OK error logged';
}
