<?php 

class Methods
{
    private $db, $bot;
    public function __construct($db, $bot)
    {
        $this->db = $db;
        $this->bot = $bot;
    }
    
    public function downloadFile($fileID, $FromId, $lock= 'lock', $seen= 1, $archive = 0)
    {
        global $Back; $db = $this->db; $bot = $this->bot;
        if($db->query("SELECT `code` FROM `files` WHERE `code`= '{$fileID}'")->num_rows > 0){
            $query = $db->query("SELECT * FROM `files` WHERE `code`= '{$fileID}' LIMIT 1")->fetch_assoc();
            $settings = $db->query("SELECT * FROM `panel` WHERE `rowID`= '85' LIMIT 1")->fetch_assoc();
            $texts = $db->query("SELECT * FROM `bot_texts` WHERE `rowID`= '85' LIMIT 1")->fetch_assoc();
            if($seen== 1 && $settings['viewChannel']== 1 && $texts['viewchannel']!= '' && $db->query("SELECT `chatType` FROM `channel_set` WHERE `chatType`= '1'")->num_rows> 0){
                $select_channel = $db->query("SELECT * FROM `channel_set` WHERE `chatType`= '1' LIMIT 1")->fetch_assoc();
                $viewtime = time() + $texts['viewTime'];
                $bot->sendMessage(['chat_id'=> $FromId, 'text'=> $texts['viewchannel'], 'parse_mode'=> 'html', 'reply_markup'=> json_encode(['inline_keyboard'=> [
                    [['text'=> "مشاهده کانال 👁", 'url'=> $select_channel['chatLink']]],
                    [['text'=> "✅مشاهده کردم", 'callback_data'=> "vich^{$query['rowID']}^{$viewtime}"]]
                ]])]);
                die;
            } else {
                if($query['passwordSet']== '' || $lock== 'unlock'){
                    $fa_type = str_replace('multi', 'گالری ', $query['fileType']);
                    $fa_type = str_replace(['photo', 'video', 'document', 'audio', 'animation', 'voice', 'video_note'], ['عکس', 'ویدئو', 'فایل', 'موسیقی', 'گیف', 'ویس', 'ویدئو نوت'], $fa_type);
                    $_time = ($texts['delayTime'] >= 60 ? ($texts['delayTime']/60).' دقیقه' : $texts['delayTime'].' ثانیه');
                    $_delay = time() + $texts['delayTime'];
                    $select_channel = $db->query("SELECT * FROM `channel_set` WHERE `chatType`= '2' LIMIT 1")->fetch_assoc();
                    if($db->query("SELECT * FROM `downloads` WHERE (`userID`= '{$FromId}' AND `mainFile`= '{$query['rowID']}')")->num_rows < 1)
                        $downloadCount = $query['downloadCount'] + 1;
                    else $downloadCount = $query['downloadCount'];
                    $keyboard= null; $key= [];
                    if($settings['downloadCount']== 1)
                        $key[]= [['text'=> "📥 تعداد دریافت: - {$downloadCount} -", 'callback_data'=> 'notset']];
                    if($settings['likesOption']== 1)
                        $key[]= [['text'=> "👍 ( {$query['likeCount']} )", 'callback_data'=> "like@0@{$fileID}"], ['text'=> "👎 ( {$query['disslikeCount']} )", 'callback_data'=> "disslike@0@{$fileID}"]];
                    if($db->query("SELECT `chatType` FROM `channel_set` WHERE `chatType`= '2'")->num_rows > 0)
                        $key[]= [['text'=> $select_channel['chatTitle'], 'url'=> $select_channel['chatLink']]];
                    if(count($key)> 0)
                        $keyboard= json_encode(['inline_keyboard'=> $key]);
                    $msgid_list= [];
                    $type = str_replace('multi', '', $query['fileType']);
                    if(preg_match('/^(multi(.*))$/', $query['fileType'])){
                        if($settings['groupDownload']== 1){
                            $num = 0;
                            for($n= 0; $n< count(explode(', ', $query['fileID'])); $n++){
                                $media= []; $result= [];
                                for($i = $num; $i < ($num + 10); $i++)
                                    if(explode(', ', $query['fileID'])[$i] != null) $media[] = ['type'=> $type, 'media'=> explode(', ', $query['fileID'])[$i], 'parse_mode'=> 'html'];
                                foreach($media as $k1=> $v1) $result[$k1]= $v1;
                                $result[count($media)- 1]['caption']= end(explode(', ', $query['fileCaption']));
                                $post = $bot->req('sendMediaGroup', ['chat_id'=> $FromId, 'media'=> json_encode($result), 'protect_content'=> ($settings['protectContent']> 0 ? true : false)])->result;
                                foreach($post as $msgid) $msgid_list[]= $msgid->message_id;
                                $num+= 10;
                            } $bot->sendMessage(['chat_id'=> $FromId, 'text'=> "{$fa_type} مورد نظر با موفقیت برای شما ارسال گردید.", 'reply_to_message_id'=> end($msgid_list), 'reply_markup'=> $keyboard]);
                            if($settings['antiFilter']== 1 and $archive == 0){
                                $reply = $bot->sendMessage(['chat_id'=> $FromId, 'text'=> ($texts['antiFilter']!= '' ? $texts['antiFilter'] : "{$fa_type} تا {$_time} دیگر حذف میشود.\nلطفا {$fa_type} مورد نظر را در Saved Messages خود ذخیره کنید."), 'reply_to_message_id'=> end($msgid_list)])->result;
                                foreach($msgid_list as $msgid)
                                    $db->query("INSERT INTO `dFile`(`userID`, `msgID`, `delay`) VALUES ('{$FromId}', '{$msgid}', '{$_delay}')");
                                $db->query("INSERT INTO `dFile`(`userID`, `msgID`, `delay`) VALUES ('{$FromId}', '{$reply->message_id}', '{$_delay}')");
                            }
                        } else {
                            for($i= 0; $i< count(explode(', ', $query['fileID'])); $i++){
                                $media= [];
                                $media= ['chat_id'=> $FromId, strtolower($type)=> explode(', ', $query['fileID'])[$i], 'caption'=> explode(', ', $query['fileCaption'])[$i], 'parse_mode'=> 'html', 'protect_content'=> ($settings['protectContent']> 0 ? true : false), 'reply_markup'=> $keyboard];
                                $post = $bot->req('send'.ucfirst($type), $media)->result;
                                $msgid_list[]= $post->message_id;
                            }
                            if($settings['antiFilter']== 1 and $archive == 0){
                                $reply = $bot->sendMessage(['chat_id'=> $FromId, 'text'=> ($texts['antiFilter']!= '' ? $texts['antiFilter'] : "{$fa_type} تا {$_time} دیگر حذف میشود.\nلطفا {$fa_type} مورد نظر را در Saved Messages خود ذخیره کنید."), 'reply_to_message_id'=> end($msgid_list)])->result;
                                foreach($msgid_list as $msgid)
                                    $db->query("INSERT INTO `dFile`(`userID`, `msgID`, `delay`) VALUES ('{$FromId}', '{$msgid}', '{$_delay}')");
                                $db->query("INSERT INTO `dFile`(`userID`, `msgID`, `delay`) VALUES ('{$FromId}', '{$reply->message_id}', '{$_delay}')");
                            }
                        }
                    } else {
                        $media= [];
                        $media= ['chat_id'=> $FromId, strtolower($query['fileType'])=> $query['fileID'], 'caption'=> $query['fileCaption'], 'parse_mode'=> 'html', 'protect_content'=> ($settings['protectContent']> 0 ? true : false), 'reply_markup'=> $keyboard];
                        $post = $bot->req('send'.ucfirst($query['fileType']), $media)->result;
                        if($settings['antiFilter']== 1 and $archive == 0){
                            $reply = $bot->sendMessage(['chat_id'=> $FromId, 'text'=> ($texts['antiFilter']!= '' ? $texts['antiFilter'] : "{$fa_type} تا {$_time} دیگر حذف میشود.\nلطفا {$fa_type} مورد نظر را در Saved Messages خود ذخیره کنید."), 'reply_to_message_id'=> $post->message_id])->result;
                            $db->query("INSERT INTO `dFile`(`userID`, `msgID`, `delay`) VALUES ('{$FromId}', '{$post->message_id}', '{$_delay}')");
                            $db->query("INSERT INTO `dFile`(`userID`, `msgID`, `delay`) VALUES ('{$FromId}', '{$reply->message_id}', '{$_delay}')");
                        }
                    } if($settings['resendButton']== 1 and $archive == 0) $bot->sendMessage(['chat_id'=> $FromId, 'text'=> "پس از حذف فایل بالا، میتوانید توسط کیبورد زیر فایل را مجدد دریافت نمایید ♻️", 'reply_markup'=> json_encode(['inline_keyboard'=> [
                        [['text'=> "دریافت مجدد فایل ♻️", 'url'=> "https://t.me/{$bot->getMe([])->result->username}?start=file_{$fileID}"]]
                    ]])]);
                    $db->query("UPDATE `files` SET `downloadCount`= '{$downloadCount}' WHERE `code`= '{$fileID}' LIMIT 1");
                    if($db->query("SELECT * FROM `downloads` WHERE (`userID`= '{$FromId}' AND `mainFile`= '{$query['rowID']}')")->num_rows < 1)
                        $db->query("INSERT INTO `downloads`(`userID`, `mainFile`) VALUES ('{$FromId}', '{$query['rowID']}')");
                    $db->query("UPDATE `users` SET `Step`= 'none' WHERE `userID`= '{$FromId}' LIMIT 1");
                } else {
                    $bot->sendMessage(['chat_id'=> $FromId, 'text'=> '🔐 پسورد فایل مورد نظر را ارسال کنید :', 'reply_markup'=> $Back]);
                    $db->query("UPDATE `users` SET `Step`= 'filePass-{$fileID}' WHERE `userID`= '{$FromId}' LIMIT 1");
                }
            }
        } else $bot->sendMessage(['chat_id'=> $FromId, 'text'=> "فایل با آیدی ( <code>{$fileID}</code> ) در دیتابیس ربات یافت نشد.", 'parse_mode'=> 'html']);
        return true;
    }
    
    public function saveFile($FromId, $files, $covers= '', $password= '')
    {
        $db = $this->db; $bot = $this->bot; $fileID= ''; $captions= '';
        if(count($files['fileID'])> 1){
            foreach($files['fileID'] as $file_id)
                $fileID .= "{$file_id}, ";
            $fileID = substr($fileID, 0, -2);
        } else $fileID= end($files['fileID']);
        if(count($files['fileCaption'])> 1){
            foreach($files['fileCaption'] as $caps)
                $captions .= "{$caps}, ";
            $captions = substr($captions, 0, -2);
        } else $captions= end($files['fileCaption']);
        $covers['coverType'] = $covers=='' ? '' : $covers['coverType'];
        $covers['coverID'] = $covers=='' ? '' : $covers['coverID'];
        $covers['coverCaption'] = $covers=='' ? '' : $covers['coverCaption'];
        $code = $this->passwordCreator();
        $_time = time();
        $db->query("INSERT INTO `files`(`userID`, `code`, `fileType`, `fileID`, `fileCaption`, `coverType`, `coverID`, `coverCaption`, `passwordSet`, `fileDTime`) VALUES ('{$FromId}', '{$code}', '{$files['fileType']}', '{$fileID}', '{$captions}', '{$covers['coverType']}', '{$covers['coverID']}', '{$covers['coverCaption']}', '{$password}', '{$_time}')");
        if($db->affected_rows > 0)
            return true;
        else return false;
    }
    
    public function passwordCreator($limit= 8)
    {
        $result= ""; $list_of_word = "QWERTYUIOPASDFGHJKLZXCVBNM-_qwertyuiopasdfghjklzxcvbnm0123456789";
        for($i=0; $i< $limit; $i++)
            $result .= $list_of_word[rand(0, strlen($list_of_word))];
        return $result;
    }
}