<?php defined('BASEPATH') OR exit('No direct script access allowed');

// ==========================================================
// HELPER TELEGRAM (dipakai fitur PMG)
// ==========================================================

// - Ambil setting telegram (1 baris). Kalau belum ada, buat otomatis. -
function az_tg_get_setting()
{
	$ci =& get_instance();
	$ci->db->where('id', 1);
	$row = $ci->db->get('telegram_setting')->row();
	if (!$row)
	{
		$ci->db->insert('telegram_setting', array('id' => 1, 'bot_token' => '', 'chat_id' => ''));
		$row = (object) array('id' => 1, 'bot_token' => '', 'chat_id' => '', 'webhook_url' => '');
	}
	return $row;
}

// - Panggil API Telegram (inti "kantor pos") -
function az_tg_api($method, $params = array())
{
	$set = az_tg_get_setting();
	if (strlen((string)$set->bot_token) == 0) return null;

	$url = 'https://api.telegram.org/bot' . $set->bot_token . '/' . $method;

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, 15);
	// Cadangan untuk server yang tidak punya bundel sertifikat CA lengkap
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	$resp = curl_exec($ch);
	$err = curl_error($ch);
	curl_close($ch);

	if ($resp === false)
	{
		// Kembalikan objek error supaya penyebabnya terlihat di layar
		return (object) array('ok' => false, 'description' => 'cURL error: ' . $err);
	}
	return json_decode($resp);
}

// - Kirim pesan teks ke chat id admin. $keyboard = tombol inline (opsional, dipakai tahap 4) -
function az_tg_send($text, $keyboard = null)
{
	$set = az_tg_get_setting();
	if (strlen((string)$set->chat_id) == 0) return null;

	$params = array('chat_id' => $set->chat_id, 'text' => $text);
	if ($keyboard !== null)
	{
		$params['reply_markup'] = json_encode(array('inline_keyboard' => $keyboard));
	}
	return az_tg_api('sendMessage', $params);
}