<?php

function tg_sendMessage(string $chatId, string $text): bool {
    $url = "https://api.telegram.org/bot" . TOKEN . "/sendMessage";
    $data = [
        'chat_id' => $chatId,
        'text'    => $text,
        'parse_mode' => 'HTML',
    ];
    $options = [
        'http' => [
            'header'  => "Content-Type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data),
        ]
    ];
    $context  = stream_context_create($options);
    $result   = @file_get_contents($url, false, $context);
    return $result !== false;
}

function gregorianToJalaliDate(string $gregorianDate): string {
    [$gy,$gm,$gd] = explode('-', $gregorianDate);
    [$jy,$jm,$jd] = gregorian_to_jalali((int)$gy,(int)$gm,(int)$gd);
    $months = ["فروردین","اردیبهشت","خرداد","تیر","مرداد","شهریور","مهر","آبان","آذر","دی","بهمن","اسفند"];
    return convertToPersianNumbers($jd.' '.$months[$jm-1].' '.$jy);
}

function gregorian_to_jalali($g_y,$g_m,$g_d){
    $gdm=[31,28,31,30,31,30,31,31,30,31,30,31]; $jdm=[31,31,31,31,31,31,30,30,30,30,30,29];
    $gy=$g_y-1600;$gm=$g_m-1;$gd=$g_d-1;$gdn=365*$gy+intdiv($gy+3,4)-intdiv($gy+99,100)+intdiv($gy+399,400);
    for($i=0;$i<$gm;++$i)$gdn+=$gdm[$i]; if($gm>1 && (($gy%4==0 && $gy%100!=0)||($gy%400==0)))$gdn++;
    $gdn+=$gd; $jdn=$gdn-79; $jnp=intdiv($jdn,12053); $jdn%=12053; $jy=979+33*$jnp+4*intdiv($jdn,1461);
    $jdn%=1461; if($jdn>=366){$jy+=intdiv($jdn-1,365); $jdn=($jdn-1)%365;}
    for($i=0;$i<11 && $jdn>=$jdm[$i];++$i)$jdn-=$jdm[$i]; $jm=$i+1; $jd=$jdn+1; return [$jy,$jm,$jd];
}

function convertToPersianNumbers($input) {
    $persian_digits = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];
    $english_digits = ['0','1','2','3','4','5','6','7','8','9'];
    return str_replace($english_digits, $persian_digits, $input);
}

function sendMessage($chat_id, $text, $keyboard = null, $parse_mode = 'HTML') {
    global $website;

    $url = $website . "sendMessage";

    $post_fields = [
        'chat_id' => $chat_id,
        'text' => $text,
        'parse_mode' => $parse_mode
    ];

    if ($keyboard) {
        // اگر کیبورد آرایه است، آن را به JSON تبدیل کنید
        if (is_array($keyboard)) {
            $post_fields['reply_markup'] = json_encode($keyboard, JSON_UNESCAPED_UNICODE);
        } 
        // اگر کیبورد از قبل JSON است (رشته است و معتبر است)، مستقیماً استفاده کنید
        elseif (is_string($keyboard) && json_decode($keyboard) !== null) {
            $post_fields['reply_markup'] = $keyboard;
        }
        // اگر فرمت نامعتبر است، خطا لاگ کنید
        else {
            error_log('Invalid keyboard format: ' . print_r($keyboard, true));
            return false;
        }
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    if (is_array($post_fields)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_fields));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded'
        ]);
    } else {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    }
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    
    if (curl_errno($ch)) {
        error_log('cURL error: ' . curl_error($ch));
    }
    
    curl_close($ch);
    
    $response = json_decode($result, true);
    if (isset($response['ok']) && $response['ok'] === true) {
        return true;
    } else {
        error_log('Telegram API error: ' . $result);
        return false;
    }
}
