<?php
// includes/telegram_helper.php

if (!function_exists('telegram_html')) {
    function telegram_html($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('telegram_is_configured')) {
    function telegram_is_configured(): bool
    {
        $enabled = true;
        if (defined('TELEGRAM_NOTIF_ENABLED')) {
            $enabled = TELEGRAM_NOTIF_ENABLED === true;
        } elseif (defined('TELEGRAM_ENABLED')) {
            $enabled = TELEGRAM_ENABLED === true;
        }

        if (!$enabled) {
            return false;
        }

        if (!defined('TELEGRAM_BOT_TOKEN') || !defined('TELEGRAM_CHAT_ID_KEPERAWATAN')) {
            return false;
        }

        $token = trim((string)TELEGRAM_BOT_TOKEN);
        $chatId = trim((string)TELEGRAM_CHAT_ID_KEPERAWATAN);

        return $token !== ''
            && $chatId !== ''
            && $token !== 'ISI_BOT_TOKEN_DISINI'
            && $token !== 'ISI_TOKEN_BOT_KAMU_DI_SINI'
            && $chatId !== 'ISI_CHAT_ID_GRUP_DISINI'
            && $chatId !== 'ISI_CHAT_ID_GRUP_DI_SINI';
    }
}

if (!function_exists('telegram_log')) {
    function telegram_log(string $message): void
    {
        error_log('[TELEGRAM LAPORAN KATIM] ' . $message);
    }
}

if (!function_exists('sendTelegramMessage')) {
    function sendTelegramMessage(string $message, ?string &$error = null): bool
    {
        $error = null;

        if (!telegram_is_configured()) {
            $error = 'Telegram belum dikonfigurasi. Cek TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID_KEPERAWATAN, dan TELEGRAM_NOTIF_ENABLED.';
            telegram_log($error);
            return false;
        }

        $token = trim((string)TELEGRAM_BOT_TOKEN);
        $chatId = trim((string)TELEGRAM_CHAT_ID_KEPERAWATAN);
        $url = 'https://api.telegram.org/bot' . $token . '/sendMessage';

        $payload = [
            'chat_id' => $chatId,
            'text' => $message,
            'parse_mode' => 'HTML',
            'disable_web_page_preview' => true,
        ];

        if (function_exists('curl_init')) {
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $payload,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CONNECTTIMEOUT => 10,
                CURLOPT_TIMEOUT => 20,
                CURLOPT_SSL_VERIFYPEER => true,
            ]);

            $response = curl_exec($ch);
            $curlError = curl_error($ch);
            $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($response === false || $httpCode < 200 || $httpCode >= 300) {
                $error = $curlError ?: ('HTTP ' . $httpCode . ' - ' . (string)$response);
                telegram_log('Gagal kirim. ' . $error);
                return false;
            }

            $decoded = json_decode((string)$response, true);
            if (!is_array($decoded) || empty($decoded['ok'])) {
                $error = (string)$response;
                telegram_log('Response Telegram tidak OK. ' . $error);
                return false;
            }

            return true;
        }

        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
                'content' => http_build_query($payload),
                'timeout' => 20,
            ],
        ]);

        $response = @file_get_contents($url, false, $context);
        if ($response === false) {
            $error = 'Gagal menghubungi Telegram API via file_get_contents.';
            telegram_log($error);
            return false;
        }

        $decoded = json_decode((string)$response, true);
        if (!is_array($decoded) || empty($decoded['ok'])) {
            $error = (string)$response;
            telegram_log('Response Telegram tidak OK. ' . $error);
            return false;
        }

        return true;
    }
}

if (!function_exists('buildLaporanKatimTelegramMessage')) {
    function buildLaporanKatimTelegramMessage(array $data): string
    {
        $tanggalRaw = (string)($data['tanggal'] ?? '');
        $tanggal = $tanggalRaw !== '' ? date('d-m-Y', strtotime($tanggalRaw)) : '-';
        $totalPasien = (int)($data['total_pasien'] ?? 0);
        $jumlahTenaga = (int)($data['jumlah_tenaga'] ?? 0);
        $rasio = $jumlahTenaga > 0 ? round($totalPasien / $jumlahTenaga, 2) : 0;

        $message  = "<b>📋 LAPORAN KATIM BARU</b>\n";
        $message .= "<b>RS BaliMéd Denpasar</b>\n\n";
        $message .= "<b>Unit</b> : " . telegram_html($data['unit_name'] ?? '-') . "\n";
        $message .= "<b>Tanggal</b> : " . telegram_html($tanggal) . "\n";
        $message .= "<b>Shift</b> : " . telegram_html($data['shift'] ?? '-') . "\n";
        $message .= "<b>Petugas Submit</b> : " . telegram_html($data['created_by_name'] ?? '-') . "\n\n";

        $message .= "<b>A. Data Pasien</b>\n";
        $message .= "• Total pasien: <b>" . $totalPasien . "</b>\n";
        $message .= "• BZ: " . (int)($data['pasien_bz'] ?? 0) . "\n";
        $message .= "• Rujuk: " . (int)($data['pasien_rujuk'] ?? 0) . "\n";
        $message .= "• WT: " . (int)($data['pasien_wt'] ?? 0) . "\n";
        $message .= "• Jumlah tenaga: <b>" . $jumlahTenaga . "</b>\n";
        $message .= "• Rasio pasien/tenaga: <b>" . telegram_html((string)$rasio) . "</b>\n\n";

        $message .= "<b>B. Operasi & Sarana</b>\n";
        $message .= "• Pre-Op: " . (int)($data['pre_op'] ?? 0) . "\n";
        $message .= "• Post-Op: " . (int)($data['post_op'] ?? 0) . "\n";
        $message .= "• Sedang OK: " . (int)($data['sedang_ok'] ?? 0) . "\n";
        $message .= "• SP terpasang: " . (int)($data['sp_terpasang'] ?? 0) . "\n";
        $message .= "• SP tersedia: " . (int)($data['sp_tersedia'] ?? 0) . "\n";
        $message .= "• SP rusak: " . (int)($data['sp_rusak'] ?? 0) . "\n";
        $message .= "• SP tidak dipakai: " . (int)($data['sp_tidak_dipakai'] ?? 0) . "\n\n";

        if (!empty($data['bed_detail']) && is_array($data['bed_detail'])) {
            $message .= "<b>C. Detail Bed IGD</b>\n";
            foreach ($data['bed_detail'] as $bed) {
                $message .= "• Bed " . telegram_html($bed['bed_number'] ?? '-') . ": " . (int)($bed['jumlah_pasien'] ?? 0) . " pasien";
                if (!empty($bed['keterangan'])) {
                    $message .= " (" . telegram_html($bed['keterangan']) . ")";
                }
                $message .= "\n";
            }
            $message .= "\n";
        }

        $kondisi = trim((string)($data['kondisi_khusus'] ?? ''));
        $masalah = trim((string)($data['masalah'] ?? ''));
        $prefix = !empty($data['bed_detail']) ? ['D', 'E'] : ['C', 'D'];

        $message .= "<b>" . $prefix[0] . ". Kondisi Khusus</b>\n";
        $message .= telegram_html($kondisi !== '' ? $kondisi : '-') . "\n\n";

        $message .= "<b>" . $prefix[1] . ". Masalah</b>\n";
        $message .= telegram_html($masalah !== '' ? $masalah : '-') . "\n\n";
        $message .= "<i>Dikirim otomatis dari Aplikasi Keperawatan.</i>";

        return $message;
    }
}
