<?php

//send telegram

date_default_timezone_set('Asia/Tehran');
ini_set("log_errors", 1);
ini_set("error_log", "./z_php_error.log");

set_exception_handler(function($e) {
    error_log(
        date('Y-m-d H:i:s').' | '.$_SERVER['REQUEST_URI'].' | '.$e->getMessage().PHP_EOL,
        3,
        "./z_sql_error.log"
    );
});

header( "Content-type: application/json" );

//Get required configs:
require('../../majoris_config.php');
require('../../majoris_core_config.php');

foreach ( glob("../v3/class/*.php" ) as $filename )  include $filename;
db::init();

if(!isset($_POST['app_id']) || !isset($_POST['text'])){
    http_response_code(400);
    echo "[app_id] or [text] parameters has not sent";
    exit;
}

$app_id  = $_POST['app_id'];
$text  = $_POST['text'];
$telegramConfigRow = db::fetch( "SELECT * FROM `serverconfig` WHERE `type` = ? AND app_id = ?",['telegram_bot_config', $app_id ]);
$telegramConfig = trim($telegramConfigRow['data']);
if($telegramConfig == "") $telegramConfig = "[]";
$telegramConfig = json_decode($telegramConfig,true);

if(!isset($telegramConfig['chat_id']) || !isset($telegramConfig['bot_token'])){
    http_response_code(400);
    echo "telegram bot is not configured!";
    exit;
}
$chat_id   = $telegramConfig['chat_id'];
$bot_token    = $telegramConfig['bot_token'];

$url = 'https://api.telegram.org/bot' . $bot_token . '/sendMessage';

$data = array(
    'chat_id' => $chat_id,
    'parse_mode' => 'HTML',
    'text'    => $text
);

$ret = CallAPI("POST",$url,$data);

if($ret){
    if($ret['ok']){
        http_response_code(200);
        echo "ok";
        exit;
    }else{
        http_response_code(501);
        echo "error: " . $ret['description'];
        exit;
    }
}else{
    http_response_code(501);
    echo "uknown telegram error";
    exit;
}


// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value

function CallAPI($method, $url, $data = false , $apikey = false)
{
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if (!is_bool($data))
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // Optional Authentication:
    // curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    // curl_setopt($curl, CURLOPT_USERPWD, "username:password");

    if($apikey){
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Authorization: AccessKey '.$apikey
        ));
    }

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($curl);

    if ($result === false) {
        // Log the error
        $error_msg = 'cURL Error: ' . curl_error($curl);
        //error_log($error_msg);
        // Optionally, return the error instead of an empty response
        curl_close($curl);
        return (['description' => $error_msg]);
    }

    curl_close($curl);

    return $result;
    
}