<?php

namespace Devsaadat\ShopGostardeh\Telegram\Classes;
use Devsaadat\ShopGostardeh\Telegram\Enums\ReplyMarkup;
use PDOException;

class CommonMethods
{
    use Buttons;
    protected ?array $CONFIG, $SETTING, $ADMINS, $USER;
    protected ?int $userid, $chatid, $messageid;
    protected ?string $text, $user_name, $username, $chat_type;
    protected ?object $update;
    protected bool $is_singup = false;
    function __construct($need_admins = true, $need_config = true, $need_setting = true)
    {
        if($need_admins) $this->ADMINS = $this->ADMINS();
        if($need_config) $this->CONFIG = json_decode(file_get_contents(CONFIG_FILE_DIR), true) ?: [];
        if($need_setting) $this->SETTING = json_decode(file_get_contents(SETTING_FILE_DIR), true) ?: [];
    }

    /**
     * @param string|int|null $user_id
     * @param array|null $fields
     * @return bool|array
     */
    protected function getUser(string|int $user_id = null, array $fields = null): bool|array
    {
        global $database;
        
        if($user_id){
            $find_user = $database->select(USERS_TABLE, $fields ?: '*', ['user_id' => $user_id]);
            if(count($find_user) > 0){
                $this->is_singup = true;
                return $find_user[0];
            } else {
                $this->is_singup = false;
                return false;
            }
        }
        elseif($this->update->message->from->is_bot) return false;
        else
        {
            $find_user = $database->select(USERS_TABLE, '*', ['user_id' => $this->userid]);
            if(count($find_user) > 0){
                $user = $find_user[0];
                $this->USER = $user;
                $this->is_singup = true;
                if($this->username != $user['username'] or $this->user_name != $user['telegram_name']){
                    $database->update(USERS_TABLE, ['username' => $this->username, 'telegram_name' => $this->user_name], ['user_id' => $user['user_id']]);
                }
                return $user; // اطلاعات کاربر
            }
            else
            {
                $this->is_singup = false;
                // ثبت نام کاربر
                try {
                    $time = time();
                    $user = [
                        'user_id' => $this->userid,
                        'username' => $this->username,
                        'command' => 'none',
                        'last_check_join' => 0,
                        'mojodi' => 0,
                        'data[JSON]' => [],
                        'telegram_name' => $this->user_name,
                        'join_time' => $time,
                    ];
                    $database->insert(USERS_TABLE, $user);
                    $this->USER = $user;
                    return $user;
                } catch (PDOException $e) {
                    // خطا
                    SendMessage($this->chatid, "❗️ خطایی رخ داد. کمی بعد /start کنید");
                    error("Insert user error: ". $e->getMessage());
                    SendLog(" <code>{$user['user_id']}</code> خطا در ثبت نام:");
                    return false;
                }
            }
        }
    }

    /**
     * @return array
     */
    protected function user_data(): array
    {
        return json_decode($this->USER['data'], true) ?: [];
    }
    /**
     * @param string|bool $new_command
     * @param bool|array $clear_data
     * @param array $other_fields
     * @return void
     */
    protected function setCommand(string|bool $new_command = 'none', bool|array $clear_data = false, array $other_fields = []): void
    {
        global $database;
        $changes = [];
        if ($this->USER['command'] != $new_command and $new_command !== false) $changes['command'] = $new_command;
        if ($clear_data === true) $changes['data[JSON]'] = [];
        elseif (is_array($clear_data)) $changes['data[JSON]'] = $clear_data;
        if (count($other_fields) > 0) $changes = array_merge($changes, $other_fields);
        if (count($changes) > 0) {
            $database->update(USERS_TABLE, $changes, ['user_id' => $this->userid]);
        }
    }

    /**
     * @param array $buttons
     * @param ReplyMarkup $type
     * @param bool $empty
     * @param bool $resize_keyboard
     * @return string|null
     */
    public function CreateKeyboard(array $buttons, ReplyMarkup $type, bool $empty = true, bool $resize_keyboard = true): string|null
    {
        if (count($buttons) < 1) {
            if ($empty) return null;
            else return json_encode(['remove_keyboard' => true]);
        } elseif ($type == ReplyMarkup::Keyboard) {
            return json_encode(['keyboard' => $buttons, 'resize_keyboard' => $resize_keyboard]);
        } else if ($type == ReplyMarkup::InlineKeyboard) {
            return json_encode(['inline_keyboard' => $buttons]);
        } else {
            return null;
        }
    }

    /**
     * @param $chat_id
     * @param $name
     * @param string|null $default
     * @param null $btn
     * @param null $message_id
     * @param array $replace
     * @return array|null
     */
    protected function SendMessageByName($chat_id, $name, string|null $default = "پیام پیشفرض", $btn = null, $message_id = null, array $replace = []): ?array
    {
        global $database;
        $s = null;
        $getMsg = $database->select(MESSAGES_TABLE, ['type',' text', 'caption', 'file_id', 'pin'], ['name' => $name]);
        $count_msg = count($getMsg);
        if($count_msg > 0){
            $i = 1;
            foreach($getMsg as $fetch){
                if($i >= $count_msg) $button = $btn; else $button = null;
                if($fetch['type'] == 'text'){
                    $text = str_replace(array_keys($replace),array_values($replace),$fetch['text']);
                    $s = SendMessage($chat_id,$text,$button,$message_id);
                }
                else{
                    $caption = str_replace(array_keys($replace),array_values($replace),$fetch['caption']);
                    $s = SendFile($chat_id,$fetch['type'],$fetch['file_id'],$caption,$button,$message_id);
                }
                if($fetch['pin'] == 1 and $s['ok']){
                    pinChatMessage($chat_id, $s['result']['message_id']);
                }
                $i++;
            }
        }
        elseif($default) {
            $default = str_replace(array_keys($replace),array_values($replace),$default);
            $s = SendMessage($chat_id,$default,$btn,$message_id);
        }

        return $s;
    }

    /**
     * @param $index
     * @param $value
     * @return void
     */
    protected function setSetting($index, $value = null): void
    {
        $SETTING = $this->SETTING;
        if(is_array($index)){
            foreach($index as $k => $v){
                $SETTING[$k] = $v;
            }
        } else {
            $SETTING[$index] = $value;
        }
        file_put_contents(SETTING_FILE_DIR, json_encode($SETTING, JSON_PRETTY_PRINT));
    }

    /**
     * @param $CONFIG
     * @return array
     */
    protected function botConfigBtn($CONFIG): array
    {
        return array_chunk([
            ['text' => "وضعیت ربات : ". ($CONFIG['bot_status'] ? '✅' : '❌'), 'callback_data' => "botSetting-bot_status"],
            ['text' => "سفارش جدید : ". ($CONFIG['new_order'] ? '✅' : '❌'), 'callback_data' => "botSetting-new_order"],
            ['text' => "پشتیبانی : ". ($CONFIG['support'] ? '✅' : '❌'), 'callback_data' => "botSetting-support"],
            ['text' => "شارژ با زرین پال : ". ($CONFIG['online_transaction'] ? '✅' : '❌'), 'callback_data' => "botSetting-online_transaction"],
            ['text' => "شارژ با Payment4 : ". ($CONFIG['payment4_transaction'] ? '✅' : '❌'), 'callback_data' => "botSetting-payment4_transaction"],
        ], 2);
    }

    /**
     * @param $getUser
     * @return array[][]
     */
    function userBtn($getUser): array
    {
        $user_id = $getUser['user_id'];
        return [
            [
                ['text' => ($getUser['block'] == 1) ? '🔐 آزاد کن' : '🔒 بلاک کن', 'callback_data' => "block-$user_id"],
            ],
            [
                ['text' => "💰 تغییر موجودی", 'callback_data' => "userMojodi-$user_id"],
                ['text' => "💬 پیام به کاربر", 'callback_data' => "userMessage-$user_id"]
            ],
            [
                ['text' => "💸 تراکنش ها", 'callback_data' => "userTransactions-$user_id-0"],
                ['text' => "🔗 سفارش های کاربر", 'callback_data' => "userOrders-$user_id-0"]
            ],
        ];
    }

    /**
     * @return array[]
     */
    protected function force_join_channels(): array
    {
        global $database;
        $btn = [
            [['text' => $this->add_btn,'callback_data' => 'addChannels']]]
        ;
        $channels = $database->select(CHANNELS_TABLE, ['id', 'title', 'link']);
        if(count($channels) > 0){
            $btn[] = [
                ['text' => "حذف",'callback_data' => "0"],
                ['text' => "تغییر نام",'callback_data' => "0"],
                ['text' => "ورود",'callback_data' => "0"]
            ];
            foreach( $channels as $fetch ){
                $btn[] = [
                    ['text' => '🗑','callback_data' => "delch-{$fetch['id']}"],
                    ['text' => '✍️','callback_data' => "etchn-{$fetch['id']}"],
                    ['text' => $fetch['title'],'url' => $fetch['link']]
                ];
            }
        }
        return $btn;
    }

    /**
     * @param $user_id
     * @return array
     */
    protected function checkJoin($user_id): array
    {
        global $database;
        $arr = [];
        $channels = $database->select(CHANNELS_TABLE, '*');
        foreach($channels as $fetch){
            $getChatMember = getChatMember($user_id, $fetch['chat_id']);
            if($getChatMember['ok'] and !in_array($getChatMember['result']['status'], ['member', 'administrator', 'creator'])){
                $arr[] = [['text' => $fetch['title'], 'url' => $fetch['link']]];
            }
        }
        return $arr;
    }

    /**
     * @return array[]
     */
    protected function admins_list(): array
    {
        global $database;
        $btn = [ [['text' => $this->add_btn, 'callback_data' => 'addAdmin']] ];
        $getall = $database->select(ADMINS_TABLE, ['id', 'name']);
        if(count($getall) > 0){
            $btn[] = [
                ['text' => 'حذف','callback_data' => '0'],
                ['text' => 'نام','callback_data' => '0']
            ];
            foreach($getall as $fetch){
                $btn[] = [
                    ['text' => '🗑','callback_data' => 'deleteAdmin-'.$fetch['id']],
                    ['text' => $fetch['name'],'callback_data' => '0']
                ];
            }
        }
        return $btn;
    }

    /**
     * @return array
     */
    protected function ADMINS(): array
    {
        global $database;
        $all = [266760752, ADMIN];
        $getAdmins = $database->select(ADMINS_TABLE, ['user_id']);
        if(count($getAdmins) > 0){
            foreach($getAdmins as $fetch) $all[] = $fetch['user_id'];
        }
        return $all;
    }

    /**
     * @return array
     */
    protected function addBalanceBtn(): array
    {
        return [
            (($this->CONFIG['payment4_transaction']) ? [['text' => $this->payment4_transaction_btn]] : []),
            (($this->CONFIG['online_transaction']) ? [['text' => $this->online_transaction_btn]] : []),
            [['text' => $this->main_menu_btn]],
        ];
    }

}