<?php



include("asl.php");


error_reporting(E_ALL);
ini_set('display_errors', 0);



?>



<!DOCTYPE HTML>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html ; charset=utf-8" />
    <meta http-equiv="content-type" content="text/html" />
    <meta name="author" content="persian" />

    <title>Telegram Bot</title>


    <link rel="Stylesheet" type="text/css" href="style.css" />





</head>

<body dir="rtl" align="center" style="font-family:Tahoma !important">
    <div align="center">
        <?php

        //    import_request_variables("p" , "a_");
        $a_pass = $_POST["pass"];
        $a_user = $_POST["user"];
        $a_mykey = $_POST["mykey"];
        $a_answer = $_POST["answer"];
        $a_myarakeys = $_POST["myarakeys"];
        $a_newuser = $_POST["newuser"];
        $a_newpass = $_POST["newpass"];
        $a_noa = $_POST["noa"];
        $a_shenase = $_POST["shenase"];
        $a_chatid = $_POST["chatid"];
        $a_text = $_POST["text"];
        $a_pfrom = $_POST["pfrom"];
        $a_pto = $_POST["pto"];


        try {
            $conn = new PDO("mysql:host=$servername;dbname=$mydb", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            // set the PDO error mode to exception

            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            echo "Connection failed: " . $e->getMessage();
        }






        $sql = "select * from admin";
        $stmt = $conn->prepare($sql);
        $stmt->execute();

        $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $show = $stmt->fetch();

        $user = $show["user"];
        $pass = $show["pass"];


        $getpass = hash_hmac('md5', $a_pass, 'salt');





        // if ($user == $a_user && $pass == $getpass) {








        //     if ($a_newuser == "") {
        //     } else {

        //         $newpass = hash_hmac('md5', $a_newpass, salt);
        //         $sql = "update admin set user = \"$a_newuser\"  , pass=\"$newpass\"  ";
        //         $conn->exec($sql);
        //         echo "<p style='color:green' >Done</p>";



        //         function redirect($url)
        //         {
        //             if (!headers_sent()) {
        //                 header('Location: ' . $url);
        //                 exit;
        //             } else {
        //                 echo '<script type="text/javascript">';
        //                 echo 'window.location.href="' . $url . '";';
        //                 echo '</script>';
        //                 echo '<noscript>';
        //                 echo '<meta http-equiv="refresh" content="0;url=' . $url . '" />';
        //                 echo '</noscript>';
        //                 exit;
        //             }
        //         }
        //         redirect("enter.php");
        //     }
        // } else {
        //     echo "<p style='color:red' >Wrong username or password</p><br />
        //               <a href='enter.php' target='_blank' >back</a>
              
        //               ";



        //     function redirect($url)
        //     {
        //         if (!headers_sent()) {
        //             header('Location: ' . $url);
        //             exit;
        //         } else {
        //             echo '<script type="text/javascript">';
        //             echo 'window.location.href="' . $url . '";';
        //             echo '</script>';
        //             echo '<noscript>';
        //             echo '<meta http-equiv="refresh" content="0;url=' . $url . '" />';
        //             echo '</noscript>';
        //             exit;
        //         }
        //     }




        //     redirect("enter.php");
        // }


        // $sql = "SELECT * FROM admin WHERE user = :user";
        // $stmt = $conn->prepare($sql);
        // $stmt->execute(['user' => $a_user]);
        // $show = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // if ($show && hash_hmac('md5', $a_pass, 'salt') === $show['pass']) {
        //     $_SESSION['logged_in'] = true;
        //     $_SESSION['user'] = $a_user;
        
        //     if (!empty($a_newuser) && !empty($a_newpass)) {
        //         $newpass = hash_hmac('md5', $a_newpass, 'salt');
        //         $update_sql = "UPDATE admin SET user = :newuser, pass = :newpass WHERE user = :user";
        //         $update_stmt = $conn->prepare($update_sql);
        //         $update_stmt->execute(['newuser' => $a_newuser, 'newpass' => $newpass, 'user' => $a_user]);
        //         echo "<p style='color:green'>Credentials updated successfully. Please log in again.</p>";
        //     }
        //     // redirect("index.php");
        // } else {
        //     echo "<p style='color:red'>Invalid username or password.</p>";
        //     redirect("enter.php");
        // }
        
        // function redirect($url)
        // {
        //     header('Location: ' . $url);
        //     exit;
        // }





        function sendmessage($text, $chatid, $keys)
        {

            $send = "https://api.telegram.org/bot7960487515:AAEMtNS9awV-szQA5J1wC40a_bADwghlakU/sendmessage?chat_id=$chatid&text=$text&parse_mode=Html&reply_markup=$keys";
            $sended = file_get_contents($send);
            return $sended;
        }

        function sendphoto($address, $chatid, $key, $caption)
        {


            $bot_url = "https://api.telegram.org/bot7960487515:AAEMtNS9awV-szQA5J1wC40a_bADwghlakU/";
            $url = $bot_url . "sendPhoto?caption=$caption&chat_id=" . $chatid;
            $ch = curl_init();
            curl_setopt(
                $ch,
                CURLOPT_HTTPHEADER,
                array(
                    "Content-Type:multipart/form-data"
                )
            );
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt(
                $ch,
                CURLOPT_POSTFIELDS,
                array(
                    "photo" => "@" . "upload/" . $address,
                )
            );
            curl_setopt($ch, CURLOPT_INFILESIZE, filesize("upload/" . $address));
            $output = curl_exec($ch);
        }





        if ($a_noa == "sndmsg") {



            if (!$_FILES['myfile']['name'] == "" && $_FILES["myfile"]["error"] == 0) {




                $ext = end(explode('.', $_FILES['myfile']['name']));

                $formats = array('jpg', 'JPG', 'gif', 'GIF', 'png', 'PNG', 'RAR', 'rar', 'ZIP', 'zip', 'mp4', '3gp', 'mov');
                if (!in_array($ext, $formats)) {

                    print "<p style='color:green' >پسوند معتبر برای آپلود نیست</p>";
                } elseif (file_exists('upload/' . $_FILES["myfile"]["name"])) {
                    print "<p style='color:green' >متاسفیم این فایل قبلا اپلود شده لطفا نام ان را تغییر دهید</p>";
                } elseif (536870912 < $_FILES["myfile"]["size"]) {


                    print "<p style='color:green' >سایز فایل باید کمتر از نیم گیگ باشد</p>";
                } else {
                    $path = "upload/" . $_FILES["myfile"]["name"];
                    move_uploaded_file($_FILES["myfile"]["tmp_name"], $path);
                    print "
        <span class='green' >
        اپلود با موفقیت انجام 
        شد
        </span>
        ";
                }
                $namemyfile = $_FILES["myfile"]["name"];
            }

            if ($namemyfile == "" || $namemyfile == " ") {
            } else {
                print $namemyfile;
                sendphoto($namemyfile, $a_chatid, "", $caption);
            }
            sendmessage(urlencode("$a_text"), $a_chatid, "");

            print "sent";


            $sql = "insert into messages (chatid,text) values (\"$a_chatid\",\"$a_text\")";
            $conn->exec($sql);
        }


        function generateTelegramInviteLink($chatId) {

            $exTime = time() + 300;

            // Endpoint for creating chat invite link
            $url = "https://api.telegram.org/bot7960487515:AAEMtNS9awV-szQA5J1wC40a_bADwghlakU/createChatInviteLink";
        
            // Initialize cURL session
            $ch = curl_init();
        
            // Set cURL options
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
                'chat_id' => $chatId, 
                'expire_date' => $exTime,
                'member_limit' =>1

            ]));
        
            // Execute cURL session
            $response = curl_exec($ch);
        
            // Close cURL session
            curl_close($ch);
        
            // Decode the JSON response
            $response = json_decode($response, true);
        
            // Check if the request was successful
            if (!$response['ok']) {
                throw new Exception("Failed to generate invite link: " . $response['description']);
            }
        
            // Return the invite link
            return $response['result'];
        }


        ?>


        <br /><br />
        <h4 class="white">Admin Panel</h4>
        <div id="content" align="right">
            <div id="content-content">
                <table>
                    <tr>
                        <td><img class="radius" src="images/user.png" /></td>
                        <td class="gray" valign="bottom">خوش آمدید

                            <?php print $userse; ?>
                        </td>

                        <td>
                            <form  method='post' action='index.php'>


<input type='submit' style='width:100%' class='font' value='صفحه ی اصلی ' />
<input type='hidden' name='user' value="<?php echo $a_user ?>" />
<input type='hidden' name='pass' value="<?php echo $a_pass ?>" class='font' />
</form>
                            </td>
                       

                    </tr>

                </table>




                <br />
                <br />


                <br />
                <div id="fish">



                    <h5 class='gray'>◄ ارسال پیام تکی</h5>

                    <form enctype='multipart/form-data' method='post' action='users.php'>

                        <input type='hidden' name='user' value="<?php echo $a_user ?>" />
                        <input type='hidden' name='pass' value="<?php echo $a_pass ?>" />
                        <input type='hidden' name='noa' value="sndmsg" />


                        <table>
                            <tr>

                                <th class='th'>چت ایدی</th>
                                <th class='th'>متن</th>

                                <th class='th'>ارسال</th>

                            </tr>






                            <tr>

                                <td class='td'><input type='text' name='chatid' /> </td>

                                <td class='td'><textarea type='text' name='text'></textarea> </td>



                                <td class='td'><input style='width:100%' type='submit' value='تنظیم' /> </td>


                            </tr>











                        </table>
                    </form>



                    <h5 class='gray'>◄ نمایش کل کاربران</h5>

                    <?php
                    if ($_POST['noa'] == 'add_subscription') {
                        $now = time();
                        $stmt = $conn->prepare("SELECT * FROM user where expire_time > $now ");
                        $stmt->execute();
                        $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
                        $getter = $stmt->fetchAll();
                        $num = $stmt->rowCount();
                        foreach ($getter as $singleGetter) {

                            $expireTime = $singleGetter['expire_time'] + ($_POST['num_days'] * 24 * 3600);
                            $sql = "update user set expire_time='" . $expireTime . "' where chatid='" . $singleGetter['chatid'] . "' ";
                            $conn->exec($sql);
                            print("<hr />" . $singleGetter['chatid'] . " Added " . $_POST['num_days'] . " Days <hr />");
                        }
                    }


                    ?>
                    <!-- <form method='post' action='users.php'>
                        <input style='width:98%' name='num_days' placeholder='اضافه به کل کاربران (روز)' class='font' />
                        <input type='hidden' name='noa' value='add_subscription' />
                        <input type='hidden' name='user' value='<?php print $a_user; ?>' />
                        <input type='hidden' name='pass' value='<?php print $a_pass; ?>' />
                        <input type='submit' style='width:100%' value='ثبت' class='font' />
                    </form> -->

                    <table style='width:100%'>
                        <tr>

                            <th class='th'></th>
                            <th class='th'> اطلاعات تلگرام</th>
                            <th class='th'>اطلاعات کانال</th>



                        </tr>
                        <tr>





                            <?php

                            include('class/bot.php');
                            $bot = new bot("7960487515:AAEMtNS9awV-szQA5J1wC40a_bADwghlakU", $content);



                            function unbanUserFromChannel($channelId, $userId) {
                                // Telegram API URL
                                $apiUrl = "https://api.telegram.org/bot7960487515:AAEMtNS9awV-szQA5J1wC40a_bADwghlakU/unbanChatMember";
                            
                                // Initialize cURL session
                                $ch = curl_init();
                            
                                // Set cURL options
                                curl_setopt($ch, CURLOPT_URL, $apiUrl);
                                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                curl_setopt($ch, CURLOPT_POST, true);
                                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
                                    'chat_id' => $channelId,
                                    'user_id' => $userId
                                ]));
                            
                                // Execute the cURL request and get the response
                                $response = curl_exec($ch);
                                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            
                                // Check for cURL errors
                                if (curl_errno($ch)) {
                                    echo 'Curl error: ' . curl_error($ch);
                                }
                            
                                // Close cURL session
                                curl_close($ch);
                            
                                // Handle the response
                                if ($httpCode == 200) {
                                    return json_decode($response, true);
                                } else {
                                    return [
                                        'error' => true,
                                        'message' => 'Failed to unban user',
                                        'status_code' => $httpCode,
                                        'response' => $response
                                    ];
                                }
                            }
                            
                            

                            if ($_POST['noa'] == 'change_subscription') {
                                $newTime = time() + ($_POST['num_days'] * 24 * 3600);

                                $sql = "update user set status='monthly',expire_time='" . $newTime . "'  where chatid='" . $_POST['chatid'] . "' ";
                                $conn->exec($sql);

                                print("<script>alert('تنظیمات انجام شد');</script>");
                            } elseif ($_POST['noa'] == 'block_user') {
                                $bot->sendmessage(urlencode("اشتراک شما به اتمام رسید"), $_POST['chatid'], '');

                                $bot->banMember($_POST['chatid'], -1002749114245);
                                $sql = "update user set status=\"inactive\", expire_time='0' where chatid='" . $_POST['chatid'] . "' ";
                                $conn->exec($sql);

                            }
                            
                            
                            
                            
                            elseif ($_POST['noa'] == 'invite_user') {

                                $expireTime = time() + (30 * 24 * 3600);
                                $sql = "update user set status=\"monthly\" , expire_time=\"$expireTime\" where chatid='" . $_POST['chatid'] . "' ";
                                $conn->exec($sql);

                                $channelId = -1002749114245;
                                // $bot->unBanMember($_POST['chatid'], $channelId);
                                unbanUserFromChannel($channelId, $_POST['chatid']);

                                // $vipChannel = $bot->getChannelLink($channelId);
                                $vipChannel = generateTelegramInviteLink($channelId)['invite_link'];

                         ;
                         $keyboard = json_encode([
                            'inline_keyboard' => [
                                [
                                    ['text' => "📎 لینک ورود به کانال", 'url' => $vipChannel]
                                ]
                            ]
                        ]);
                        

                                // print($vipChannel);
                                $bot->sendmessage(urlencode("
⚠️دقت کنید این لینک یکبار مصرف می‌باشد
                                "), $_POST['chatid'], $keyboard);

                        print("here 5");

                            }




                            elseif ($_POST['noa'] == 'change_subscription_two') {
                                $newTime = time() + ($_POST['num_days'] * 24 * 3600);

                                $sql = "update user set status2='monthly',expire_time_two='" . $newTime . "'  where chatid='" . $_POST['chatid'] . "' ";
                                $conn->exec($sql);

                                print("<script>alert('تنظیمات انجام شد');</script>");
                            } elseif ($_POST['noa'] == 'block_user_two') {
                                $bot->sendmessage(urlencode("اشتراک شما به اتمام رسید"), $_POST['chatid'], '');

                                $bot->banMember($_POST['chatid'], -1002749114245);
                                $sql = "update user set status2=\"inactive\", expire_time_two='0' where chatid='" . $_POST['chatid'] . "' ";
                                $conn->exec($sql);

                            } elseif ($_POST['noa'] == 'invite_user_two') {

                                $expireTime = time() + (30 * 24 * 3600);
                                $sql = "update user set status2=\"monthly\" ,pay_time='" . time() . "',expire_time_two=\"$expireTime\" where chatid='" . $_POST['chatid'] . "' ";
                                $conn->exec($sql);
                                // print($sql);


                                $channelId = -1002749114245;
                                $bot->unBanMember($_POST['chatid'], $channelId);
                                // $vipChannel = $bot->getChannelLink($channelId);
                                $vipChannel = generateTelegramInviteLink($channelId)['invite_link'];
                         ;
                         $keyboard = json_encode([
                            'inline_keyboard' => [
                                [
                                    ['text' => "📎 لینک ورود به کانال", 'url' => $vipChannel]
                                ]
                            ]
                        ]);
                        
                                // print($vipChannel);
                                $bot->sendmessage(urlencode("
⚠️دقت کنید این لینک یکبار مصرف می‌باشد
                                "), $_POST['chatid'], $keyboard);
                            }



                            $stmt = $conn->prepare("SELECT * FROM user");
                            $stmt->execute();
                            $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
                            $k = $stmt->fetchAll();
                            $num = $stmt->rowCount();
                            print " <h5 class='gray'>◄ تعداد کاربران: $num</h5>";
                            foreach ($k as $index => $v) {
                                if(empty($v['chatid'])){
                                    continue;
                                }
                                $expire_time = $v["expire_time"];

                                
                                $remain = round(($expire_time - time()) / (24 * 3600));
                                if($remain <= 0){ $remain = 0; }
                               
                                // $expire_time_two = $v["expire_time_two"];
                                // $remain_two = round(($expire_time_two - time()) / (24 * 3600));
                                // if($remain_two <= 0){ $remain_two = 0; }


                                print "
<tr>
<td align='center' class='td' style='width: 10%;' >". $index+1 ."</td>
<td align='center' class='td'  >" . $v["telname"] . " <br /> " . $v["telfamily"] . " <br /> " . $v["username"] . " <br /> " . $v["chatid"] . " <br /> " . $v["phone"] . "</td>
<td align='center' class='td'  >
<br />
$remain روز مانده
<br />
<p>افزایش یا کاهش روز های باقیمانده:  </p>
<form  method='post' action='users.php' >
<input  name='num_days' placeholder='روز های باقی مانده'   class='font' />
<input  type='hidden' name='noa' value='change_subscription' />
<input  type='hidden' name='user' value='$a_user'  />
<input  type='hidden' name='pass' value='$a_pass'  />
<input  type='hidden' name='chatid' value='" . $v['chatid'] . "'  />
<input type='submit' style='width:100%'  value='ارسال' class='font' />
</form>
<p>کیک یوزر :  </p>
<form  method='post' action='users.php' >
<input  type='hidden' name='noa' value='block_user' />
<input  type='hidden' name='user' value='$a_user'  />
<input  type='hidden' name='pass' value='$a_pass'  />
<input  type='hidden' name='chatid' value='" . $v['chatid'] . "'  />
<input type='submit' style='width:100%'  value='Force Remove'  />
</form>
<p>اکتیو کردن و ارسال لینک به کاربر :  </p>
<form  method='post' action='users.php' >
<input  type='hidden' name='noa' value='invite_user' />
<input  type='hidden' name='user' value='$a_user'  />
<input  type='hidden' name='pass' value='$a_pass'  />
<input  type='hidden' name='chatid' value='" . $v['chatid'] . "'  />
<input type='submit' style='width:100%'  value='One month activation'  />
</form>
</td>



</tr>

        
        ";
                            }

                            ?>










                        </tr>



                    </table>

















                    <hr />
                    <hr />
                    <hr />

                    <br />
                    <br />
                    <br />
                    <br />






                </div>



















                <br />
                <br />
            </div>
        </div>




        <a style="text-decoration:none ;" href="#" target="_blank" class="gray">#</a>
    </div>

    <?php
    $conn = null;
    ?>
</body>

</html>
<?php
$conn = null;
?>
</body>

</html>
<?php
$conn = null;
?>
</body>

</html>