<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>Hello!</title>
    <meta http-equiv="Content-Type" content="text/html ; charset=utf-8" />
</head>

<body>
    <?php
    error_reporting(E_ALL);
    ini_set('display_errors', '0');



    function connectd()
    {


        include("asl.php");
        $conn = new PDO("mysql:host=$servername;dbname=$mydb", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"));
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $conn;
    }
    $conn = connectd();

    include('functions.php');
    include('class/bot.php');





    $content = file_get_contents("php://input");
    $update = json_decode($content, true);
    $message = $update["message"];
    print_r($message);

    

    $fileidBest = $message['photo'][4]['file_id'];
    $fileidGood = $message['photo'][3]['file_id'];
    $fileid = $message['photo'][2]['file_id'];
    $fileidBad = $message['photo'][1]['file_id'];
    $fileidVeryBad = $message['photo'][0]['file_id'];
    $documentFileId = $message['document']['file_id'];



    $recmsg = $message['text'];
    $message_id = $message['message_id'];
    $chatid = $message['chat']['id'];
    $username = $message['from']['username'];
    $firstname = $message['from']['first_name'];
    $lastname = $message['from']['last_name'];

    $myphone = $message["contact"]["phone_number"];
    $message_id = $message['message_id'];
    $myphone = $message["contact"]["phone_number"];
    $datamytext = $update["callback_query"]["data"];
    $datachatid = $update["callback_query"]["from"]["id"];
    if ($chatid == '') {
        $recmsg = $datamytext;
        $chatid = $datachatid;
    }



// if ($chatid == '80433998' || $chatid == '5803067539' || $chatid == '732200331' || $chatid == '6691188752' || $chatid == '5997320431') {
//         sendmessage(urlencode("The meesage id is : $message_id"), $chatid, '');
//         $sql = "insert into file_data (message_id,from_chat_id) values (\"$message_id\",\"$chatid\")";
//         $conn->exec($sql);
//  }

    ifnewuserinsert($chatid, $username, $firstname, $lastname, $conn, $myphone, $recmsg);


    // if(inchannel($chatid, '@asdfasdfasdfassre') != 'ok') {

    //     $key = json_encode(
    //         array(
    //             "inline_keyboard" => array(
    //                 array(
    //                     array("url" => "https://t.me/asdfasdfasdfassre", "text" => urlencode("📣 عضویت در کانال")),
    //                 ),
    //                 array(
    //                     array("callback_data" => "/start", "text" => urlencode("✅ عضو شدم")),
    //                 ),
    //             )
    //         )
    //     );
    //     $text = "برای استفاده از این ربات شما باید عضو کانال رسمی ما شده باشید.
    
    //     لطفا در کانال @asdfasdfasdfassre عضو شوو روی دکمه ی عضو شدم کلیک کن";
    //     sendmessage(urlencode($text), $chatid, $key);
    
    
    //     exit(); 
    // }


    $stmt = $conn->prepare("SELECT * FROM admin ");
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $resultAdmin = $stmt->fetchAll();
    $numrowAdmin = $stmt->rowCount();

    $channel1 = $resultAdmin[0]['channel1'];
    $channel2 = $resultAdmin[0]['channel2'];
    $AdminTtext = $resultAdmin[0]['text'];

    $stmt = $conn->prepare("SELECT * FROM user where chatid=\"$chatid\" ");
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $result = $stmt->fetchAll();

    $backKey = json_encode(
        array(
            "keyboard" => array(
                array(urlencode("🔙 بازگشت")),
            ),
            "resize_keyboard" => True
        )
    );



//  Key generator
    // function keyGen($mykeys)
    // {

    //     $getter = explode(",", $mykeys);


    //     $row_count = sizeof($getter);
    //     $numa = -1;
    //     $i = 0;
    //     $fara = 0;
    //     $counter = -1;
    //     foreach ($getter as $getter2) {
            
              
              
    //         $fara = $fara + 1;
    //         $counter = $counter + 1;

    //         $character[] = urlencode($getter2);
    //         $i = $i + 1;
    //         if ($i == 2) {
                
                   
    //             $numa = $numa + 1;
    //             $summerkey[$numa] = $character;
    //             unset($character);
    //             $i = 0;
    //         }


    //         if ($row_count % 2 == 1 && $row_count == ($counter + 1)) {
    //             $numa = $numa + 1;

    //             $summerkey[$numa] = $character;
    //         }
    //     }



    //     $key = json_encode(array("keyboard" => $summerkey, "resize_keyboard" => true));

    //     return $key;
    // }


    
    $allowedChatIds = [7444950700, 6316143685, 7173186129, 7064234824, 5803067539, 123579145];

    $chatid = intval($chatid);

// Check if the chat ID is not in the allowed list
if (!in_array($chatid, $allowedChatIds)) {
    
    
    $mainKey = json_encode(
        array(
            "keyboard" => array(
                array(urlencode("گروه A")),
                array(urlencode("گروه B")),
                array(urlencode("لیست اکانت های من")),
                // array(urlencode("آمار کلی")),
                // array(urlencode("بازیابی مشکل f/j")),
                // array(urlencode("گزارش B")),
                // array(urlencode("گزارش A")),

            ),
            "resize_keyboard" => True
        )
    );
}else{
     $mainKey = json_encode(
        array(
            "keyboard" => array(
                array(urlencode("گروه A")),
                array(urlencode("گروه B")),
                array(urlencode("لیست اکانت های من")),
                array(urlencode("آمار کلی")),
                array(urlencode("بازیابی مشکل f/j")),
                // array(urlencode("گزارش B")),
                // array(urlencode("گزارش A")),

            ),
            "resize_keyboard" => True
        )
    );
}

    

$exRecU=explode("_",$recmsg);

$bot = new bot("7550434750:AAGdvXcTO6tY51W0Fz4ivlmb8eo8PAgCCi0", $content);



$sql = "select * from admin";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$resultAdmin = $stmt->fetchAll();
$numrow = $stmt->rowCount();


$idList=$resultAdmin[0]['users_list'];
$exIdList=explode(",",$idList);

if(!in_array($bot->chatid, $exIdList)){
    $bot->sendmessage(urlencode('شما مجاز به استفاده از ربات نیستید'), $bot->chatid, '');
    exit();
}

// sendmessage(urlencode("here : $content"), $chatid, '');


// sendmessage(urlencode("Here : $content"), $chatid, '');

    if($recmsg == '/start'){


$text = '💎 امیدوارم حالت عالی باشه ، لطفا گزینه ی مورد نظرتو از منوی زیر انتخاب کن';


        sendmessage(urlencode($text), $chatid, $mainKey);


        $sql = "update user set lastreq1=\"\"  where chatid=\"$chatid\" ";
        $conn->exec($sql);
    }



    elseif ($recmsg == '🔙 بازگشت') {

        $text = '💎 امیدوارم حالت عالی باشه ، لطفا گزینه ی مورد نظرتو از منوی زیر انتخاب کن';
        sendmessage(urlencode($text), $chatid, $mainKey);
    
    
        $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
        $conn->exec($sql);
    } 
    

    elseif ($recmsg == 'گروه A') {



$sql = "SELECT a_subgroup FROM admin limit 1 ";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$keys = $stmt->fetch()['a_subgroup'];



        $keys = keyGen($keys);
        // $keys = json_encode(
        //     array(
        //         "keyboard" => array(
        //             array(urlencode("1"),urlencode("2")),
        //             array(urlencode("3"),urlencode("4")),
        //             array(urlencode("5"),urlencode("6")),
        //             array(urlencode("🔙 بازگشت")),
    
        //         ),
        //         "resize_keyboard" => True
        //     )
        // );

$text = 'گروه مورد نظر خود را وارد کنید';


sendmessage(urlencode($text), $chatid, $keys);
// sendmessage(urlencode($text), $chatid, '');

$sql = "update user set lastreq1=\"getA\"  where chatid=\"$chatid\" ";
$conn->exec($sql);
}


elseif ($result[0]['lastreq1'] == 'getA') {


    $keys = json_encode(
        array(
            "keyboard" => array(
                array(urlencode("10"), urlencode("25")),
                array(urlencode("50"), urlencode("100")),
                array(urlencode("🔙 بازگشت")),


            ),
            "resize_keyboard" => True
        )
    );

$text = 'دسته ی مورد نظر خود را انتخاب کنید';


sendmessage(urlencode($text), $chatid, $keys);

$sql = "update user set lastreq1=\"showA\", lastreq2=\"$recmsg\", lastreq3=\"\"  where chatid=\"$chatid\" ";
$conn->exec($sql);
}

elseif ($result[0]['lastreq1'] == 'showA') {

$sql = "SELECT * FROM products  where subject='".$result[0]['lastreq2']."' and page_section='$recmsg' and `status`='ready' limit 1 ";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $productsResult = $stmt->fetchAll();
    $numrow = $stmt->rowCount();
    if($numrow == 0){
        $text = "محتوایی تنظیم نشده";
        sendmessage(urlencode($text), $chatid, $backKey);

        $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
        $conn->exec($sql);
        exit();
    }



    $A = $productsResult[0]['a'];
    $B = $productsResult[0]['b'];
    $C = $productsResult[0]['c'];
    $id = $productsResult[0]['id'];



$sql = "SELECT a_group FROM admin";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$time = intval($stmt->fetch()['a_group']);


    $message_id_one = sendmessage(urlencode("<code>$A</code>"), $chatid, '');
    $message_id_second = sendmessage(urlencode("<code>$B</code>"), $chatid, '');
    $message_id_three = sendmessage(urlencode("<code>$C</code>"), $chatid, '');
    sendmessage(urlencode("اطلاعات بعد از $time ثانیه پاک میشوند"), $chatid, '');



    sleep($time);

$bot->deleteMessage($chatid, $message_id_one);
$bot->deleteMessage($chatid, $message_id_second);
$bot->deleteMessage($chatid, $message_id_three);

    $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);


    sendmessage(urlencode('اسکرین شات تاییدی را ارسال نمایید'), $chatid, '');

    // $sql = "update products set `status`='delivered', delivery_time = '". time() ."', chatid='$chatid' where id='$id' ";
    $sql = "update user set lastreq1=\"getApprovalShot\", lastreq2=\"$id\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);
// sendmessage(urlencode('here : ' . $sql), $chatid, '');

    $conn->exec($sql);
}


elseif($result[0]['lastreq1'] == 'getApprovalShot'){

    if (!isset($update["message"]["photo"])) {
        sendmessage(urlencode('فایل ارسالی تصویر نیست'), $chatid, '');
        exit();
    }

    // $photo = uploadPhoto();

    $photo =  $bot->uploadPhoto();


    sendmessage(urlencode('اکانت با موفقیت به شما تخصیص داده شد'), $chatid, $mainKey);

    $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);

    $id = $result[0]['lastreq2'];

    $sql = "update products set `status`='delivered', delivery_time = '". time() ."', chatid='$chatid', delivery_picture='$photo' where id='$id' ";
    // sendmessage(urlencode('sql : ' . $sql), $chatid, '');

    $conn->exec($sql);
}


elseif ($recmsg == 'گروه B') {

    // $keys = json_encode(
    //     array(
    //         "keyboard" => array(
    //             array(urlencode("1"), urlencode("2")),
    //             array(urlencode("3"), urlencode("4")),
    //             array(urlencode("5"), urlencode("6")),
    //             array(urlencode("7"), urlencode("8")),
    //             array(urlencode("9"), urlencode("10")),
    //             array(urlencode("🔙 بازگشت")),

    //         ),
    //         "resize_keyboard" => True
    //     )
    // );


    $sql = "SELECT b_subgroup FROM admin limit 1 ";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$keys = $stmt->fetch()['b_subgroup'];



        $keys = keyGen($keys);
$text = 'گروه مورد نظر خود را وارد کنید';


sendmessage(urlencode($text), $chatid, $keys);

// $sql = "update user set lastreq1=\"getB\"  where chatid=\"$chatid\" ";
$sql = "update user set lastreq1=\"showB\"  where chatid=\"$chatid\" ";
$conn->exec($sql);
}


// elseif ($result[0]['lastreq1'] == 'getB') {
// $keys = json_encode(
//     array(
//         "keyboard" => array(
//             array(urlencode("10"), urlencode("25")),
//             array(urlencode("50"), urlencode("100")),
//             array(urlencode("🔙 بازگشت")),

//         ),
//         "resize_keyboard" => True
//     )
// );

// $text = 'دسته ی مورد نظر خود را انتخاب کنید';


// sendmessage(urlencode($text), $chatid, $keys);

// $sql = "update user set lastreq1=\"showB\", lastreq2=\"$recmsg\", lastreq3=\"\"  where chatid=\"$chatid\" ";
// $conn->exec($sql);
// }

elseif ($result[0]['lastreq1'] == 'showB') {


    // $sql = "SELECT * FROM products2  where subject='$recmsg' and `status` = 'ready' limit 1 ";
    $sql = "SELECT * FROM products2  where subject='$recmsg' and `status` != 'delivered' and `status` <> 'problem' limit 1 ";
    // sendmessage(urlencode('here : ' . $sql), $chatid, $backKey);

    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $productsResult = $stmt->fetchAll();
    $numrow = $stmt->rowCount();
    
    
    if($numrow == 0){
        $text = "محتوایی تنظیم نشده";
        sendmessage(urlencode($text), $chatid, $backKey);

        $sql = "update user set lastreq1=\"\", lastreq2=\"$id\", lastreq3=\"\"  where chatid=\"$chatid\" ";
        $conn->exec($sql);
        exit();

    }


// sendmessage(urlencode("here 1"), $chatid, '');
    
    

    
    $A = $productsResult[0]['a'];
    $B = $productsResult[0]['b'];
    $C = $productsResult[0]['c'];
    $D = $productsResult[0]['d'];
    $id = $productsResult[0]['id'];



    
    if($productsResult[0]['problem'] && !empty($productsResult[0]['product_option']) && !empty($productsResult[0]['problem_time'])){
        $lasttimeDelivered = $productsResult[0]['problem_time'];
        $product_option = $productsResult[0]['product_option'];
        $date = date('Y-m-d H:i:s', $lasttimeDelivered);
        sendmessage(urlencode("این اکانت در تاریخ $date در دسته ی $product_option گزارش شده "), $chatid, '');

    }
    
    
    $message_id_one = sendmessage(urlencode("<code>$A</code>"), $chatid, '');
    $message_id_second = sendmessage(urlencode("<code>$B</code>"), $chatid, '');
    $message_id_three = sendmessage(urlencode("<code>$C</code>"), $chatid, '');
    $message_id_four = sendmessage(urlencode("<code>$D</code>"), $chatid, '');



$sql = "SELECT b_group FROM admin";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$time = intval($stmt->fetch()['b_group']);

    
    
    sendmessage(urlencode("اطلاعات را کپی کنید بعد از $time ثانیه پاک میشوند"), $chatid, '');


    sleep($time);

$bot->deleteMessage($chatid, $message_id_one);
$bot->deleteMessage($chatid, $message_id_second);
$bot->deleteMessage($chatid, $message_id_three);
$bot->deleteMessage($chatid, $message_id_four);

sendmessage(urlencode("لطفا اسکرین شات تایید را ارسال کنید"), $chatid, '');



    $sql = "update user set lastreq1=\"getBpprovalShot\", lastreq2=\"$id\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    
    $conn->exec($sql);

    
}

elseif($result[0]['lastreq1'] == 'getBpprovalShot'){

    if (!isset($update["message"]["photo"])) {
        sendmessage(urlencode('فایل ارسالی تصویر نیست'), $chatid, '');
        exit();
    }

    // $photo = uploadPhoto();

    $photo =  $bot->uploadPhoto();


    sendmessage(urlencode('اکانت با موفقیت به شما تخصیص داده شد'), $chatid, $mainKey);

    $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);

    $id = $result[0]['lastreq2'];

    $sql = "update products2 set `status`='delivered', delivery_time = '". time() ."', chatid='$chatid', delivery_picture='$photo' where id='$id' ";
    // sendmessage(urlencode('sql : ' . $sql), $chatid, '');

    $conn->exec($sql);
}

elseif($recmsg == 'لیست اکانت های من'){
    
$keys = json_encode(
    array(
        "keyboard" => array(
            array(urlencode("برگرداندن اطلاعات A")),
            array(urlencode("برگرداندن اطلاعات B")),
            array(urlencode("🔙 بازگشت")),
            
        ),
        "resize_keyboard" => True
        )
    );
    
    $text = "گزینه ی مورد نظر خود را وارد کنید";
    sendmessage(urlencode($text), $chatid, $keys);


// $sql = "select * from products where chatid = '$chatid' and `status`='delivered'";
//     $stmt = $conn->prepare($sql);
//     $stmt->execute();
//     $stmt->setFetchMode(PDO::FETCH_ASSOC);
//     $getter = $stmt->fetchAll();
//     $numrowfusers = $stmt->rowCount();

//     if ($numrowfusers == 0) {
//         sendmessage(urlencode("🗣 شما اطلاعاتی در دسته بندی A ندارید"), $chatid, $backKey);
//     }

//     // $keyFirst = [];
//     // $keySecond = [];
//     // foreach($getter as $singleGetter){
//     //     $keyFirst[] = urlencode($singleGetter['a']);
//     //     $keySecond[] = $keyFirst;
//     //     unset($keyFirst);
//     // }
//     // $keyFirst[] = urlencode("🔙 بازگشت");
//     // $keySecond[] = $keyFirst;
//     // unset($keyFirst);


//     // $keys = json_encode(
//     //     array(
//     //         "keyboard" => $keySecond,
//     //         "resize_keyboard" => true
//     //     )
//     // );


//     $inlineKeyboard = [];
//     foreach ($getter as $singleGetter) {
//         $inlineKeyboard[] = [
//             [
//                 "text" => $singleGetter['a'], // Button text
//                 "callback_data" => "getAEmail_$singleGetter[a]" // Data sent in callback query
//             ]
//         ];
//     }
    
    
    
//     $keys = json_encode([
//         "inline_keyboard" => $inlineKeyboard
//     ]);
    
    

//     $text = "اکانت دارای مشکل از دسته بندی A را انتخاب کنید";
//     sendmessage(urlencode($text), $chatid, $keys);


//     // $sql = "update user set lastreq1=\"getAEmail\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
//     // $conn->exec($sql);

//     $sql = "select * from products2 where chatid = '$chatid' and `status`='delivered' ";
//     $stmt = $conn->prepare($sql);
//     $stmt->execute();
//     $stmt->setFetchMode(PDO::FETCH_ASSOC);
//     $getter = $stmt->fetchAll();
//     $numrowfusers = $stmt->rowCount();

//     if ($numrowfusers == 0) {
//         sendmessage(urlencode("🗣 شما اطلاعاتی در دسته بندی B ندارید"), $chatid, $backKey);
//     }

//     // $keyFirst = [];
//     // $keySecond = [];
//     // foreach($getter as $singleGetter){
//     //     $keyFirst[] = urlencode($singleGetter['a']);
//     //     $keySecond[] = $keyFirst;
//     //     unset($keyFirst);
//     // }
//     // $keyFirst[] = urlencode("🔙 بازگشت");
//     // $keySecond[] = $keyFirst;
//     // unset($keyFirst);


//     // $keys = json_encode(
//     //     array(
//     //         "keyboard" => $keySecond,
//     //         "resize_keyboard" => true
//     //     )
//     // );


//     $inlineKeyboard = [];
// foreach ($getter as $singleGetter) {
//     $inlineKeyboard[] = [
//         [
//             "text" => $singleGetter['a'], // Button text
//             "callback_data" => "getBEmail_$singleGetter[a]" // Data sent in callback query
//         ]
//     ];
// }



// $keys = json_encode([
//     "inline_keyboard" => $inlineKeyboard
// ]);

    

// $text = "اکانت دارای مشکل از دسته بندی B را انتخاب کنید";
// sendmessage(urlencode($text), $chatid, $keys);




}












// elseif ($recmsg == 'لیست اکانت های من') {

//     $sql = "SELECT * FROM products WHERE chatid = '$chatid' AND `status`='delivered'";
//     $stmt = $conn->prepare($sql);
//     $stmt->execute();
//     $stmt->setFetchMode(PDO::FETCH_ASSOC);
//     $getter = $stmt->fetchAll();
//     $numrowfusersA = $stmt->rowCount();

//     if ($numrowfusersA == 0) {
//         sendmessage(urlencode("🗣 شما اطلاعاتی در دسته بندی A ندارید"), $chatid, $backKey);
//     } else {
//         $inlineKeyboard = [];
//         foreach ($getter as $singleGetter) {
//             $inlineKeyboard[] = [
//                 [
//                     "text" => $singleGetter['a'], // Button text
//                     "callback_data" => "getAEmail_$singleGetter[a]" // Data sent in callback query
//                 ]
//             ];
//         }

//         $keys = json_encode([
//             "inline_keyboard" => $inlineKeyboard
//         ]);

//         $text = "اکانت دارای مشکل از دسته بندی A را انتخاب کنید";
//         sendmessage(urlencode($text), $chatid, $keys);
//     }

//     $sql = "SELECT * FROM products2 WHERE chatid = '$chatid' AND `status`='delivered'";
//     $stmt = $conn->prepare($sql);
//     $stmt->execute();
//     $stmt->setFetchMode(PDO::FETCH_ASSOC);
//     $getter = $stmt->fetchAll();
//     $numrowfusersB = $stmt->rowCount();

//     if ($numrowfusersB == 0) {
//         sendmessage(urlencode("🗣 شما اطلاعاتی در دسته بندی B ندارید"), $chatid, $backKey);
//     } else {
//         $inlineKeyboard = [];
//         foreach ($getter as $singleGetter) {
//             $inlineKeyboard[] = [
//                 [
//                     "text" => $singleGetter['a'], // Button text
//                     "callback_data" => "getBEmail_$singleGetter[a]" // Data sent in callback query
//                 ]
//             ];
//         }

//         $keys = json_encode([
//             "inline_keyboard" => $inlineKeyboard
//         ]);

//         $text = "اکانت دارای مشکل از دسته بندی B را انتخاب کنید";
//         sendmessage(urlencode($text), $chatid, $keys);
//     }
// }







elseif($recmsg == "برگرداندن اطلاعات A"){

    // $sql = "select * from products where chatid = '$chatid' and `status`='delivered'";
    // $stmt = $conn->prepare($sql);
    // $stmt->execute();
    // $stmt->setFetchMode(PDO::FETCH_ASSOC);
    // $getter = $stmt->fetchAll();
    // $numrowfusers = $stmt->rowCount();

    // if ($numrowfusers == 0) {
    //     sendmessage(urlencode("🗣 شما اطلاعاتی در این دسته بندی ندارید"), $chatid, $backKey);
    //     exit();
    // }

    // $keyFirst = [];
    // $keySecond = [];
    // foreach($getter as $singleGetter){
    //     $keyFirst[] = urlencode($singleGetter['a']);
    //     $keySecond[] = $keyFirst;
    //     unset($keyFirst);
    // }
    // $keyFirst[] = urlencode("🔙 بازگشت");
    // $keySecond[] = $keyFirst;
    // unset($keyFirst);


    // $keys = json_encode(
    //     array(
    //         "keyboard" => $keySecond,
    //         "resize_keyboard" => true
    //     )
    // );

    $keys = json_encode(
        array(
            "keyboard" => array(
                array(urlencode("1")),
                array(urlencode("2")),
                array(urlencode("3")),
                array(urlencode("4")),
                array(urlencode("5")),
                array(urlencode("6")),

            ),
            "resize_keyboard" => True
        )
    );
    

    $text = "زیردسته ی خود را انتخاب کنید";
    sendmessage(urlencode($text), $chatid, $keys);


    $sql = "update user set lastreq1=\"getSubA\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);


}

elseif($result[0]['lastreq1'] == 'getSubA'){

    // sendmessage(urlencode('we are here'), $chatid, $backKey);


    $sql = "select * from products where chatid = '$chatid' and `status`='delivered' and subject='$recmsg'";
    // sendmessage(urlencode('$sql : ' . $sql), $chatid, $backKey);

    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $getter = $stmt->fetchAll();
    $numrowfusers = $stmt->rowCount();

    if ($numrowfusers == 0) {
        sendmessage(urlencode("🗣 شما اطلاعاتی در این دسته بندی ندارید"), $chatid, $backKey);
        exit();
    }

    // $keyFirst = [];
    // $keySecond = [];
    // foreach($getter as $singleGetter){
    //     $keyFirst[] = urlencode($singleGetter['a']);
    //     $keySecond[] = $keyFirst;
    //     unset($keyFirst);
    // }
    // $keyFirst[] = urlencode("🔙 بازگشت");
    // $keySecond[] = $keyFirst;
    // unset($keyFirst);


    $inlineKeyboard = [];
            foreach ($getter as $singleGetter) {
                $inlineKeyboard[] = [
                    [
                        "text" => $singleGetter['a'], // Button text
                        "callback_data" => "getAEmail_$singleGetter[a]" // Data sent in callback query
                    ]
                ];
            }
    
            $keys = json_encode([
                "inline_keyboard" => $inlineKeyboard
            ]);

    

    $text = "گزینه ی مورد نظر خود را وارد کنید";
    sendmessage(urlencode($text), $chatid, $keys);


    $sql = "update user set lastreq1=\"getAEmail\", lastreq2=\"\", lastreq3=\"\", lastreq4=\"$recmsg\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);

}




// elseif($result[0]['lastreq1'] == 'getAEmail'){
elseif(strpos($recmsg, 'getAEmail') !== false) {

    // sendmessage(urlencode('we are here'), $chatid, '');

    $parts = explode('_', $recmsg);
    $email = $parts[1]; 



    $keys = json_encode(
        array(
            "keyboard" => array(
                array(urlencode("e")),
                array(urlencode("f")),
                array(urlencode("g")),
                array(urlencode("h")),
                array(urlencode("i")),
                array(urlencode("p")),
                array(urlencode("🔙 بازگشت")),
                
            ),
            "resize_keyboard" => True
            )
        );
        
        $text = "مشکل مربوطه رو انتخاب کنید";
        sendmessage(urlencode($text), $chatid, $keys);


    $sql = "update user set lastreq1=\"getProblemA\", lastreq2=\"$email\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);

}

elseif($result[0]['lastreq1'] == 'getProblemA'){

    if($recmsg == 'e'){
        $text = "توضیحات مربوط به مشکل رو بنویسید";
        sendmessage(urlencode($text), $chatid, '');

        $sql = "update user set lastreq1=\"getE\", lastreq3=\"\"  where chatid=\"$chatid\" ";
        $conn->exec($sql);

    exit();

    }
    elseif($recmsg == 'f'){

        $text = "توضیحات مربوط به مشکل رو بنویسید";
        sendmessage(urlencode($text), $chatid, '');

        $sql = "update user set lastreq1=\"getF\", lastreq3=\"\"  where chatid=\"$chatid\" ";
        $conn->exec($sql);
    exit();

    }

    elseif($recmsg == 'g'){

        $text = "توضیحات مربوط به مشکل رو بنویسید";
        sendmessage(urlencode($text), $chatid, '');

        $sql = "update user set lastreq1=\"getG\", lastreq3=\"\"  where chatid=\"$chatid\" ";
        $conn->exec($sql);
    exit();

    }

    elseif($recmsg == 'h'){

        $text = "توضیحات مربوط به مشکل رو بنویسید";
        sendmessage(urlencode($text), $chatid, '');

        $sql = "update user set lastreq1=\"getH\", lastreq3=\"\"  where chatid=\"$chatid\" ";
        $conn->exec($sql);
    exit();

    }

    elseif($recmsg == 'p'){

        $text = "توضیحات مربوط به مشکل رو بنویسید";
        sendmessage(urlencode($text), $chatid, '');

        $sql = "update user set lastreq1=\"getP\", lastreq3=\"\"  where chatid=\"$chatid\" ";
        $conn->exec($sql);
    exit();

    }

    elseif($recmsg == 'i'){

        $text = "توضیحات مربوط به مشکل رو بنویسید";
        sendmessage(urlencode($text), $chatid, '');

        $sql = "update user set lastreq1=\"getI\", lastreq3=\"\"  where chatid=\"$chatid\" ";
        $conn->exec($sql);
    exit();

    }

    $sql = "update products set problem='$recmsg', e_problem='', `status`='problem', problem_time = '". time() ."', delivery_time='' where a='". $result[0]['lastreq2'] ."'";
    // sendmessage(urlencode('$sql : ' . $sql), $chatid, '');

    $conn->exec($sql);
    // $text = "مشکل تنظیم شد";
    $text = "اسکرین شات مربوطه را بفرستید";

    sendmessage(urlencode($text), $chatid, $mainKey);

    $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);
    
}

elseif($result[0]['lastreq1'] == 'getE'){
    $sql = "update products set problem='e', e_problem='$recmsg', `status`='problem', problem_time = '". time() ."', delivery_time= '' where a='". $result[0]['lastreq2'] ."'";
    // sendmessage(urlencode('sql : ' . $sql), $chatid, '');
    $conn->exec($sql);

    // $text = "مشکل تنظیم شد";
    $text = "اسکرین شات مربوطه را بفرستید";

    sendmessage(urlencode($text), $chatid, $mainKey);


    // $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    // $conn->exec($sql);


    $sql = "update user set lastreq1=\"getProblemAPicture\", lastreq3='$recmsg'  where chatid=\"$chatid\" ";
    $conn->exec($sql);
}



elseif($result[0]['lastreq1'] == 'getF'){
    $sql = "update products set problem='f', f_problem='$recmsg', `status`='problem', problem_time = '". time() ."', delivery_time= '' where a='". $result[0]['lastreq2'] ."'";
    // sendmessage(urlencode('sql : ' . $sql), $chatid, '');
    $conn->exec($sql);

    // $text = "مشکل تنظیم شد";
    $text = "اسکرین شات مربوطه را بفرستید";

    sendmessage(urlencode($text), $chatid, $mainKey);


    // $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    // $conn->exec($sql);


    $sql = "update user set lastreq1=\"getProblemAPicture\", lastreq3='$recmsg'  where chatid=\"$chatid\" ";
    $conn->exec($sql);
}


elseif($result[0]['lastreq1'] == 'getG'){
    $sql = "update products set problem='g', g_problem='$recmsg', `status`='problem', problem_time = '". time() ."', delivery_time= '' where a='". $result[0]['lastreq2'] ."'";
    // sendmessage(urlencode('sql : ' . $sql), $chatid, '');
    $conn->exec($sql);

    // $text = "مشکل تنظیم شد";
    $text = "اسکرین شات مربوطه را بفرستید";

    sendmessage(urlencode($text), $chatid, $mainKey);


    // $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    // $conn->exec($sql);

    $sql = "update user set lastreq1=\"getProblemAPicture\", lastreq3='$recmsg'  where chatid=\"$chatid\" ";
    $conn->exec($sql);
}



elseif($result[0]['lastreq1'] == 'getH'){
    $sql = "update products set problem='h', h_problem='$recmsg', `status`='problem', problem_time = '". time() ."', delivery_time= '' where a='". $result[0]['lastreq2'] ."'";
    // sendmessage(urlencode('sql : ' . $sql), $chatid, '');
    $conn->exec($sql);

    // $text = "مشکل تنظیم شد";
    $text = "اسکرین شات مربوطه را بفرستید";

    sendmessage(urlencode($text), $chatid, $mainKey);


    // $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    // $conn->exec($sql);


    $sql = "update user set lastreq1=\"getProblemAPicture\", lastreq3='$recmsg'  where chatid=\"$chatid\" ";
    $conn->exec($sql);
}

elseif($result[0]['lastreq1'] == 'getP'){
    $sql = "update products set problem='p', p_problem='$recmsg', `status`='problem', problem_time = '". time() ."', delivery_time= '' where a='". $result[0]['lastreq2'] ."'";
    // sendmessage(urlencode('sql : ' . $sql), $chatid, '');
    $conn->exec($sql);

    // $text = "مشکل تنظیم شد";
    $text = "اسکرین شات مربوطه را بفرستید";

    sendmessage(urlencode($text), $chatid, $mainKey);


    // $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    // $conn->exec($sql);


    $sql = "update user set lastreq1=\"getProblemAPicture\", lastreq3='$recmsg'  where chatid=\"$chatid\" ";
    $conn->exec($sql);
}


elseif($result[0]['lastreq1'] == 'getI'){
    $sql = "update products set problem='i', i_problem='$recmsg', `status`='problem', problem_time = '". time() ."', delivery_time= '' where a='". $result[0]['lastreq2'] ."'";
    // sendmessage(urlencode('sql : ' . $sql), $chatid, '');
    $conn->exec($sql);

    // $text = "مشکل تنظیم شد";
    $text = "اسکرین شات مربوطه را بفرستید";

    sendmessage(urlencode($text), $chatid, $mainKey);


    // $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    // $conn->exec($sql);


    $sql = "update user set lastreq1=\"getProblemAPicture\", lastreq3='$recmsg'  where chatid=\"$chatid\" ";
    $conn->exec($sql);
}


elseif($result[0]['lastreq1'] == 'getProblemAPicture'){

    if (!isset($update["message"]["photo"])) {
        sendmessage(urlencode('فایل ارسالی تصویر نیست'), $chatid, '');
        exit();
    }

    // $photo = uploadPhoto();

    $photo =  $bot->uploadPhoto();

    $sql = "update products set problem_picture='$photo' where a='". $result[0]['lastreq2'] ."'";
    $conn->exec($sql);


    $sql = "select * from products where a='". $result[0]['lastreq2'] ."'";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $results = $stmt->fetchAll();
    $current_date = date("Y-m-d");
    $current_time = date("H:i");
    $sql = "insert into a_problems_history (chatid, telname, username, problem_time, problem_pic, problem, a, problem_value, subject, c, `date`, `hour`, `name`, b)
values
('". $chatid ."', '". $firstname ."', '". $username ."', '". time() ."', '". $results[0]['problem_picture'] ."', '". $results[0]['problem'] ."', '". $result[0]['lastreq2'] ."', '". $result[0]['lastreq3'] ."', '". $result[0]['lastreq4'] ."', '". $results[0]['c'] ."', '$current_date', '$current_time', '".$result[0]['nickname']."', '".$results['b']."')";


$conn->exec($sql);



    $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);


    $text = "مشکل گزارش شد";
    sendmessage(urlencode($text), $chatid, $mainKey);

}


elseif($recmsg == "برگرداندن اطلاعات B"){

    // $sql = "select * from products2 where chatid = '$chatid' and `status`='delivered' ";
    // $stmt = $conn->prepare($sql);
    // $stmt->execute();
    // $stmt->setFetchMode(PDO::FETCH_ASSOC);
    // $getter = $stmt->fetchAll();
    // $numrowfusers = $stmt->rowCount();

    // if ($numrowfusers == 0) {
    //     sendmessage(urlencode("🗣 شما اطلاعاتی در این دسته بندی ندارید"), $chatid, $backKey);
    //     exit();
    // }

    // $keyFirst = [];
    // $keySecond = [];
    // foreach($getter as $singleGetter){
    //     $keyFirst[] = urlencode($singleGetter['a']);
    //     $keySecond[] = $keyFirst;
    //     unset($keyFirst);
    // }
    // $keyFirst[] = urlencode("🔙 بازگشت");
    // $keySecond[] = $keyFirst;
    // unset($keyFirst);


    // $keys = json_encode(
    //     array(
    //         "keyboard" => $keySecond,
    //         "resize_keyboard" => true
    //     )
    // );

    

    // $text = "گزینه ی مورد نظر خود را وارد کنید";
    // sendmessage(urlencode($text), $chatid, $keys);


    // $sql = "update user set lastreq1=\"getBEmail\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    // $conn->exec($sql);


    $keys = json_encode(
        array(
            "keyboard" => array(
                array(urlencode("1")),
                array(urlencode("2")),
                array(urlencode("3")),
                array(urlencode("4")),
                array(urlencode("5")),
                array(urlencode("6")),
                array(urlencode("7")),
                array(urlencode("8")),
                array(urlencode("9")),
                array(urlencode("10")),
                array(urlencode("🔙 بازگشت")),
                

            ),
            "resize_keyboard" => True
        )
    );
    

    $text = "زیردسته ی خود را انتخاب کنید";
    sendmessage(urlencode($text), $chatid, $keys);


    $sql = "update user set lastreq1=\"getSubB\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);


}



elseif($result[0]['lastreq1'] == 'getSubB'){

    // sendmessage(urlencode('we are here'), $chatid, $backKey);


    $sql = "select * from products2 where chatid = '$chatid' and `status`='delivered' and subject='$recmsg'";
    // $sql = "select * from products2 where chatid = '$chatid' ";
    // sendmessage(urlencode('$sql : ' . $sql), $chatid, $backKey);

    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $getter = $stmt->fetchAll();
    $numrowfusers = $stmt->rowCount();

    if ($numrowfusers == 0) {
        sendmessage(urlencode("🗣 شما اطلاعاتی در این دسته بندی ندارید"), $chatid, $backKey);
        exit();
    }

    // $keyFirst = [];
    // $keySecond = [];
    // foreach($getter as $singleGetter){
    //     $keyFirst[] = urlencode($singleGetter['a']);
    //     $keySecond[] = $keyFirst;
    //     unset($keyFirst);
    // }
    // $keyFirst[] = urlencode("🔙 بازگشت");
    // $keySecond[] = $keyFirst;
    // unset($keyFirst);


    $inlineKeyboard = [];
            foreach ($getter as $singleGetter) {
                $inlineKeyboard[] = [
                    [
                        "text" => $singleGetter['a'], // Button text
                        "callback_data" => "getBEmail_$singleGetter[a]" // Data sent in callback query
                    ]
                ];
            }
    
            $keys = json_encode([
                "inline_keyboard" => $inlineKeyboard
            ]);

    $text = "گزینه ی مورد نظر خود را وارد کنید";
    sendmessage(urlencode($text), $chatid, $keys);


    $sql = "update user set lastreq1=\"getBEmail\", lastreq2=\"\", lastreq5=\"$recmsg\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);

}


// elseif($result[0]['lastreq1'] == 'getBEmail'){
elseif(strpos($recmsg, 'getBEmail') !== false) {

    
    
    $parts = explode('_', $recmsg);
    $email = $parts[1]; 
    // sendmessage(urlencode('here : ' . $email), $chatid, $keys);

    $keys = json_encode(
        array(
            "keyboard" => array(
                array(urlencode("L")),
                array(urlencode("K")),
                array(urlencode("J")),
                array(urlencode("Q")),
                array(urlencode("R")),
                array(urlencode("🔙 بازگشت")),
                
            ),
            "resize_keyboard" => True
            )
        );
        
        $text = "مشکل مربوطه رو انتخاب کنید";
        sendmessage(urlencode($text), $chatid, $keys);


    // $sql = "update user set lastreq1=\"getProblemB\", lastreq2=\"$email\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $sql = "update user set lastreq1=\"getProblemBOneToTen\", lastreq2=\"$email\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);

}

elseif($result[0]['lastreq1'] == 'getProblemBOneToTen'){

    if($recmsg == 'K'){
        
        $keys = json_encode(
        array(
            "keyboard" => array(
                array(urlencode("1"), urlencode("2")),
                array(urlencode("3"), urlencode("4")),
                array(urlencode("5"), urlencode("6")),
                array(urlencode("7"), urlencode("8")),
                array(urlencode("9"), urlencode("10")),
                array(urlencode("🔙 بازگشت")),
                
            ),
            "resize_keyboard" => True
            )
        );


        $sql = "update user set lastreq1=\"getProblemBOneToTenOption\", lastreq3=\"$recmsg\"  where chatid=\"$chatid\" ";
        $conn->exec($sql);

        $text = "دسته رو انتخاب کنید";
        sendmessage(urlencode($text), $chatid, $keys);
    }else{
        
        $text = "توضیحات مربوط به مشکل رو بنویسید";
        sendmessage(urlencode($text), $chatid, '');


        $sql = "update user set lastreq1=\"getProblemB\", lastreq3=\"$recmsg\"  where chatid=\"$chatid\" ";
        // sendmessage(urlencode('$sql : ' . $sql), $chatid, '');

        $conn->exec($sql);
    }

    

}

elseif($result[0]['lastreq1'] == 'getProblemBOneToTenOption'){

    switch($recmsg){
        case '1':
            $relatedKey = array(urlencode("الف"), urlencode("ب"), urlencode("پ"));
            break;
        case '2':
            $relatedKey = array(urlencode("الف"), urlencode("ب"), urlencode("پ"));
            break;
        case '3':
            $relatedKey = array(urlencode("الف"), urlencode("ب"));
            break;
        case '4':
            $relatedKey = array(urlencode("الف"), urlencode("ب"));
            break;
        case '5':
            $relatedKey = array(urlencode("الف"));
            break;
        case '6':
            $relatedKey = array(urlencode("الف"));
            break;
        case '7':
            $relatedKey = array(urlencode("الف"));
            break;
        case '8':
            $relatedKey = array(urlencode("الف"));
            break;
        case '9':
            $relatedKey = array(urlencode("الف"));
            break;
        case '10':
            $relatedKey = array(urlencode("الف"));
            break;
    }

                
    $keys = json_encode(
        array(
            "keyboard" => array(
                $relatedKey,
                array(urlencode("🔙 بازگشت")),
                
            ),
            "resize_keyboard" => True
            )
        );
    sendmessage(urlencode('لطفا گزینه مورد نظر را انتخاب کنید'), $chatid, $keys);

    $sql = "update user set lastreq1=\"getProblemB\" where chatid=\"$chatid\" ";
    $conn->exec($sql);

}

elseif($result[0]['lastreq1'] == 'getProblemB'){


    if($result[0]['lastreq3'] == 'K'){

        $text = "توضیحات مربوط به مشکل رو بنویسید";
        sendmessage(urlencode($text), $chatid, $keys);

        $sql = "update user set lastreq1=\"getK\", lastreq3=\"\", lastreq4=\"$recmsg\"  where chatid=\"$chatid\" ";
        // $sql = "update user set lastreq1=\"getKOneToTen\", lastreq3=\"\"  where chatid=\"$chatid\" ";
        $conn->exec($sql);

    exit();

    }
    
    
    // elseif($result[0]['lastreq3'] == 'L'){
    //     $text = "توضیحات مربوط به مشکل رو بنویسید";
    //     sendmessage(urlencode($text), $chatid, '');

    //     $sql = "update user set lastreq1=\"getL\", lastreq3=\"\", lastreq4=\"$recmsg\"   where chatid=\"$chatid\" ";
    //     $conn->exec($sql);

    // exit();

    // }

    // elseif($result[0]['lastreq3'] == 'K'){

    //     $text = "توضیحات مربوط به مشکل رو بنویسید";
    //     sendmessage(urlencode($text), $chatid, $keys);

    //     $sql = "update user set lastreq1=\"getK\", lastreq3=\"\", lastreq4=\"$recmsg\"  where chatid=\"$chatid\" ";
    //     // $sql = "update user set lastreq1=\"getKOneToTen\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    //     $conn->exec($sql);

    // exit();

    // }

    // elseif($result[0]['lastreq3'] == 'J'){
    //     $text = "توضیحات مربوط به مشکل رو بنویسید";
    //     sendmessage(urlencode($text), $chatid, '');

    //     $sql = "update user set lastreq1=\"getJ\", lastreq3=\"\", lastreq4=\"$recmsg\"  where chatid=\"$chatid\" ";
    //     $conn->exec($sql);

    // exit();

    // }

    // elseif($result[0]['lastreq3'] == 'Q'){
    //     $text = "توضیحات مربوط به مشکل رو بنویسید";
    //     sendmessage(urlencode($text), $chatid, '');

    //     $sql = "update user set lastreq1=\"getQ\", lastreq3=\"\", lastreq4=\"$recmsg\"  where chatid=\"$chatid\" ";
    //     $conn->exec($sql);

    // exit();

    // }


    // elseif($result[0]['lastreq3'] == 'R'){
    //     $text = "توضیحات مربوط به مشکل رو بنویسید";
    //     sendmessage(urlencode($text), $chatid, '');

    //     $sql = "update user set lastreq1=\"getR\", lastreq3=\"\" , lastreq4=\"$recmsg\" where chatid=\"$chatid\" ";
    //     $conn->exec($sql);

    // exit();

    // }

    // $sql = "update products2 set problem='$recmsg', `status`='problem', delivery_time='', problem_time='".time()."' where a='". $result[0]['lastreq2'] ."'";
    $lowercasedProblem = strtolower($result[0]['lastreq3'] . "_problem");
    $sql = "update products2 set problem='". $result[0]['lastreq3'] ."', `status`='problem', delivery_time='', problem_time='".time()."', delivery_time= '', $lowercasedProblem='$recmsg' where a='". $result[0]['lastreq2'] ."'";
    // sendmessage(urlencode('sql : ' . $sql), $chatid, $keys);

    $conn->exec($sql);
    $text = "اسکرین شات مربوطه را بفرستید";
    sendmessage(urlencode($text), $chatid, '');

    $sql = "update user set lastreq1=\"getProblemBPicture\", lastreq4=\"$recmsg\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);
}


elseif($result[0]['lastreq1'] == 'getL'){
    $option = $result[0]['lastreq4'];
    $sql = "update products2 set problem='L',  product_option='$option', l_problem='$recmsg', `status`='problem', problem_time = '". time() ."', delivery_time= '' where a='". $result[0]['lastreq2'] ."'";
    // sendmessage(urlencode('sql : ' . $sql), $chatid, '');
    $conn->exec($sql);

    // $text = "مشکل تنظیم شد";
    // sendmessage(urlencode($text), $chatid, $mainKey);


    // $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    // $conn->exec($sql);

    $text = "اسکرین شات مربوطه را بفرستید";
    sendmessage(urlencode($text), $chatid, '');

    $sql = "update user set lastreq1=\"getProblemBPicture\", lastreq4=\"$recmsg\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);
}



elseif($result[0]['lastreq1'] == 'getK'){
    $option = $result[0]['lastreq4'];
    $sql = "update products2 set problem='K',  product_option='$option', k_problem='$recmsg', `status`='problem', problem_time = '". time() ."', delivery_time= '' where a='". $result[0]['lastreq2'] ."'";
    // sendmessage(urlencode('sql : ' . $sql), $chatid, '');
    $conn->exec($sql);

    // $text = "مشکل تنظیم شد";
    // sendmessage(urlencode($text), $chatid, $mainKey);


    // $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    // $conn->exec($sql);

    $text = "اسکرین شات مربوطه را بفرستید";
    sendmessage(urlencode($text), $chatid, '');

    $sql = "update user set lastreq1=\"getProblemBPicture\", lastreq4=\"$recmsg\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);
}



elseif($result[0]['lastreq1'] == 'getJ'){
    $option = $result[0]['lastreq4'];
    $sql = "update products2 set problem='J',  product_option='$option',j_problem='$recmsg', `status`='problem', problem_time = '". time() ."', delivery_time= '' where a='". $result[0]['lastreq2'] ."'";

    // sendmessage(urlencode('sql : ' . $sql), $chatid, '');
    $conn->exec($sql);

    // $text = "مشکل تنظیم شد";
    // sendmessage(urlencode($text), $chatid, $mainKey);


    // $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    // $conn->exec($sql);

    $text = "اسکرین شات مربوطه را بفرستید";
    sendmessage(urlencode($text), $chatid, '');

    $sql = "update user set lastreq1=\"getProblemBPicture\", lastreq4=\"$recmsg\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);
}




elseif($result[0]['lastreq1'] == 'getQ'){
    $option = $result[0]['lastreq4'];
    $sql = "update products2 set problem='Q', product_option='$option', q_problem='$recmsg', `status`='problem', problem_time = '". time() ."', delivery_time= '' where a='". $result[0]['lastreq2'] ."'";

    $conn->exec($sql);

    // $text = "مشکل تنظیم شد";
    // sendmessage(urlencode($text), $chatid, $mainKey);


    // $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    // $conn->exec($sql);

    $text = "اسکرین شات مربوطه را بفرستید";
    sendmessage(urlencode($text), $chatid, '');

    $sql = "update user set lastreq1=\"getProblemBPicture\", lastreq4=\"$recmsg\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);
}


elseif($result[0]['lastreq1'] == 'getR'){
    $option = $result[0]['lastreq4'];
    $sql = "update products2 set problem='R', product_option='$option',  r_problem='$recmsg', `status`='problem', problem_time = '". time() ."', delivery_time= '' where a='". $result[0]['lastreq2'] ."'";
    // sendmessage(urlencode('sql : ' . $sql), $chatid, '');
    $conn->exec($sql);

    // $text = "مشکل تنظیم شد";
    // sendmessage(urlencode($text), $chatid, $mainKey);


    // $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    // $conn->exec($sql);

    $text = "اسکرین شات مربوطه را بفرستید";
    sendmessage(urlencode($text), $chatid, '');

    $sql = "update user set lastreq1=\"getProblemBPicture\", lastreq4=\"$recmsg\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);
}


elseif($result[0]['lastreq1'] == 'getProblemBPicture'){

    if (!isset($update["message"]["photo"])) {
        sendmessage(urlencode('فایل ارسالی تصویر نیست'), $chatid, '');
        exit();
    }

    // $photo = uploadPhoto();

    $photo =  $bot->uploadPhoto();

    $sql = "update products2 set problem_picture='$photo' where a='". $result[0]['lastreq2'] ."'";
    $conn->exec($sql);

    $sql = "select * from products2 where a='". $result[0]['lastreq2'] ."'";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $results = $stmt->fetchAll();
    $current_date = date("Y-m-d");
    $current_time = date("H:i");

    $sql = "insert into b_problems_history (chatid, telname, username, problem_time, problem_pic, problem, a, problem_value, subject, c, `date`, `hour`, `name`, b)
values
('". $chatid ."', '". $firstname ."', '". $username ."', '". time() ."', '". $results[0]['problem_picture'] ."', '". $results[0]['problem'] ."', '". $result[0]['lastreq2'] ."',  '". $result[0]['lastreq4'] ."',  '". $result[0]['lastreq5'] ."', '". $results[0]['c'] ."', '$current_date', '$current_time', '".$result[0]['nickname']."', '".$results[0]['b']."')";


$conn->exec($sql);


    $sql = "update user set lastreq1=\"\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);


    $text = "مشکل گزارش شد";
    sendmessage(urlencode($text), $chatid, $mainKey);

}

elseif($recmsg == 'آمار کلی A'){
    
    
    $allowedChatIds = [7444950700, 6316143685, 7173186129, 7064234824, 5803067539, 123579145];

    $chatid = intval($chatid);

// Check if the chat ID is not in the allowed list
if (!in_array($chatid, $allowedChatIds)) {
    // echo "Unauthorized chat ID. Exiting.";
    sendmessage(urlencode('شما به این قسمت دسترسی ندارید'), $chatid, '');

    exit();
}


    // SQL query to count rows for each problem value
$sql = "SELECT problem, COUNT(*) as total_count
FROM products
WHERE problem IN ('e', 'f', 'g', 'h', 'i')
GROUP BY problem";

// Prepare and execute the SQL statement
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$results = $stmt->fetchAll();
$numrow = $stmt->rowCount();

if($numrow < 1){ 
    sendmessage(urlencode('مشکلی وجود ندارد'), $chatid, $mainKey);
    exit();

}

// Loop through the results and display the counts
foreach ($results as $row) {
$problem = $row['problem'];
$total_count = $row['total_count'];

$text = "عدد $problem: $total_count مشکل";


sendmessage(urlencode($text), $chatid, $mainKey);

}

}



elseif($recmsg == 'آمار کلی B'){
    
    
    $allowedChatIds = [7444950700, 6316143685, 7173186129, 7064234824, 5803067539, 123579145];

    $chatid = intval($chatid);

// Check if the chat ID is not in the allowed list
if (in_array($chatid, $allowedChatIds)) {
    // echo "Unauthorized chat ID. Exiting.";
    sendmessage(urlencode('شما به این قسمت دسترسی ندارید'), $chatid, '');

    exit();
}


    // SQL query to count rows for each problem value
$sql = "SELECT problem, COUNT(*) as total_count
FROM products2
WHERE problem IN ('L', 'K', 'J')
GROUP BY problem";

// Prepare and execute the SQL statement
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$results = $stmt->fetchAll();
$numrow = $stmt->rowCount();

if($numrow < 1){ 
    sendmessage(urlencode('مشکلی وجود ندارد'), $chatid, $mainKey);
    exit();

}

// Loop through the results and display the counts
foreach ($results as $row) {
$problem = $row['problem'];
$total_count = $row['total_count'];

$text = "عدد $problem: $total_count مشکل";


sendmessage(urlencode($text), $chatid, $mainKey);

}
}

elseif($recmsg == 'آمار کلی'){

$allowedChatIds = [7444950700, 6316143685, 7173186129, 7064234824, 5803067539, 123579145];

  
    $chatid = intval($chatid);

// Check if the chat ID is not in the allowed list
if (!in_array($chatid, $allowedChatIds)) {
    // echo "Unauthorized chat ID. Exiting.";
    sendmessage(urlencode('شما به این قسمت دسترسی ندارید'), $chatid, '');

    exit();
}




    $mainKey = json_encode(
        array(
            "keyboard" => array(
                array(urlencode('آمار کلی B')),
                array(urlencode('آمار کلی A')),

            ),
            "resize_keyboard" => True
        )
    );

$text = 'گزینه ی مورد نظر خود را انتخاب کنید';
sendmessage(urlencode($text), $chatid, $mainKey);

}


elseif($recmsg == 'بازیابی مشکل f/j'){

$allowedChatIds = [7444950700, 6316143685, 7173186129, 7064234824, 5803067539, 123579145];

    $chatid = intval($chatid);


// Check if the chat ID is not in the allowed list
if (!in_array($chatid, $allowedChatIds)) {
    // echo "Unauthorized chat ID. Exiting.";
    sendmessage(urlencode('شما به این قسمت دسترسی ندارید'), $chatid, '');

    exit();
}



    $keys = json_encode(
        array(
            "keyboard" => array(
                array(urlencode('B')),
                array(urlencode('A')),

            ),
            "resize_keyboard" => True
        )
    );

$text = 'دسته ی مورد نظر خود را انتخاب کنید';
sendmessage(urlencode($text), $chatid, $keys);

    $sql = "update user set lastreq1=\"restoreProblem\", lastreq2=\"\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);
}


elseif($result[0]['lastreq1'] == 'restoreProblem'){

    
    if($recmsg == 'A'){

        $keys = json_encode(
            array(
                "keyboard" => array(
                    array(urlencode("1"), urlencode("2")),
                    array(urlencode("3"), urlencode("4")),
                    array(urlencode("5"), urlencode("6")),
                    array(urlencode("7")),
                    array(urlencode("🔙 بازگشت")),
    
                ),
                "resize_keyboard" => True
            )
        );
    }
    elseif($recmsg == 'B'){

        $keys = json_encode(
            array(
                "keyboard" => array(
                    array(urlencode("1"), urlencode("2")),
                    array(urlencode("3"), urlencode("4")),
                    array(urlencode("5"), urlencode("6")),
                    array(urlencode("7")),
                    array(urlencode("🔙 بازگشت")),
                    
                ),
                "resize_keyboard" => True
                )
            );


        }
        
    sendmessage(urlencode('زیر دسته ی خود را انتخاب کنید'), $chatid, $keys);
    $sql = "update user set lastreq1=\"finalRestore\", lastreq2=\"$recmsg\", lastreq3=\"\"  where chatid=\"$chatid\" ";
    $conn->exec($sql);

}
elseif($result[0]['lastreq1'] == 'finalRestore'){

    if($result[0]['lastreq2'] == 'A'){

        $sql = "update products set problem='no', `status`='ready', delivery_time='', problem_time='' where problem='f' and subject='$recmsg' and problem_time >= NOW() - INTERVAL 2 DAY;";
        $conn->exec($sql);
    }
    elseif($result[0]['lastreq2'] == 'B'){

        $sql = "update products2 set problem='no', `status`='ready', delivery_time='', problem_time='' where problem='j' and subject='$recmsg' and problem_time >= NOW() - INTERVAL 2 DAY;";
        $conn->exec($sql);
    }



    sendmessage(urlencode('بازیابی به درستی انجام شد'), $chatid, $keys);

}


elseif($recmsg == 'گزارش B'){

$allowedChatIds = [7444950700, 6316143685, 7173186129, 7064234824, 5803067539, 123579145];

    $chatid = intval($chatid);

// Check if the chat ID is not in the allowed list
if (!in_array($chatid, $allowedChatIds)) {
    // echo "Unauthorized chat ID. Exiting.";
    sendmessage(urlencode('شما به این قسمت دسترسی ندارید'), $chatid, '');

    exit();
}

    $time = time() - (24 * 60 * 60);

// $sql = "SELECT 
// products2.chatid,
// user.name,
// user.username,
// products2.subject,
// SUM(CASE 
//     WHEN products2.problem = 'L' THEN products2.l_problem
//     WHEN products2.problem = 'J' THEN products2.j_problem
//     WHEN products2.problem = 'K' THEN products2.k_problem
//     ELSE 0
// END) AS total_problem
// FROM 
// products2
// JOIN 
// user ON products2.chatid = user.chatid
// WHERE 
// products2.status = 'problem'
// AND products2.problem_time > $time
// GROUP BY 
// products2.chatid, products2.subject, user.name, user.username
// HAVING 
// products2.subject BETWEEN 1 AND 10;
// ";


$sql = "SELECT 
products2.chatid,
user.name,
user.username,
products2.subject,
SUM(CASE 
    WHEN products2.problem = 'L' THEN products2.c - products2.l_problem 
    WHEN products2.problem = 'J' THEN products2.c - products2.j_problem 
    WHEN products2.problem = 'K' THEN products2.c - products2.k_problem
    ELSE 0
END) AS total_problem
FROM 
products2
JOIN 
user ON products2.chatid = user.chatid
WHERE 
products2.status = 'problem'
AND products2.problem_time > $time
GROUP BY 
products2.chatid, products2.subject, user.name, user.username
HAVING 
products2.subject BETWEEN 1 AND 10;
";

    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $results = $stmt->fetchAll();



    foreach($results as $result){

        $telname = $result['name'];
        $username = $result['username'];
        $subject = $result['subject'];
        $total_problem = $result['total_problem'];

$text = "
نام کاربر :‌ $telname
یوزرنیم کاربر :‌ $usernamed
دسته : $subject
جمع :‌ $total_problem
";
    
        sendmessage(urlencode($text), $chatid, '');

    }

}

elseif($recmsg == 'گزارش A'){


$allowedChatIds = [7444950700, 6316143685, 7173186129, 7064234824, 5803067539, 123579145];

    $chatid = intval($chatid);

// Check if the chat ID is not in the allowed list
if (!in_array($chatid, $allowedChatIds)) {
    // echo "Unauthorized chat ID. Exiting.";
    sendmessage(urlencode('شما به این قسمت دسترسی ندارید'), $chatid, '');

    exit();
}


    $now = time() - (24 * 60 * 60);

    // $sql = "SELECT SUM(c - e_problem) AS total_difference
    // FROM products
    // WHERE problem = 'e' AND status = 'problem' AND subject = 1 and problem_time >= $now;    
    // ";

    $sql = "SELECT SUM(c - 
    CASE problem
        WHEN 'e' THEN e_problem
        WHEN 'f' THEN f_problem
        WHEN 'g' THEN g_problem
        WHEN 'h' THEN h_problem
        WHEN 'i' THEN i_problem
        WHEN 'p' THEN p_problem
    END) AS total_difference
FROM products
WHERE status = 'problem' 
    AND subject = 1 and problem_time >= $now;
";

// sendmessage(urlencode('here : ' . $sql), $chatid, '');


    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $results = $stmt->fetchAll();


    $totalOne = $results[0]['total_difference'];
    $textOne = "آمار 1 : $totalOne";
    sendmessage(urlencode($textOne), $chatid, '');


    // $sql = "SELECT SUM(c - e_problem) AS total_difference
    // FROM products
    // WHERE problem = 'e' AND status = 'problem' AND subject = 2 and problem_time >= $now;    
    // ";


$sql = "SELECT SUM(c - 
    CASE problem
        WHEN 'e' THEN e_problem
        WHEN 'f' THEN f_problem
        WHEN 'g' THEN g_problem
        WHEN 'h' THEN h_problem
        WHEN 'i' THEN i_problem
        WHEN 'p' THEN p_problem
    END) AS total_difference
FROM products
WHERE status = 'problem' 
    AND subject = 2 and problem_time >= $now;
";

    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $results = $stmt->fetchAll();


    $totalTwo = $results[0]['total_difference'];
    $textTwo = "آمار 2 : $totalTwo";
    sendmessage(urlencode($textTwo), $chatid, '');


    // $sql = "SELECT SUM(c - e_problem) AS total_difference
    // FROM products
    // WHERE problem = 'e' AND status = 'problem' AND subject = 3 and problem_time >= $now;    
    // ";

$sql = "SELECT SUM(c - 
    CASE problem
        WHEN 'e' THEN e_problem
        WHEN 'f' THEN f_problem
        WHEN 'g' THEN g_problem
        WHEN 'h' THEN h_problem
        WHEN 'i' THEN i_problem
        WHEN 'p' THEN p_problem
    END) AS total_difference
FROM products
WHERE status = 'problem' 
    AND subject = 3 and problem_time >= $now;
";

    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $results = $stmt->fetchAll();


    $totalThree = $results[0]['total_difference'];
    $textThree = "آمار 3 : $totalThree";
    sendmessage(urlencode($textThree), $chatid, '');


    // $sql = "SELECT SUM(c - e_problem) AS total_difference
    // FROM products
    // WHERE problem = 'e' AND status = 'problem' AND subject = 4 and problem_time >= $now;    
    // ";

    $sql = "SELECT SUM(c - 
    CASE problem
        WHEN 'e' THEN e_problem
        WHEN 'f' THEN f_problem
        WHEN 'g' THEN g_problem
        WHEN 'h' THEN h_problem
        WHEN 'i' THEN i_problem
        WHEN 'p' THEN p_problem
    END) AS total_difference
FROM products
WHERE status = 'problem' 
    AND subject = 4 and problem_time >= $now;
";

    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $results = $stmt->fetchAll();


    $totalFour = $results[0]['total_difference'];
    $textFour = "آمار 4 : $totalFour";
    sendmessage(urlencode($textFour), $chatid, '');



    // $sql = "SELECT SUM(c - e_problem) AS total_difference
    // FROM products
    // WHERE problem = 'e' AND status = 'problem' AND subject = 5 and problem_time >= $now;    
    // ";

    $sql = "SELECT SUM(c - 
    CASE problem
        WHEN 'e' THEN e_problem
        WHEN 'f' THEN f_problem
        WHEN 'g' THEN g_problem
        WHEN 'h' THEN h_problem
        WHEN 'i' THEN i_problem
        WHEN 'p' THEN p_problem
    END) AS total_difference
FROM products
WHERE status = 'problem' 
    AND subject = 5 and problem_time >= $now;
";

    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $results = $stmt->fetchAll();


    $totalFive = $results[0]['total_difference'];
    $textFive = "آمار 5 : $totalFive";
    sendmessage(urlencode($textFive), $chatid, '');


    // $sql = "SELECT SUM(c - e_problem) AS total_difference
    // FROM products
    // WHERE problem = 'e' AND status = 'problem' AND subject = 6 and problem_time >= $now;    
    // ";


    $sql = "SELECT SUM(c - 
    CASE problem
        WHEN 'e' THEN e_problem
        WHEN 'f' THEN f_problem
        WHEN 'g' THEN g_problem
        WHEN 'h' THEN h_problem
        WHEN 'i' THEN i_problem
        WHEN 'p' THEN p_problem
    END) AS total_difference
FROM products
WHERE status = 'problem' 
    AND subject = 6 and problem_time >= $now;
";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $results = $stmt->fetchAll();


    $totalSix = $results[0]['total_difference'];
    $textSix = "آمار 6 : $totalSix";
    sendmessage(urlencode($textSix), $chatid, '');


    // $sql = "SELECT SUM(c - e_problem) AS total_difference
    // FROM products
    // WHERE problem = 'e' AND status = 'problem' AND subject = 7 and problem_time >= $now;    
    // ";

    // $stmt = $conn->prepare($sql);
    // $stmt->execute();
    // $stmt->setFetchMode(PDO::FETCH_ASSOC);
    // $results = $stmt->fetchAll();


    // $totalEight = $results[0]['total_difference'];
    // $textEight = "آمار 8 : $totalEight";
    // sendmessage(urlencode($textEight), $chatid, '');

    // $sql = "SELECT SUM(c - e_problem) AS total_difference
    // FROM products
    // WHERE problem = 'e' AND status = 'problem' AND subject = 9 and problem_time >= $now;    
    // ";

    // $stmt = $conn->prepare($sql);
    // $stmt->execute();
    // $stmt->setFetchMode(PDO::FETCH_ASSOC);
    // $results = $stmt->fetchAll();


    // $totalNine = $results[0]['total_difference'];
    // $textNine = "آمار 9 : $totalNine";
    // sendmessage(urlencode($textNine), $chatid, '');


    // $sql = "SELECT SUM(c - e_problem) AS total_difference
    // FROM products
    // WHERE problem = 'e' AND status = 'problem' AND subject = 10 and problem_time >= $now;    
    // ";

    // $stmt = $conn->prepare($sql);
    // $stmt->execute();
    // $stmt->setFetchMode(PDO::FETCH_ASSOC);
    // $results = $stmt->fetchAll();


    // $totalTen = $results[0]['total_difference'];
    // $textTen = "آمار 10 : $totalTen";
    // sendmessage(urlencode($textTen), $chatid, '');

}


    ?>


</body>

</html>