<?php

namespace Bot\BotHandler;

trait UtilityTrait
{

    public function getLabelVehicle($vehicleKey)
    {
        // Use the forms config loaded in the constructor
        $formsConfig = $this->forms ?? include(__DIR__ . '/Forms.php');
        if (isset($formsConfig['tour_creation']['fields']['transport_options']['options'][$vehicleKey])) {
            return $formsConfig['tour_creation']['fields']['transport_options']['options'][$vehicleKey];
        }
        return $vehicleKey;
    }


    public function deleteMessageWithDelay($messageId = null): void
    {
        if ($messageId == null) {
            $messageId =  $this->messageId;
        }

        $this->sendRequest("deleteMessage", [
            "chat_id" => $this->chatId,
            "message_id" => $messageId
        ]);
    }


    public function deleteMessages(array $messageIds): bool
    {
        if (empty($messageIds) || count($messageIds) > 100) {
            return false;
        }
        $data = [
            'chat_id' => $this->chatId,
            'message_ids' => $messageIds
        ];
        $response = $this->sendRequest("deleteMessages", $data);
        return $response['ok'] ?? false;
    }


    public function isValidIranianMobile($mobile)
    {
        // اگر با +98 شروع شده، تبدیلش به 0
        if (strpos($mobile, '+98') === 0) {
            $mobile = '0' . substr($mobile, 3);
        }
        if (strpos($mobile, '98') === 0) {
            $mobile = '0' . substr($mobile, 2);
        }

        // بررسی فرمت شماره ایران
        if (preg_match('/^09\d{9}$/', $mobile)) {
            return true;
        }

        return false;
    }


    public function isValidIranianYear($year)
    {
        return (preg_match('/^\d{4}$/', $year));
    }


    public function isValidIranianIBAN(string $iban): bool
    {
        $iban = strtoupper(str_replace(' ', '', $iban));
        if (strpos($iban, 'IR') === 0) {
            $iban = substr($iban, 2);
        }
        if (strlen($iban) !== 24) {
            return false;
        }
        if (!ctype_digit($iban)) {
            return false;
        }

        $countryCodeNumeric = '1827';

        $bban_part = substr($iban, 2);
        $kk_part = substr($iban, 0, 2);

        $ibanNumeric = $bban_part . $countryCodeNumeric . $kk_part;

        if (function_exists('bcmod')) {
            return bcmod($ibanNumeric, '97') === '1';
        } else {
            $remainder = 0;
            $length = strlen($ibanNumeric);
            for ($i = 0; $i < $length; $i++) {
                $digit = (int)$ibanNumeric[$i];
                $remainder = ($remainder * 10 + $digit);

                if ($remainder >= 97000000) {
                    $remainder %= 97;
                }
            }
            $remainder %= 97;
            return $remainder === 1;
        }
    }


    public function gregorianToJalali($gDate)
    {
        $parts = explode('-', $gDate);
        if (count($parts) !== 3) {
            return $gDate;
        }
        $jalaliArray = jdf::gregorian_to_jalali((int)$parts[0], (int)$parts[1], (int)$parts[2]);
        return sprintf('%04d/%02d/%02d', $jalaliArray[0], $jalaliArray[1], $jalaliArray[2]);
    }


    public function MiladiToShamsi($gDate)
    {
        $gDate = str_replace('/', '-', $gDate); // همه / ها رو به - تبدیل کن
        $parts = explode('-', $gDate);

        if (count($parts) !== 3) {
            return $gDate;
        }

        $jalaliArray = jdf::gregorian_to_jalali((int)$parts[0], (int)$parts[1], (int)$parts[2]);
        return sprintf('%04d/%02d/%02d', $jalaliArray[0], $jalaliArray[1], $jalaliArray[2]);
    }


    public function jalaliToGregorian($jy, $jm, $jd)
    {
        $gregorianArray = jdf::jalali_to_gregorian((int)$jy, (int)$jm, (int)$jd);
        return $gregorianArray; // خروجی یک آرایه است: [year, month, day]
    }


    public function isJalaliDate($dateStr)
    {
        // بررسی فرمت: چهار رقم سال / یک یا دو رقم ماه / یک یا دو رقم روز
        if (preg_match('/^\d{4}\/\d{1,2}\/\d{1,2}$/', $dateStr)) {
            $parts = explode('/', $dateStr);
            $year = (int)$parts[0];
            $month = (int)$parts[1];
            $day = (int)$parts[2];

            // بررسی محدوده سال شمسی (می تونی این عددها رو تنظیم کنی)
            if ($year >= 1300 && $year <= 1500) {
                // بررسی ماه و روز معتبر بودن
                if ($month >= 1 && $month <= 12 && $day >= 1 && $day <= 31) {
                    return true;
                }
            }
        }
        return false;
    }


    private function editTextOrCaption($chatId, $messageId, $text, $replyMarkup = null)
    {
        $params = [
            "chat_id"      => $chatId,
            "message_id"   => $messageId,
            "text"         => $text,
            "parse_mode"   => "HTML"
        ];
        if ($replyMarkup) {
            $params['reply_markup'] = json_encode($replyMarkup);
        }

        $response = $this->sendRequest("editMessageText", $params);

        if (isset($response['ok']) && !$response['ok'] && strpos($response['description'], 'there is no text in the message') !== false) {
            unset($params['text']);
            $params['caption'] = $text;
            $this->sendRequest("editMessageCaption", $params);
        }
    }


    private function cleanReplyMarkup($markup)
    {
        if (is_array($markup)) {
            if (isset($markup['text']) || isset($markup['callback_data']) || isset($markup['url']) || isset($markup['switch_inline_query_current_chat']) || isset($markup['web_app'])) {
                if (isset($markup['style'])) {
                    $validStyles = ['success', 'danger', 'primary', 'secondary'];
                    if (!in_array($markup['style'], $validStyles)) {
                        unset($markup['style']);
                    }
                }
                if (isset($markup['icon_custom_emoji_id'])) {
                    $text = $markup['text'] ?? '';
                    $cleanText = preg_replace('/[\x{1F600}-\x{1F64F}\x{1F300}-\x{1F5FF}\x{1F680}-\x{1F6FF}\x{1F700}-\x{1F77F}\x{1F780}-\x{1F7FF}\x{1F800}-\x{1F8FF}\x{1F900}-\x{1F9FF}\x{1FA00}-\x{1FA6F}\x{1FA70}-\x{1FAFF}\x{2600}-\x{26FF}\x{2700}-\x{27BF}\x{2300}-\x{23FF}\x{2B50}\x{2B55}\x{2934}\x{2935}\x{25AA}\x{25AB}\x{25B6}\x{25C0}\x{25FB}\x{25FC}\x{25FD}\x{25FE}]/u', '', $text);
                    $markup['text'] = trim($cleanText);
                }
            } else {
                foreach ($markup as $key => $value) {
                    $markup[$key] = $this->cleanReplyMarkup($value);
                }
            }
        }
        return $markup;
    }


    public function sendRequest($method, $data)
    {
        if (isset($data['reply_markup'])) {
            $markup = $data['reply_markup'];
            if (is_string($markup)) {
                $markup = json_decode($markup, true);
            }
            if (is_array($markup)) {
                $markup = $this->cleanReplyMarkup($markup);
                $data['reply_markup'] = $markup; // keep it as array since it will be json_encoded below
            }
        }

        $url = "https://api.telegram.org/bot" . $this->botToken . "/$method";

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_errno($ch) ? curl_error($ch) : null;
        curl_close($ch);

        $this->logTelegramRequest($method, $data, $response, $httpCode, $curlError);

        if ($curlError) {
            return false;
        }

        if ($httpCode >= 200 && $httpCode < 300) {
            return json_decode($response, true);
        } else {
            $errorResponse = json_decode($response, true);
            $errorMessage = $errorResponse['description'] ?? 'Unknown error';
            return false;
        }
    }


    private function logTelegramRequest($method, $data, $response, $httpCode, $curlError = null): void
    {
        $logData = [
            'time' => date("Y-m-d H:i:s"),
            'method' => $method,
            'request_data' => $data,
            'response' => $response,
            'http_code' => $httpCode,
            'curl_error' => $curlError
        ];

        $logMessage = json_encode($logData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        // error_log("TELEGRAM API LOG: " . $logMessage);
    }


    private function checkUserStatus($userId): bool
    {
        $user = $this->db->getUserByChatId($userId);
        if ($user && isset($user['status']) && $user['status'] === 'blocked') {
            $this->sendRequest("sendMessage", [
                "chat_id" => $userId,
                "text" => "🚫 حساب کاربری شما مسدود شده است و امکان استفاده از ربات را ندارید.\n پشتیبانی  @Arcbau"
            ]);
            return true;
        }
        return false;
    }

}
