<?php
define('BOT_TOKEN', '8113417981:AAGNPqbuDLScL9fSeNxuW63NS2xDNrtlXOE'); // Replace with your actual bot token
// $bot_token = '8291470736:AAHMwfbO6ABPoe3OtzRujXmaLzXJaMPphIQ';

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");


include_once 'functions/function_cud_file_json.php';
include_once 'functions/function_mgdb.php';
include_once 'functions/function_telagram_bot.php';
//include_once 'functions/function_time_json.php';
include_once 'functions/function_Webhook.php';



$update = json_decode(file_get_contents('php://input'), true);

// define('chat_id', $update['message']['chat']['id']); // Replace with your HTTPS URL
// define('text', $update['message']['text']); // Replace with your HTTPS URL

 $chat_id = isset($update['message']['chat']['id'])?$update['message']['chat']['id']:"";
$chatq_id = isset($update['callback_query']['message']['chat']['id'])?$update['callback_query']['message']['chat']['id']:"304835260";
$text = isset($update['message']['text'])?$update['message']['text']:"";
$callback_querys = isset($update['callback_query'])?$update['callback_query']:"";
$callback_data = isset($update['callback_query']['data'])?$update['callback_query']['data']:"";

sendMessage_tbot($chat_id, $update['message']['text']);

// $chat_id = $update['message']['chat']['id'];
// $chatcq_id = $update['callback_query']['message']['chat']['id'];
// $username = $update['message']['chat']['username'];

//$urlsoal = "https://isekolah.my.id/myWebhook/soal/";
$urlreg = "https://isekolah.my.id/myWebhook/img_reg/";
$urlpoin= 'https://isekolah.my.id/myWebhook';


//////////////////////////////////////////
// include_once 'mongodb_config.php';
$db = new DbManager();
$conn = $db->getConnection();
$dbname="myWebhook";
$collection_user="user";
$collection_soal="soal3";
$collection_kunci="kunci";
$chat_id_admin="304835260";
$collection_setting ='dataAdmin';

    
    
   $filter1 = ['id' => (string)$chat_id_admin,];
   $result1 = read_mgdb($dbname,$collection_user,$filter1,[])["result"];

    echo "1)";
 	echo $jsonString1 = json_encode($result1[0]);  echo "\n";echo "\n";//1){"_id":{"$oid":"69532ce57b3df17e1e0c73d2"},"id":"304835260","nama":"nzmz","kelas":"","role":"siswa","edit":0,"delete":0,"select":0}
	echo "2)";
    echo $str1 = base64_encode($jsonString1); echo "\n";echo "\n";    // 2)eyJfaWQiOnsiJG9pZCI6IjY5NTMyY2U1N2IzZGYxN2UxZTBjNzNkMiJ9LCJpZCI6IjMwNDgzNTI2MCIsIm5hbWEiOiJuem16Iiwia2VsYXMiOiIiLCJyb2xlIjoic2lzd2EiLCJlZGl0IjowLCJkZWxldGUiOjAsInNlbGVjdCI6MH0=
    echo "3)";
    echo $count1= json_encode(count($result1));  echo "\n";echo "\n";//3)6
    echo "4)";
    echo $oidValue1 = $result1[0]['_id']['$oid']; echo "\n";echo "\n"; //4)69532ce57b3df17e1e0c73d2
    echo "5)";
    echo $nm1 = $result1[0]['nama']; // 5)nzmz
    //    var_dump($result1[0]['nama']) ;

    echo "\n";echo "\n";echo "6)";

 














$filter_adm = [];
    $options = [
    'projection' => [
        '_id' => 0.0,
        'idData' => 1.0,
        'input' => 1.0,
        'ket' => 1.0
    ],
    'sort' => [
        'idData' => 1.0
    ]
];
 	//$options = ['projection' => ['_id' => 0.0]];
    //  $options_adm = ['projection' => ['_id' => 0.0],'sort' => [
    //     'idData' => 1.0]];
	// $read_adm = new MongoDB\Driver\Query($filter_adm, $options);
	// $records_adm = $conn->executeQuery("$dbname.$collection_setting", $read_adm);
 	// $res_adm= json_encode(iterator_to_array($records_adm)); //echo  
    // $result_adm= json_decode($res_adm, true); 
    // $jsonString_adm = json_encode($result_adm);
    // $ket_adm =$result_adm['inputKet'];
    // $adm_daftar= $result_adm['daftarUser'];
    // $adm_soal=$result_adm;
// $Gsoal=$result_adm['Gsoal'];
// $ket11 = getChatIdFromUsername('arsyplp');
// sendMessage_tbot($chat_id, $jsonString_adm[0]['soal']);
// echo var_dump($result_adm );

   $result_adm = read_mgdb($dbname,$collection_setting,[],$options)["result"];



foreach ($result_adm as $document) {
    if( $document['ket'] == 'mulai_soal')
  $adm_mulai_soal = $document['input'];

    if( $document['ket'] == 'soal_grup')
  $adm_Grup_soal = $document['input'];

if( $document['ket'] == 'newUser')
  $adm_new_user = $document['input']; 

if( $document['ket'] == 'updateUser')
  $adm_update_user = $document['input'];  

if( $document['ket'] == 'cap_propil')
  $adm_photo_propil = $document['input'];  

if( $document['ket'] == 'cap_simpan')
  $adm_photo_simpan = $document['input'];  

if( $document['ket'] == 'cap_kirm-tugas')
  $adm_photo_tugas = $document['input'];  

if( $document['ket'] == 'send_admin')
  $adm_send_admin = $document['input'];  

if( $document['ket'] == 'user_ket')
  $adm_input_ket = $document['input'];  

if( $document['ket'] == 'info_user')
  $adm_info_user = $document['input'];  

if( $document['ket'] == 'cetak')
  $adm_cetak_user = $document['input'];  

if( $document['ket'] == 'paket_arr')
   $adm_paket_arr = $document['input']; 

if( $document['ket'] == 'paket_1')
  $adm_paket1 = $document['input']; 


}


$buah = array("01", "02", "03", "04","05","06","07","08","09","10");
shuffle($buah); // Mengacak array $buah
// print_r($buah);


//array
$input = ($adm_paket_arr);
$rand_paket = array_rand($input);
$paket_arr = $input[$rand_paket];

// 1 saja
echo $paket_1 = $adm_paket1;

echo "\n";echo "\n";
echo  $urlsoal = "https://isekolah.my.id/myWebhook/soal/".$paket_1."/";
 echo "\n";echo "\n";
echo  $filePath = 'soal/'.$paket_1.'.json';
echo "\n";echo "\n";
//$filePath = 'soal/jawaban.json';

if (!file_exists($filePath)) {
    echo "Error: JSON file not found at $filePath";
}

$jsonString = file_get_contents($filePath);

if ($jsonString === false) {
     echo "Error reading the JSON file.";
}

$jsonData = json_decode($jsonString, true);

if (json_last_error() !== JSON_ERROR_NONE) {
     echo "Error decoding JSON data: " . json_last_error_msg();
}


  $json_soal_pel = isset($jsonData['soal']['pelajaran'])?$jsonData['soal']['pelajaran']:"";
  $jsonData_soal = $jsonData['soal'];
  $jsonData_ket = $jsonData['ket'];
  $jsonData_img = $jsonData['img'];
  $jsonData_jwb = $jsonData['jawab'];
  $jsonData_soal_acak = $jsonData['soal']['acak'];
  $jsonData_soal_paket = $jsonData['soal']['nama_paket'];
  ///////////array to sting////////////////
  shuffle($jsonData_soal_acak);
 $string_json = implode(", ", $jsonData_soal_acak); ////string
 $acak_array = explode(",", $string_json);  // array

echo  var_dump($jsonData_img );
echo "\n";
// echo decode$acak_array;



// $pecahi = (explode('@',$text));
//      $_txt_img= $pecahi['0'];
//      $_txt1_img= $pecahi['1'];
//      $txt2_img= $pecahi['2'];
//     //  sendMessage_tbot($chat_id, $_txt_img);
//     //  sendMessage_tbot($chat_id, $_txt1_img);
// ///////////////////////////
// if( $_txt_img == "img"){
// ///////////////////////////
// sendMessage_tbot($chat_id, $jsonData_soal_paket);
// $pth = "https://isekolah.my.id/myWebhook/soal/".$paket_1 ."/".$jsonData['img'][$_txt1_img];
// // sendMessage_tbot($chat_id, $pth);
 
//     //  sendMessage_tbot($chat_id, $pth);
// photo_tbot($chat_id,$pth,$jsonData['img'][$_txt1_img]);

// }






// $img ='./soal/paket_b/02b.JPG';

// $inlineKeyboard = [
//          [
//             ['text' => 'A BENAR', 'callback_data' => "s"],
//             ['text' => 'D BENAR', 'callback_data' => "ghg"]         
//         ],
//         [
//             ['text' => 'B BENAR', 'callback_data' => "hjjhj"],
//             ['text' => 'E BENAR', 'callback_data' => "hjhjhj"]
//         ],
//         [
//             ['text' => 'C BENAR', 'callback_data' => "hjhjh"],
//             ['text' => 'Semua Salah', 'callback_data' => "jkjk"]
//         ] 
// ];


// $url = "https://api.telegram.org/bot".BOT_TOKEN."/sendPhoto";
// $replyMarkupInline = json_encode([
//     'inline_keyboard' => $inlineKeyboard
// ]);

// $curl = curl_init();
//    curl_setopt_array($curl, array(
//   CURLOPT_URL => $url,
//   CURLOPT_RETURNTRANSFER => true,
//   CURLOPT_ENCODING => '',
//   CURLOPT_MAXREDIRS => 10,
//   CURLOPT_TIMEOUT => 0,
//   CURLOPT_FOLLOWLOCATION => true,
//   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//   CURLOPT_CUSTOMREQUEST => 'POST',
//   CURLOPT_POSTFIELDS => array('chat_id' => $chat_id,'photo'=> './soal/paket_b/02b.JPG','caption' => "fdfd",'reply_markup' =>$replyMarkupInline ),
//    ));

//    $response = curl_exec($curl);

//    curl_close($curl);




// $inlineKeyboard = [
//          [
//             ['text' => 'A BENAR', 'callback_data' => '01a'],
//             ['text' => 'D BENAR', 'callback_data' => '01d']         
//         ],
//         [
//             ['text' => 'B BENAR', 'callback_data' => '01b'],
//             ['text' => 'E BENAR', 'callback_data' => '01e']
//         ],
//         [
//             ['text' => 'C BENAR', 'callback_data' => '01c'],
//             ['text' => 'Semua Salah', 'callback_data' => '01s']
//         ] 
// ];

// $local_img ='./soal/paket_b/02b.JPG';

// $chat_id = '304835260';

// sendpoto1($chat_id,$local_img,$inlineKeyboard,$caption1);


// function sendpoto1($chat_id,$local_img,$inlineKeyboard,$caption1) {
// $replyMarkupInline = json_encode([
//     'inline_keyboard' => $inlineKeyboard
// ]);


// $url = "https://api.telegram.org/bot".BOT_TOKEN."/sendPhoto";

// $curl = curl_init();

// curl_setopt_array($curl, array(
//   CURLOPT_URL => $url,
//   CURLOPT_RETURNTRANSFER => true,
//   CURLOPT_ENCODING => '',
//   CURLOPT_MAXREDIRS => 10,
//   CURLOPT_TIMEOUT => 0,
//   CURLOPT_FOLLOWLOCATION => true,
//   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//   CURLOPT_CUSTOMREQUEST => 'POST',
//   CURLOPT_POSTFIELDS => array('chat_id' => $chat_id ,'photo'=> new CURLFILE($local_img),'reply_markup' =>$replyMarkupInline,'caption' => $caption1),
// ));

// // CURLOPT_POSTFIELDS => array('chat_id' => $chat_id,'photo' => $url_img,'caption' => $caption1,'reply_markup' =>$replyMarkupInline ),
// //    ));

// $response = curl_exec($curl);

// curl_close($curl);
// echo $response;


// }


$result2w = read_mgdb($dbname,$collection_setting,[],[])["result"];
foreach ($result2w as $document) {
    if( $document['idData'] == '3')
  $adm_grup = $document['input']; 
}
$filter2w = ['Gsoal'=>$adm_grup];

     
      $options2 = [
         'projection' => [
        '01' => 0.0,
        '02' => 0.0,
        '03' => 0.0,
        '04' => 0.0,
        '05' => 0.0,
        '06' => 0.0,
        '07' => 0.0,
        '08' => 0.0,
        '09' => 0.0,
        '10' => 0.0,
        'end_at' => 0.0,
        '_id' => 0.0,
        'id' => 0.0,
        'nama' => 0.0,
        'pel' => 0.0,
        'nilai' => 0.0,
        'skor' => 0.0,
        'user' => 0.0,
       // 'sesi' => 0.0,
        'kelas' => 0.0,
        'created_at' => 0.0
    ],
    'sort' => [
        'y' => -1.0
    ]
];
     
	// $read2 = new MongoDB\Driver\Query($filter2, $options2);
	// $records2 = $conn->executeQuery("$dbname.$collection_soal", $read2);
 	// $res2= json_encode(iterator_to_array($records2)); //echo  
    // $result2= json_decode($res2, true); 
$result2w = read_mgdb($dbname,$collection_soal,$filter2,$options2)["result"];



//  echo var_dump($result2) ;
 
 
 
 
 function getKeyBasedOnName($arr,$name)
{
    foreach($arr as $key=>$o) {
        if($o->sesi==$name) return $key;
    }
    return false;
}
 $arr=json_decode($res2);
 echo var_dump(getKeyBasedOnName($arr,'5')); //Return 0  



// $chat_ida="304835260";


// $filter2 = ['id' => (string)$chat_ida,'sesi' => '6'];
//      $options2 = ['projection' => []];
// 	$read2 = new MongoDB\Driver\Query($filter2, $options2);
// 	$records2 = $conn->executeQuery("$dbname.$collection_soal", $read2);
//  	$res2= json_encode(iterator_to_array($records2)); //echo  
//     $result2= json_decode($res2, true); 

//   echo $res2 ; 








// $filter_user = [];
// 	//$options = ['projection' => ['_id' => 0.0]];
//      $options_user = ['projection' => []];
// 	$read_user = new MongoDB\Driver\Query($filter_user, $options_user);
// 	$records_user = $conn->executeQuery("$dbname.$collection_user", $read_user);
//  	$res_user= json_encode(iterator_to_array($records_user)); //echo  
//     $result_user= json_decode($res_user, true); 
    

    
//  	 $jsonString_user = json_encode($result_user[0]);  //1){"_id":{"$oid":"6953_userce57b3df17e1e0c73d_user"},"id":"304835_user60","nama":"nzmz","kelas":"","role":"siswa","edit":0,"delete":0,"select":0}
	
//     $str_user = base64_encode($jsonString_user);    // _user)eyJfaWQiOnsiJG9pZCI6IjY5NTMyY_userU1N_userIzZGYxN_userUxZTBjNzNkMiJ9LCJpZCI6IjMwNDgzNTI_userMCIsIm5hbWEiOiJuem16Iiwia_userVsYXMiOiIiLCJyb_userxlIjoic_userlzd_userEiLCJlZGl0IjowLCJkZWxldGUiOjAsInNlbGVjdCI6MH0=
  
//     $count_user= json_encode(count($result_user));  //3)6
  
//     $oidValue_user= $result_user[0]['_id']['$oid'];  //4)69532ce57b3df17e1e0c73d2



if($chat_id){


    $filter2 = ['id' => (string)$chat_id,];
	//$options = ['projection' => ['_id' => 0.0]];
     $options2 = ['projection' => []];
	$read2 = new MongoDB\Driver\Query($filter2, $options2);
	$records2 = $conn->executeQuery("$dbname.$collection_user", $read2);
 	$res2= json_encode(iterator_to_array($records2)); //echo  
    $result2= json_decode($res2, true); 
    

    
 	 $jsonString2 = json_encode($result2[0]);  //1){"_id":{"$oid":"69532ce57b3df17e1e0c73d2"},"id":"304835260","nama":"nzmz","kelas":"","role":"siswa","edit":0,"delete":0,"select":0}
	
    $str2 = base64_encode($jsonString2);    // 2)eyJfaWQiOnsiJG9pZCI6IjY5NTMyY2U1N2IzZGYxN2UxZTBjNzNkMiJ9LCJpZCI6IjMwNDgzNTI2MCIsIm5hbWEiOiJuem16Iiwia2VsYXMiOiIiLCJyb2xlIjoic2lzd2EiLCJlZGl0IjowLCJkZWxldGUiOjAsInNlbGVjdCI6MH0=
  
    $count2= json_encode(count($result2));  //3)6
  
    $oidValue2= $result2[0]['_id']['$oid'];  //4)69532ce57b3df17e1e0c73d2
 
    $nm2 = $result2[0]['nama']; // 5)nama
    $kls2 = $result2[0]['kelas'];
// sendMessage_tbot($chat_id, 'oid user='.$oidValue2 );
//sendMessage_tbot($chat_id,  $jsonString2);

    $filter3 = [];
	//$options = ['projection' => ['_id' => 0.0]];
     $options3 = ['projection' => []];
	$read3 = new MongoDB\Driver\Query($filter3, $options3);
	$records3 = $conn->executeQuery("$dbname.$collection_kunci", $read3);
 	$res3= json_encode(iterator_to_array($records3)); //echo  
    $result3= json_decode($res3, true); 
       
 	 $jsonString3 = json_encode($result3[0]);  //1){"_id":{"$oid":"69532ce57b3df17e1e0c73d2"},"id":"304835260","nama":"nzmz","kelas":"","role":"siswa","edit":0,"delete":0,"select":0}
	
    $str3 = base64_encode($jsonString3);    // 2)eyJfaWQiOnsiJG9pZCI6IjY5NTMyY2U1N2IzZGYxN2UxZTBjNzNkMiJ9LCJpZCI6IjMwNDgzNTI2MCIsIm5hbWEiOiJuem16Iiwia2VsYXMiOiIiLCJyb2xlIjoic2lzd2EiLCJlZGl0IjowLCJkZWxldGUiOjAsInNlbGVjdCI6MH0=
  
     $count3= json_encode(count($result3));  //3)6
  
     $oidValue3= $result3[0]['_id']['$oid'];  //4)69532ce57b3df17e1e0c73d2
 
      $pel3 = $result3[0]['pel']; // 5)nama
      $kls = $result3[0]['jekas'];
$mykode = $result3[0]['kode'];
//sendMessage_tbot($chat_id, $nama );
//sendMessage_tbot($chat_id,  $jsonString3);

//////////////////////////////////////////////////////////
    $filter4 = ['id' => (string)$chat_id,];
 
	//$options = ['projection' => ['_id' => 0.0]];
     $options4 = ['projection' => []];
	$read4 = new MongoDB\Driver\Query($filter4, $options4);
	$records4 = $conn->executeQuery("$dbname.$collection_soal", $read4);
 	$res4= json_encode(iterator_to_array($records4)); //echo  
    $result4= json_decode($res4, true); 
    

    
 	 $jsonString4 = json_encode($result4[0]);  //1){"_id":{"$oid":"69532ce57b3df17e1e0c73d2"},"id":"304835260","nama":"nzmz","kelas":"","role":"siswa","edit":0,"delete":0,"select":0}
	
    $str4 = base64_encode($jsonString4);    // 2)eyJfaWQiOnsiJG9pZCI6IjY5NTMyY2U1N2IzZGYxN2UxZTBjNzNkMiJ9LCJpZCI6IjMwNDgzNTI2MCIsIm5hbWEiOiJuem16Iiwia2VsYXMiOiIiLCJyb2xlIjoic2lzd2EiLCJlZGl0IjowLCJkZWxldGUiOjAsInNlbGVjdCI6MH0=
  
     $count4= json_encode(count($result4));  //3)6
     $sesi4= json_encode(count($result4));  //3)6
     $sesi0 =$sesi+1;

 // sendMessage_tbot($chat_id, 'sesi4='.$sesi4 );
//   sendMessage_tbot($chat_id, json_encode($result4) );


     $oidValue4= $result4[0]['_id']['$oid'];  //4)69532ce57b3df17e1e0c73d2
 
     $b4 = $result4[0]['01']+$result4[0]['02']+$result4[0]['03']+$result4[0]['04']+$result4[0]['05']+$result4[0]['06']+$result4[0]['07']+$result4[0]['08']+$result4[0]['09']+$result4[0]['10']; // 5)nama
// $b4 = $result4[0]['01']+$result4[0]['02']+$result4[0]['03']+$result4[0]['04']+$result4[0]['05']+$result4[0]['06']+$result4[0]['07']+$result4[0]['08']+$result4[0]['09']+$result4[0]['10']; // 5)nama


      //////////////////////////////////////////////////////////////////////////////////////////
$filter41 = ['id' => (string)$chat_id,'sesi' => (string)$sesi4];
 
	//$options = ['projection' => ['_id' => 0.0]];
     $options41 = ['projection' => []];
	$read41 = new MongoDB\Driver\Query($filter41, $options41);
	$records41 = $conn->executeQuery("$dbname.$collection_soal", $read41);
 	$res41= json_encode(iterator_to_array($records41)); //echo  
    $result41= json_decode($res41, true);   
 	//  $jsonString41 = json_encode($result41[0]);  //1){"_id":{"$oid":"69532ce57b3df17e1e0c73d2"},"id":"3041835260","nama":"nzmz","kelas":"","role":"siswa","edit":0,"delete":0,"select":0}
    // $str41 = base641_encode($jsonString41);    // 2)eyJfaWQiOnsiJG9pZCI6IjY5NTMyY2U1N2IzZGYxN2UxZTBjNzNkMiJ9LCJpZCI6IjMwNDgzNTI2MCIsIm5hbWEiOiJuem16Iiwia2VsYXMiOiIiLCJyb2xlIjoic2lzd2EiLCJlZGl0IjowLCJkZWxldGUiOjAsInNlbGVjdCI6MH0=
    //  $count41= json_encode(count($result41));  //3)6
    //  $sesi41= json_encode(count($result41));  //3)6
    //  $oidValue41= $result41[0]['_id']['$oid'];  //41)69532ce57b3df17e1e0c73d2
    //sendMessage_tbot($chat_id, json_encode($result41) );
     $b41 = $result41[0]['01']+$result41[0]['02']+$result41[0]['03']+$result41[0]['041']+$result41[0]['05']+$result41[0]['06']+$result41[0]['07']+$result41[0]['08']+$result41[0]['09']+$result41[0]['10']; // 5)nama
// $b41 = $result4[0]['01']+$result4[0]['02']+$result4[0]['03']+$result4[0]['04']+$result4[0]['05']+$result4[0]['06']+$result4[0]['07']+$result4[0]['08']+$result4[0]['09']+$result4[0]['10']; // 5)nama

//////////////////////////////////////////////////////////

if($update['callback_query']){
    $chatcq_id = $update['callback_query']['message']['chat']['id'];
    // sendMessage_tbot($chatcq_id,  json_encode($update['callback_query']));
    //sendMessage_tbot($chatcq_id,  json_encode($chatcq_id));
//user
    $filter2 = ['id' => (string)$chatcq_id,];
	//$options = ['projection' => ['_id' => 0.0]];
     $options2 = ['projection' => []];
	$read2 = new MongoDB\Driver\Query($filter2, $options2);
	$records2 = $conn->executeQuery("$dbname.$collection_user", $read2);
 	$res2= json_encode(iterator_to_array($records2)); //echo  
    $result2= json_decode($res2, true);    
 	 $jsonString2 = json_encode($result2[0]);  //1){"_id":{"$oid":"69532ce57b3df17e1e0c73d2"},"id":"304835260","nama":"nzmz","kelas":"","role":"siswa","edit":0,"delete":0,"select":0}
	
    $str2 = base64_encode($jsonString2);    // 2)eyJfaWQiOnsiJG9pZCI6IjY5NTMyY2U1N2IzZGYxN2UxZTBjNzNkMiJ9LCJpZCI6IjMwNDgzNTI2MCIsIm5hbWEiOiJuem16Iiwia2VsYXMiOiIiLCJyb2xlIjoic2lzd2EiLCJlZGl0IjowLCJkZWxldGUiOjAsInNlbGVjdCI6MH0=
  
    $count2= json_encode(count($result2));  //3)6
  
    $oidValue2= $result2[0]['_id']['$oid'];  //4)69532ce57b3df17e1e0c73d2
 
    $nm2 = $result2[0]['nama']; // 5)nama
    $kls2 = $result2[0]['kelas'];

//soal
 $filter5 = ['id' => (string)$chatcq_id,];
 	//$options = ['projection' => ['_id' => 0.0]];
     $options5 = ['projection' => []];
	$read5 = new MongoDB\Driver\Query($filter5, $options5);
	$records5 = $conn->executeQuery("$dbname.$collection_soal", $read5);
 	$res5= json_encode(iterator_to_array($records5)); //echo  
    $result5= json_decode($res5, true); 
 
    $jsonString5 = json_encode($result5[0]);  //1){"_id":{"$oid":"69532ce57b3df17e1e0c73d2"},"id":"305835260","nama":"nzmz","kelas":"","role":"siswa","edit":0,"delete":0,"select":0}
    // $str5 = base65_encode($jsonString5);    // 2)eyJfaWQiOnsiJG9pZCI6IjY5NTMyY2U1N2IzZGYxN2UxZTBjNzNkMiJ9LCJpZCI6IjMwNDgzNTI2MCIsIm5hbWEiOiJuem16Iiwia2VsYXMiOiIiLCJyb2xlIjoic2lzd2EiLCJlZGl0IjowLCJkZWxldGUiOjAsInNlbGVjdCI6MH0=
    $count5= json_encode(count($result5));  //3)6
     $sesi5= json_encode(count($result5));  //3)6
    //  sendMessage_tbot($chatcq_id,  $jsonString5);
    // sendMessage_tbot($chatcq_id, 'sesi5='.$sesi5 );


     $oidValue5= $result5[0]['_id']['$oid'];  //5)69532ce57b3df17e1e0c73d2
 
     //    $b5 = $result5[0]['01']+$result5[0]['02']+$result5[0]['03']+$result5[0]['05']+$result5[0]['05']+$result5[0]['06']+$result5[0]['07']+$result5[0]['08']+$result5[0]['09']+$result5[0]['10']; // 5)nama
     $b5 = $result5[0]['01']+$result5[0]['02']+$result5[0]['03']+$result5[0]['05']+$result5[0]['05']+$result5[0]['06']+$result5[0]['07']+$result5[0]['08']+$result5[0]['09']+$result5[0]['10']; // 5)nama

$filter51 = ['id' => (string)$chatcq_id,'sesi' => (string)$sesi5];
 	//$options = ['projection' => ['_id' => 0.0]];
     $options51 = ['projection' => []];
	$read51 = new MongoDB\Driver\Query($filter51, $options51);
	$records51 = $conn->executeQuery("$dbname.$collection_soal", $read51);
 	$res51= json_encode(iterator_to_array($records51)); //echo  
    $result51= json_decode($res51, true); 
 
    $jsonString51 = json_encode($result51[0]);  //1){"_id":{"$oid":"695132ce517b3df17e1e0c73d2"},"id":"30518351260","nama":"nzmz","kelas":"","role":"siswa","edit":0,"delete":0,"select":0}
    // $str51 = base651_encode($jsonString51);    // 2)eyJfaWQiOnsiJG9pZCI6IjY51NTMyY2U1N2IzZGYxN2UxZTBjNzNkMiJ9LCJpZCI6IjMwNDgzNTI2MCIsIm51hbWEiOiJuem16Iiwia2VsYXMiOiIiLCJyb2xlIjoic2lzd2EiLCJlZGl0IjowLCJkZWxldGUiOjAsInNlbGVjdCI6MH0=
    $count51= json_encode(count($result51));  //3)6
     $sesi51= json_encode(count($result51));  //3)6
    //  sendMessage_tbot($chatcq_id,  $jsonString51);
    // sendMessage_tbot($chatcq_id, 'sesi51='.$sesi51 );


     $oidValue51= $result51[0]['_id']['$oid'];  //51)695132ce517b3df17e1e0c73d2
     $user51= $result51[0]['user']; 
     $skor = $result51[0];
     //    $b51 = $result51[0]['01']+$result51[0]['02']+$result51[0]['03']+$result51[0]['051']+$result51[0]['051']+$result51[0]['06']+$result51[0]['07']+$result51[0]['08']+$result51[0]['09']+$result51[0]['10']; // 51)nama
     //
     $skor5n10 = $result51[0]['01']+$result51[0]['02']+$result51[0]['03']+$result51[0]['04']+$result51[0]['05']+$result51[0]['06']+$result51[0]['07']+$result51[0]['08']+$result51[0]['09']+$result51[0]['10']; // 51)nama
     $skor5n11 = $result51[0]['01']+$result51[0]['02']+$result51[0]['03']+$result51[0]['04']+$result51[0]['05']+$result51[0]['06']+$result51[0]['07']+$result51[0]['08']+$result51[0]['09']+$result51[0]['10']+$result51[0]['11']; // 51)nama
     $skor5n12 = $result51[0]['01']+$result51[0]['02']+$result51[0]['03']+$result51[0]['04']+$result51[0]['05']+$result51[0]['06']+$result51[0]['07']+$result51[0]['08']+$result51[0]['09']+$result51[0]['10']+$result51[0]['11']+$result51[0]['12']; // 51)nama
     $skor5n13 = $result51[0]['01']+$result51[0]['02']+$result51[0]['03']+$result51[0]['04']+$result51[0]['05']+$result51[0]['06']+$result51[0]['07']+$result51[0]['08']+$result51[0]['09']+$result51[0]['10']+$result51[0]['11']+$result51[0]['12']+$result51[0]['13']; // 51)nama
    $skor5n14 = $result51[0]['01']+$result51[0]['02']+$result51[0]['03']+$result51[0]['04']+$result51[0]['05']+$result51[0]['06']+$result51[0]['07']+$result51[0]['08']+$result51[0]['09']+$result51[0]['10']+$result51[0]['11']+$result51[0]['12']+$result51[0]['13']+$result51[0]['14']; // 51)nama
    $skor5n15 = $result51[0]['01']+$result51[0]['02']+$result51[0]['03']+$result51[0]['04']+$result51[0]['05']+$result51[0]['06']+$result51[0]['07']+$result51[0]['08']+$result51[0]['09']+$result51[0]['10']+$result51[0]['11']+$result51[0]['12']+$result51[0]['13']+$result51[0]['14']+$result51[0]['15']; // 51)nama


 $j_soal1 = $jsonData['soal']['jumlah'];

        if($j_soal1 == "10"){
            $skor5a= $skor5n10;
        }
        if($j_soal1 == "11"){
            $skor5a= $skor5n11;
        }
        if($j_soal1 == "12"){
            $skor5a= $skor5n12;
        }
        if($j_soal1 == "13"){
            $skor5a= $skor5n13;
        }
        if($j_soal1 == "14"){
            $skor5a= $skor5n14;
        }
        if($j_soal1 == "15"){
            $skor5a= $skor5n15;
        }


$user5_acak= $result51[0]['acak']; 



    }
      //////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////////////////////////
$filter41 = ['id' => (string)$chat_id,'sesi' => (string)$sesi4];
 
	//$options = ['projection' => ['_id' => 0.0]];
     $options41 = ['projection' => []];
	$read41 = new MongoDB\Driver\Query($filter41, $options41);
	$records41 = $conn->executeQuery("$dbname.$collection_soal", $read41);
 	$res41= json_encode(iterator_to_array($records41)); //echo  
    $result41= json_decode($res41, true);   
 	 $jsonString41 = json_encode($result41[0]);  //1){"_id":{"$oid":"69532ce57b3df17e1e0c73d2"},"id":"3041835260","nama":"nzmz","kelas":"","role":"siswa","edit":0,"delete":0,"select":0}
    // $str41 = base641_encode($jsonString41);    // 2)eyJfaWQiOnsiJG9pZCI6IjY5NTMyY2U1N2IzZGYxN2UxZTBjNzNkMiJ9LCJpZCI6IjMwNDgzNTI2MCIsIm5hbWEiOiJuem16Iiwia2VsYXMiOiIiLCJyb2xlIjoic2lzd2EiLCJlZGl0IjowLCJkZWxldGUiOjAsInNlbGVjdCI6MH0=
    //  $count41= json_encode(count($result41));  //3)6
    //  $sesi41= json_encode(count($result41));  //3)6
    //  $oidValue41= $result41[0]['_id']['$oid'];  //41)69532ce57b3df17e1e0c73d2
    $user41 = $result41[0]['user'];
     $b41 = $result41[0]['01']+$result41[0]['02']+$result41[0]['03']+$result41[0]['041']+$result41[0]['05']+$result41[0]['06']+$result41[0]['07']+$result41[0]['08']+$result41[0]['09']+$result41[0]['10']; // 5)nama
    // $b41 = $result4[0]['01']+$result4[0]['02']+$result4[0]['03']+$result4[0]['04']+$result4[0]['05']+$result4[0]['06']+$result4[0]['07']+$result4[0]['08']+$result4[0]['09']+$result4[0]['10']; // 5)nama
    //sendMessage_tbot($chatcq_id,  $jsonString41);
     
        $mysesi = $sesi4;
      
        $mysesi = $sesi5;
      
      
//sendMessage_tbot($chat_id,  $b4);

//insert_dt();

 
   $file_id = $update['message']['photo'][0]['file_id'];
    $photo = $update['message'];


// $api_url = 'https://api.telegram.org/bot' . $bot_token . '/getFile?file_id=' . $file_id;

// $response = file_get_contents($api_url);
// $file_info = json_decode($response, true);

// if ($file_info['ok']) {
//     $file_path = $file_info['result']['file_path'];
//     sendMessage_tbot($chat_id, $file_path);
//     // Proceed to the next step with $file_path
// }

// sendMessage_tbot($chat_id, json_encode($file_info));










function updateid_db($chat_id, $set_values,$dbname,$collection,$sesi) {

global $conn,$dbname;
$update = new MongoDB\Driver\BulkWrite();
$update->update(
	['id' => (string)$chat_id,'sesi'=>(string)$sesi], ['$set' => $set_values], ['multi' => false, 'upsert' => false]
);

$result = $conn->executeBulkWrite("$dbname.$collection", $update);

// verify
if ($result->getModifiedCount() == 1) {
    echo json_encode(
		array("message" => "Record successfully updated")
	);
    // sendMessage_tbot($chat_id, "Record successfully updated");
} else {
    echo json_encode(
            array("message" => "Error while updating record")
    );
    // sendMessage_tbot($chat_id, "Error while updating record");
}

}

// $data1 = ["10" => 1];
//   update_soal($chat_id, ["10" => 1],5);
 
 






////////////////////////////////////////soal/////////////////////////////////////////sendMessage_tbot($chat_id, 'oid soalr='//.$oidValue3 );
 


// $pth = "https://isekolah.my.id/myWebhook/soal/".$paket_1 ."/".$jsonData['jawab'][trim($array5[0])].".JPG";
// sendMessage_tbot($chat_idq, $pth);
$pecah = (explode('@',$text));
     $_txt0= $pecah['0'];
     $_txt1= $pecah['1'];
     $txt2= $pecah['2'];
//  sendMessage_tbot($chat_id, $_txt0.$_txt1.$adm_mulai_soal );

$callback_H = trim(trim($callback_data,"#"));
$callback_abcdsH  = trim($callback_data,"abcds#");



if ($_txt0 == $adm_mulai_soal ) {

// if ($_txt0 == $adm_mulai_soal and ($count4 >= $result3[0]['kali'])) {




  inserts_dt_acak();
    // sendMessage_tbot($chat_id, 'mulai sesi '.$sesi);
//    sendMessage_tbot($chat_id, $_txt0.$_txt1.$ar0 );
/////////////////////////////
        //sendMessage_tbot($chat_id, "Hello!Selamat Datang to your bot.");
        $url_img = $urlsoal.$jsonData['img']['mulai']; // Mendapatkan file_id
        //  $url_img = "soal/".$jsonData['soal']['nama_paket']."/".$jsonData['img']['mulai']; 
        //$chat_id = $update['message']['chat']['id'];
        
        $caption1 = "nama : ".$_txt1."\nMata Pelajaran : ".$jsonData['soal']['pelajaran']."\nPaket : ".$jsonData['soal']['nama_paket']."\nJumlah soal : ".$jsonData['soal']['jumlah'];  
        $inlineKeyboard = [
                [
                    ['text' => 'Mulai', 'callback_data' => '#mulai']
                    
                ],
                // Second row of buttons (optional)
                [
                    ['text' => 'Petunjuk', 'url' => 'https://www.google.com'] // URL button example
                ] 
        ];
        // sendpoto($chat_id,$url_img,$inlineKeyboard,$caption1); 
        $local_img = './soal/'.$jsonData['soal']['nama_paket']."/".$jsonData['img']['mulai']; 
        sendpoto1($chat_id,$local_img,$inlineKeyboard,$caption1);
        // sendMessage_tbot($chat_id,  $url_img);
        }
    
$array5 = explode(",",$user5_acak);
//print_r($array5[0]);
$ar0=$array5[0];
}
//sendMessage_tbot($chatcq_id, $callback_data );

if($callback_querys){

    
   $callback_data = $update['callback_query']['data'];
$chat_idq = $update['callback_query']['message']['chat']['id'];
$message_id = $update['callback_query']['message']['message_id'];
// sendMessage_tbot($chat_idq, $callback_data );

if('#mulai' == $callback_data ){  
      sendMessage_tbot($chatcq_id, 'mulai sesi '.$sesi5 );
//sendMessage_tbot($chatcq_id, 'mulai ok '.$ar0 );

$url_img = $urlsoal.$jsonData_img[trim($array5[0])]; // Mendapatkan file_id
$caption1 = "no 1";
// sendMessage_tbot($chatcq_id, 'url '.$caption1 );
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => "#".trim($array5[0]).'a'],
            ['text' => 'D BENAR', 'callback_data' => "#".trim($array5[0]).'d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => "#".trim($array5[0]).'b'],
            ['text' => 'E BENAR', 'callback_data' => "#".trim($array5[0]).'e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => "#".trim($array5[0]).'c'],
            ['text' => 'Semua Salah', 'callback_data' => "#".trim($array5[0]).'s']
        ] 
];
// sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
$pth = "https://isekolah.my.id/myWebhook/soal/".$paket_1 ."/".$jsonData['jawab'][trim($array5[0])].".JPG";
// sendMessage_tbot($chat_idq, $pth);
$local_img = './soal/'.$paket_1 ."/".$jsonData['jawab'][trim($array5[0])].".JPG";
sendpoto1($chat_idq,$local_img,$inlineKeyboard,$caption1);
}






if( $callback_abcdsH == trim($array5[0])){  
    sendMessage_tbot($chat_idq, "no 2" );
// sendMessage_tbot($chat_idq, $call1 );
    
$url_img1 = $urlsoal.$jsonData_img[trim($array5[1])]; // Mendapatkan file_id
$caption1 = "no 2";

// sendMessage_tbot($chat_idq, $url_img );

$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => "#".trim($array5[1]).'a'],
            ['text' => 'D BENAR', 'callback_data' => "#".trim($array5[1]).'d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => "#".trim($array5[1]).'b'],
            ['text' => 'E BENAR', 'callback_data' => "#".trim($array5[1]).'e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => "#".trim($array5[1]).'c'],
            ['text' => 'Semua Salah', 'callback_data' => "#".trim($array5[1]).'s']
        ] 
];

// sendpoto($chat_idq,$url_img1,$inlineKeyboard,$caption1);
$pth = "https://isekolah.my.id/myWebhook/soal/".$paket_1 ."/".$jsonData['jawab'][trim($array5[1])].".JPG";
// sendMessage_tbot($chat_idq, $pth);
$local_img = './soal/'.$paket_1 ."/".$jsonData['jawab'][trim($array5[1])].".JPG";
sendpoto1($chat_idq,$local_img,$inlineKeyboard,$caption1);


// sendMessage_tbot($chat_idq, $pth);
//  sendMessage_tbot($chat_id, "sesi = ".$sesi5);
//  sendMessage_tbot($chat_id, "no soal = ".$array5[0]);
//  sendMessage_tbot($chat_idq, "jawaban json=".$jsonData['jawab'][trim($array5[0])]);
// sendMessage_tbot($chat_idq, "call back =".$callback_H );
// sendMessage_tbot($chat_idq, $data1);

if($callback_H == $jsonData['jawab'][trim($array5[0])]){

$data1 = [trim($array5[0]) => 1,'y' => $skor5a*10];
sendMessage_tbot($chat_idq, 'benar');
}else{
$data1 = [trim($array5[0]) => 0,'y' => $skor5a*10]; 
sendMessage_tbot($chat_idq, 'salah');
 }
update_soal($chat_idq, $data1,$sesi5);

 
 //  update_soal($chat_id, $data1,5);



//  updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
 //update_soal($chat_idq, $data1,$sesi5);

// $update = new MongoDB\Driver\BulkWrite();
// $update->update(
// 	['id' => (string)$chat_idq,'sesi'=>(string)$sesi5], ['$set' => $data1], ['multi' => false, 'upsert' => false]
// );
// $result = $conn->executeBulkWrite("$dbname.$collection_soal", $update);
}







if( $callback_abcdsH == trim($array5[1])){  
    sendMessage_tbot($chat_idq, "no 3" );
// sendMessage_tbot($chat_idq, $call1 );
    
$url_img2 = $urlsoal.$jsonData_img[trim($array5[2])]; // Mendapatkan file_id
$caption1 = "no 3";
// sendMessage_tbot($chat_idq, $url_img );
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => "#".trim($array5[2]).'a'],
            ['text' => 'D BENAR', 'callback_data' => "#".trim($array5[2]).'d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => "#".trim($array5[2]).'b'],
            ['text' => 'E BENAR', 'callback_data' => "#".trim($array5[2]).'e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => "#".trim($array5[2]).'c'],
            ['text' => 'Semua Salah', 'callback_data' => "#".trim($array5[2]).'s']
        ] 
];

// sendpoto($chat_idq,$url_img2,$inlineKeyboard,$caption1);
$pth = "https://isekolah.my.id/myWebhook/soal/".$paket_1 ."/".$jsonData['jawab'][trim($array5[2])].".JPG";
// sendMessage_tbot($chat_idq, $pth);
$local_img = './soal/'.$paket_1 ."/".$jsonData['jawab'][trim($array5[2])].".JPG";
sendpoto1($chat_idq,$local_img,$inlineKeyboard,$caption1);


// sendMessage_tbot($chat_idq, $pth);
// sendMessage_tbot($chat_idq, "jawaban json=".$jsonData['jawab'][trim($array5[1])]);
// sendMessage_tbot($chat_idq, "call back =".$callback_H );

if($callback_H == $jsonData['jawab'][trim($array5[1])]){

$data1 = [trim($array5[1]) => 1,'y' => $skor5a*10];
sendMessage_tbot($chat_idq, 'benar');
}else{
$data1 = [trim($array5[1]) => 0,'y' => $skor5a*10]; 
sendMessage_tbot($chat_idq, 'salah');
}
update_soal($chat_idq, $data1,$sesi5);
 //updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
}




if( $callback_abcdsH == trim($array5[2])){  
    sendMessage_tbot($chat_idq, "no 4" );
// sendMessage_tbot($chat_idq, $call1 );
    
$url_img = $urlsoal.$jsonData_img[trim($array5[3])]; // Mendapatkan file_id
$caption1 = "no 4";
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => "#".trim($array5[3]).'a'],
            ['text' => 'D BENAR', 'callback_data' => "#".trim($array5[3]).'d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => "#".trim($array5[3]).'b'],
            ['text' => 'E BENAR', 'callback_data' => "#".trim($array5[3]).'e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => "#".trim($array5[3]).'c'],
            ['text' => 'Semua Salah', 'callback_data' => "#".trim($array5[3]).'s']
        ] 
];

// sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
$pth = "https://isekolah.my.id/myWebhook/soal/".$paket_1 ."/".$jsonData['jawab'][trim($array5[3])].".JPG";
// sendMessage_tbot($chat_idq, $pth);

$local_img = './soal/'.$paket_1 ."/".$jsonData['jawab'][trim($array5[3])].".JPG";
sendpoto1($chat_idq,$local_img,$inlineKeyboard,$caption1);


// sendMessage_tbot($chat_idq, $pth);
// sendMessage_tbot($chat_idq, "jawaban json=".$jsonData['jawab'][trim($array5[2])]);
// sendMessage_tbot($chat_idq, "call back =".$callback_H );


if($callback_H == $jsonData['jawab'][trim($array5[2])]){

$data1 = [trim($array5[2]) => 1,'y' => $skor5a*10];
sendMessage_tbot($chat_idq, 'benar');
}else{
$data1 = [trim($array5[2]) => 0,'y' => $skor5a*10]; 
sendMessage_tbot($chat_idq, 'salah');
}
update_soal($chat_idq, $data1,$sesi5);
 //updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
}





if( $callback_abcdsH == trim($array5[3])){  
    sendMessage_tbot($chat_idq, "no 5" );
// sendMessage_tbot($chat_idq, $call1 );
    
$url_img = $urlsoal.$jsonData_img[trim($array5[3])]; // Mendapatkan file_id
$caption1 = "no 5";
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => "#".trim($array5[4]).'a'],
            ['text' => 'D BENAR', 'callback_data' => "#".trim($array5[4]).'d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => "#".trim($array5[4]).'b'],
            ['text' => 'E BENAR', 'callback_data' => "#".trim($array5[4]).'e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => "#".trim($array5[4]).'c'],
            ['text' => 'Semua Salah', 'callback_data' => "#".trim($array5[4]).'s']
        ] 
];

// sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
$pth = "https://isekolah.my.id/myWebhook/soal/".$paket_1 ."/".$jsonData['jawab'][trim($array5[4])].".JPG";
// sendMessage_tbot($chat_idq, $pth);

$local_img = './soal/'.$paket_1 ."/".$jsonData['jawab'][trim($array5[4])].".JPG";
sendpoto1($chat_idq,$local_img,$inlineKeyboard,$caption1);

// sendMessage_tbot($chat_idq, $pth);
// sendMessage_tbot($chat_idq, "jawaban json=".$jsonData['jawab'][trim($array5[3])]);
// sendMessage_tbot($chat_idq, "call back =".$callback_H );

if($callback_H == $jsonData['jawab'][trim($array5[3])]){

$data1 = [trim($array5[3]) => 1,'y' => $skor5a*10];
sendMessage_tbot($chat_idq, 'benar');
}else{
$data1 = [trim($array5[3]) => 0,'y' => $skor5a*10]; 
sendMessage_tbot($chat_idq, 'salah');
}
update_soal($chat_idq, $data1,$sesi5);
// updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
}




if( $callback_abcdsH == trim($array5[4])){  
    sendMessage_tbot($chat_idq, "no 6" );
// sendMessage_tbot($chat_idq, $call1 );
    
$url_img = $urlsoal.$jsonData_img[trim($array5[5])]; // Mendapatkan file_id
$caption1 = "no 6";
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => "#".trim($array5[5]).'a'],
            ['text' => 'D BENAR', 'callback_data' => "#".trim($array5[5]).'d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => "#".trim($array5[5]).'b'],
            ['text' => 'E BENAR', 'callback_data' => "#".trim($array5[5]).'e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => "#".trim($array5[5]).'c'],
            ['text' => 'Semua Salah', 'callback_data' => "#".trim($array5[5]).'s']
        ] 
];

// sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
$pth = "https://isekolah.my.id/myWebhook/soal/".$paket_1 ."/".$jsonData['jawab'][trim($array5[5])].".JPG";
// sendMessage_tbot($chat_idq, $pth);
$local_img = './soal/'.$paket_1."/".$jsonData['jawab'][trim($array5[5])].".JPG";
sendpoto1($chat_idq,$local_img,$inlineKeyboard,$caption1);

// sendMessage_tbot($chat_idq, $pth);
// sendMessage_tbot($chat_idq, "jawaban json=".$jsonData['jawab'][trim($array5[4])]);
// sendMessage_tbot($chat_idq, "call back =".trim($callback_data,"#") );

if($callback_H == $jsonData['jawab'][trim($array5[4])]){

$data1 = [trim($array5[4]) => 1,'y' => $skor5a*10];
sendMessage_tbot($chat_idq, 'benar');
}else{
$data1 = [trim($array5[4]) => 0,'y' => $skor5a*10]; 
sendMessage_tbot($chat_idq, 'salah');
}
update_soal($chat_idq, $data1,$sesi5);
// updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);

}


if( $callback_abcdsH == trim($array5[5])){  
    sendMessage_tbot($chat_idq, "no 7" );
// sendMessage_tbot($chat_idq, $call1 );
    
$url_img = $urlsoal.$jsonData_img[trim($array5[6])]; // Mendapatkan file_id
$caption1 = "no 7";

$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => "#".trim($array5[6]).'a'],
            ['text' => 'D BENAR', 'callback_data' => "#".trim($array5[6]).'d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => "#".trim($array5[6]).'b'],
            ['text' => 'E BENAR', 'callback_data' => "#".trim($array5[6]).'e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => "#".trim($array5[6]).'c'],
            ['text' => 'Semua Salah', 'callback_data' => "#".trim($array5[6]).'s']
        ] 
];

// sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
$pth = "https://isekolah.my.id/myWebhook/soal/".$paket_1 ."/".$jsonData['jawab'][trim($array5[6])].".JPG";
// sendMessage_tbot($chat_idq, $pth);
$local_img = './soal/'.$paket_1."/".$jsonData['jawab'][trim($array5[6])].".JPG";
sendpoto1($chat_idq,$local_img,$inlineKeyboard,$caption1);

// sendMessage_tbot($chat_idq, $pth);
// sendMessage_tbot($chat_idq, "jawaban json=".$jsonData['jawab'][trim($array5[5])]);
// sendMessage_tbot($chat_idq, "call back =".trim($callback_data,"# ") );


if(trim($callback_data,"# ") == $jsonData['jawab'][trim($array5[5])]){

$data1 = [trim($array5[5]) => 1,'y' => $skor5a*10];
sendMessage_tbot($chat_idq, 'benar');
}else{
$data1 = [trim($array5[5]) => 0,'y' => $skor5a*10]; 
sendMessage_tbot($chat_idq, 'salah');
}
update_soal($chat_idq, $data1,$sesi5);
 //updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);




}
if( $callback_abcdsH == trim($array5[6])){  
    sendMessage_tbot($chat_idq, "no 8");
// sendMessage_tbot($chat_idq, $call1 );
    
$url_img = $urlsoal.$jsonData_img[trim($array5[7])]; // Mendapatkan file_id
$caption1 = "no 8";
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => "#".trim($array5[7]).'a'],
            ['text' => 'D BENAR', 'callback_data' => "#".trim($array5[7]).'d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => "#".trim($array5[7]).'b'],
            ['text' => 'E BENAR', 'callback_data' => "#".trim($array5[7]).'e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => "#".trim($array5[7]).'c'],
            ['text' => 'Semua Salah', 'callback_data' => "#".trim($array5[7]).'s']
        ] 
];

// sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
$pth = "https://isekolah.my.id/myWebhook/soal/".$paket_1 ."/".$jsonData['jawab'][trim($array5[7])].".JPG";
// sendMessage_tbot($chat_idq, $pth);
$local_img = './soal/'.$paket_1."/".$jsonData['jawab'][trim($array5[7])].".JPG";
sendpoto1($chat_idq,$local_img,$inlineKeyboard,$caption1);
// sendMessage_tbot($chat_idq, $pth);

// sendMessage_tbot($chat_idq, "jawaban json=".$jsonData['jawab'][trim($array5[6])]);
// sendMessage_tbot($chat_idq, "call back =".trim($callback_data,"#") );

if($callback_H == $jsonData['jawab'][trim($array5[6])]){

$data1 = [trim($array5[6]) => 1,'y' => $skor5a*10];
sendMessage_tbot($chat_idq, 'benar');
}else{
$data1 = [trim($array5[6]) => 0,'y' => $skor5a*10]; 
sendMessage_tbot($chat_idq, 'salah');
}
update_soal($chat_idq, $data1,$sesi5);
// updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);





}

if( $callback_abcdsH == trim($array5[7])){  
    sendMessage_tbot($chat_idq, "no 9" );
// sendMessage_tbot($chat_idq, $call1 );
    
$url_img = $urlsoal.$jsonData_img[trim($array5[8])]; // Mendapatkan file_id
$caption1 = "no 9";
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => "#".trim($array5[8]).'a'],
            ['text' => 'D BENAR', 'callback_data' => "#".trim($array5[8]).'d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => "#".trim($array5[8]).'b'],
            ['text' => 'E BENAR', 'callback_data' => "#".trim($array5[8]).'e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => "#".trim($array5[8]).'c'],
            ['text' => 'Semua Salah', 'callback_data' => "#".trim($array5[8]).'s']
        ] 
];

// sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
$pth = "https://isekolah.my.id/myWebhook/soal/".$paket_1 ."/".$jsonData['jawab'][trim($array5[8])].".JPG";
// sendMessage_tbot($chat_idq, $pth);
$local_img = './soal/'.$paket_1."/".$jsonData['jawab'][trim($array5[8])].".JPG";
sendpoto1($chat_idq,$local_img,$inlineKeyboard,$caption1);


// sendMessage_tbot($chat_idq, $pth);

// sendMessage_tbot($chat_idq, "jawaban json=".$jsonData['jawab'][trim($array5[7])]);
// sendMessage_tbot($chat_idq, "call back =".trim(trim($callback_data,"#")) );

if($callback_H == $jsonData['jawab'][trim($array5[7])]){

$data1 = [trim($array5[7]) => 1,'y' => $skor5a*10];
sendMessage_tbot($chat_idq, 'benar');
}else{
$data1 = [trim($array5[7]) => 0,'y' => $skor5a*10]; 
sendMessage_tbot($chat_idq, 'salah');
}
update_soal($chat_idq, $data1,$sesi5);
 //updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);




}

 if( $callback_abcdsH == trim($array5[8])){  
    sendMessage_tbot($chat_idq, "no 10" );
// sendMessage_tbot($chat_idq, $call1 );
    
$url_img = $urlsoal.$jsonData_img[trim($array5[9])]; // Mendapatkan file_id
$caption1 = "no 10";
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => "#".trim($array5[9]).'a'],
            ['text' => 'D BENAR', 'callback_data' => "#".trim($array5[9]).'d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => "#".trim($array5[9]).'b'],
            ['text' => 'E BENAR', 'callback_data' => "#".trim($array5[9]).'e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => "#".trim($array5[9]).'c'],
            ['text' => 'Semua Salah', 'callback_data' => "#".trim($array5[9]).'s']
        ] 
];

// sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);

$pth = "https://isekolah.my.id/myWebhook/soal/".$paket_1 ."/".$jsonData['jawab'][trim($array5[9])].".JPG";
// sendMessage_tbot($chat_idq, $pth);
$local_img = './soal/'.$paket_1."/".$jsonData['jawab'][trim($array5[9])].".JPG";
sendpoto1($chat_idq,$local_img,$inlineKeyboard,$caption1);

// sendMessage_tbot($chat_idq, $pth);
// sendMessage_tbot($chat_idq, "jawaban json=".$jsonData['jawab'][trim($array5[8])]);
// sendMessage_tbot($chat_idq, "call back =".trim($callback_data,"# ") );

if($callback_H == $jsonData['jawab'][trim($array5[8])]){

$data1 = [trim($array5[8]) => 1,'y' => $skor5a*10];
sendMessage_tbot($chat_idq, 'benar');
}else{
$data1 = [trim($array5[8]) => 0,'y' => $skor5a*10]; 
sendMessage_tbot($chat_idq, 'salah');
}
update_soal($chat_idq, $data1,$sesi5);
 // updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);




}

if( $callback_abcdsH == trim($array5[9])){   
$url_img = $urlsoal.$jsonData['img']['selesai']; // Mendapatkan file_id
$caption1 = $jsonData['ket']['selesai'];;
//$url_img = $urlsoal.'selesai.JPG'; // Mendapatkan file_id
//$caption1 = "Terima Kasih ";
$inlineKeyboard = [
         [
            ['text' => 'Kirim Jawaban', 'callback_data' => '00']       
        ]
        
];
// sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
$pth = "https://isekolah.my.id/myWebhook/soal/".$paket_1 ."/".$jsonData['img']['selesai'];
// sendMessage_tbot($chat_idq, $pth);
$local_img = './soal/'.$paket_1."/".$jsonData['img']['selesai'];
sendpoto1($chat_idq,$local_img,$inlineKeyboard,$caption1);
// sendMessage_tbot($chat_idq,  $urlsoal.$jsonData['img']['selesai']);
// sendMessage_tbot($chat_idq, "jawaban json=".$jsonData['jawab'][trim($array5[9])]);
// sendMessage_tbot($chat_idq, "call back =".$callback_H );

   if($callback_H == $jsonData['jawab'][trim($array5[9])]){

    $data1 = [trim($array5[9]) => 1,'end_at' => $millisecondsString1,'y' => $skor5a*10];
    sendMessage_tbot($chat_idq, 'benar');
    }else{
    $data1 = [trim($array5[9]) => 0,'end_at' => $millisecondsString1,'y' => $skor5a*10]; 
    sendMessage_tbot($chat_idq, 'salah');
    }
update_soal($chat_idq, $data1,$sesi5);
// updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);


}



if(preg_match('/^00/', $callback_data) ){  ///ok

   $j_soal1 = $jsonData['soal']['jumlah'];

        if($j_soal1 == "10"){
            $skor5a= $skor5n10;
        }
        if($j_soal1 == "11"){
            $skor5a= $skor5n11;
        }
        if($j_soal1 == "12"){
            $skor5a= $skor5n12;
        }
        if($j_soal1 == "13"){
            $skor5a= $skor5n13;
        }
        if($j_soal1 == "14"){
            $skor5a= $skor5n14;
        }
        if($j_soal1 == "15"){
            $skor5a= $skor5n15;
        }

        $nilai = ( $skor5a *100)/ (int)$j_soal1;

        $data1 = ['skor' => $skor5a,'y' => $skor5a*10,'nilai' => $nilai]; 
   
   sendMessage_tbot($chat_idq, 'selesai sesi '.$sesi5.  ' , User : '.$user51);

// updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
update_soal($chat_idq, $data1,$sesi5);

    $created_at = $result51[0]['created_at'];
    $end_at= $result51[0]['end_at'];

    $ltime= $end_at-$created_at;
    //sendMessage_tbot( $chat_id, $ltime);

    $seconds = round( $ltime/ 1000); // 1234567 / 1000 = 1234.567, round menjadi 1235 detik
    // Hitung jam, menit, dan detik
    $hours = floor($seconds / 3600); // 1235 / 3600 = 0 jam
    $seconds %= 3600; // Sisa detik setelah jam: 1235 % 3600 = 1235 detik
    $minutes = floor($seconds / 60); // 1235 / 60 = 20 menit
    $seconds %= 60; // Sisa detik setelah menit: 1235 % 60 = 35 detik
   // Format waktu menjadi HH:MM:SS
    //$timeFormat = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
    // $timeFormat = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);

    // echo "Waktu: " . $timeFormat; // Output: Waktu: 00:20:35
    // sendMessage_tbot( $chat_idq, "Waktu: " . $timeFormat);
    $data1 = ['wkerja' => $minutes." menit, ".$seconds." detik"]; 
    update_soal($chat_idq, $data1,$sesi5);
 // updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
  sendMessage_tbot($chat_idq, "Waktu mengerjakan : " . $minutes." menit, ".$seconds." detik");


}


 $nm2 = $result2[0]['nama']; // 5)nama
     $kls2 = $result2[0]['kelas'];

     $skor_ = (explode(' ',$text));
     $skor0= $skor_['0'];
     $skor1= $skor_['1'];
     $skor2= $skor_['2'];
     
     

if ($skor0 == '#skor' and $skor1 ) {
     $filter_sk = ['id' => (string)$chat_id,'sesi' => (string)$skor1];
 	//$options = ['projection' => ['_id' => 0.0]];
     $options_sk = ['projection' => []];
	$read_sk = new MongoDB\Driver\Query($filter_sk, $options_sk);
	$records_sk = $conn->executeQuery("$dbname.$collection_soal", $read_sk);
 	$res_sk= json_encode(iterator_to_array($records_sk)); //echo  
    $result_sk= json_decode($res_sk, true); 
    $jsonString_sk = json_encode($result_sk[0]);
$urutan = getKeyBasedOnName($arr,$skor1)+1;

    sendMessage_tbot($chat_id, 'user ='.$result_sk[0]['user'].
    "\nMata Pelajaran = ".$result_sk[0]['pel'].
    "\nJumlah Benar = ".$result_sk[0]['skor']."/".$jsonData['soal']['jumlah'].
    "\nNilai= ".$result_sk[0]['nilai'].
    "\ngrup Test = #".$result_sk[0]['Gsoal'].
    "\nurutan ke - = ".$urutan
    );
   }



     $adm = (explode(',',$text));
     $adm0= $adm['0'];
     $adm1= $adm['1'];
     $adm2= $adm['2'];

if ($adm0 == $adm_send_admin  and  $adm1 ) {

$filter_adm = ['id' => (string)$chat_id];
 	//$options = ['projection' => ['_id' => 0.0]];
     $options_adm = ['projection' => []];
	$read_adm = new MongoDB\Driver\Query($filter_adm, $options_adm);
	$records_adm = $conn->executeQuery("$dbname.$collection_user", $read_adm);
 	$res_adm= json_encode(iterator_to_array($records_adm)); //echo  
    $result_adm= json_decode($res_adm, true); 
    $jsonString_adm = json_encode($result_adm[0]);

    sendMessage_tbot($chat_id_admin, '?user,'.$chat_id .', nama-> '.$result_adm[0]['nama'].', kelas-> '.$result_adm[0]['kelas'].', pertanyaan-> '.$adm1 );
     }

if ($text == $adm_info_user ) {

     $filter_dt = ['id' => (string)$chat_id];
 	$options = ['projection' => ['_id' => 0.0]];
    //  $options_dt = ['projection' => []];
	$read_dt = new MongoDB\Driver\Query($filter_dt, $options);
	$records_dt = $conn->executeQuery("$dbname.$collection_user", $read_dt);
 	$res_dt= json_encode(iterator_to_array($records_dt)); //echo  
    $result_dt= json_decode($res_dt, true); 
    $jsonString_dt = json_encode($result_dt[0]);
    $text2 = trim($jsonString_dt,"{}");
    $newString = str_replace(",", "\n", $text2);
    sendMessage_tbot($chat_id, $newString );
   
    }


     $use = (explode(',',$text));
     $use0= $use['0'];
     $use1= $use['1'];
     $use2= $use['2'];

if ($use0 == '?user'  and  $use1 and $use2) {
    sendMessage_tbot($use1, 'admin-> '.$use2 );
    }

     $del = (explode(',',$text));
     $del0= $del['0'];
     $del1= $del['1'];
     $del2= $del['2'];

if ($del0 == 'del_soal' and $del1 and $del2 ) {

    $delete = new MongoDB\Driver\BulkWrite();
    $delete->delete(
	['id' => (string)$del1,'sesi' => (string)$del2],
	['limit' => 0]
    );

     $result = $conn->executeBulkWrite("$dbname.$collection_soal", $delete);


    if ($result->getDeletedCount() == 1) {
    echo json_encode(
		array("message" => "Record successfully deleted")
        
	);
    sendMessage_tbot($chat_id, "Record successfully deleted");
    } else {
    echo json_encode(
            array("message" => "Error while deleting record")
    );
    sendMessage_tbot($chat_id, "Error while deleting record");
    }
    // }
    // deleteid_db($del1, $dbname,$collection_soal);
   

        //if ($del0 == 'del1' and $del1 ) {
        //deleteid_db($del1, $dbname,$collection_user);
        //}
  
   












     $ket = (explode(',',$text));
     $ket0= $ket['0'];
     $ket1= $ket['1'];
     $ket2= $ket['2'];
     $ket3= $ket['3'];
     $ket4= $ket['4'];

if($ket0 == $adm_input_ket and $ket1 and $ket4 == $ket_adm ){

    // $ket11 = getChatIdFromUsername($ket1);
    $data1 = ["ket" => $ket2];  

    $update = new MongoDB\Driver\BulkWrite();
    $update->update(
        ['id' => $ket1], ['$set' => $data1], ['multi' => false, 'upsert' => false]
    );

    $result = $conn->executeBulkWrite("$dbname.$collection_user", $update);


    if ($result->getModifiedCount() == 1) {
        
        sendMessage_tbot($chat_id, "Record successfully updated keterangan");
        } 


        return false;

        }


if ($text == 'admin' and ($chat_id == $chat_id_admin)) {   //admin

    sendMessage_tbot($chat_id_admin, "update ket = ".$adm_input_ket.",2045357439,<isi ket>,".$inputKet." \ndataku = $adm_info_user\ngup soal = ". $adm_Grup_soal);
    sendMessage_tbot($chat_id_admin, "daftar userBaru =". $adm_new_user.",<nama> \ndaftarsoal = ".$adm_mulai_soal.",<nama user>  \nGenQrcode = /qr2,/qr20  \ntampilkan skor = #skor,<sesi>  \nbertanya admin = ".$adm_send_admin." ,<pertanyan>  \ncek data = /cek" );
   
    sendMessage_tbot($chat_id_admin, $jsonString_adm ."\nupdate_id,<id>,<input>\nupdate_ket,<ket>,<input>"); 

}
     $up = (explode(',',$text));
     $up0= $up['0'];
     $up1= $up['1'];
     $up2= $up['2'];

if ($up0 == 'update_id' and $up1 and $up2 ) {   //admin
    // sendMessage_tbot($chat_id, $up0.$up1);
   // $oid = 'ObjectId("695717ee8d9bcc741ec16bf3")';
    $set_values = ["input" => $up2];   //admin
    $update = new MongoDB\Driver\BulkWrite();
    $update->update(
        ['idData' => $up1], ['$set' => $set_values], ['multi' => false, 'upsert' => false]
    );                              
    $result = $conn->executeBulkWrite("$dbname.$collection_setting", $update);
    if ($result->getModifiedCount() == 1) { 
        sendMessage_tbot($chat_id_admin, "Record successfully updated ".$up1."=>".$up2);
    } else {  
        sendMessage_tbot($chat_id_admin, "Error while updating record ");
    }
    return false;
    }

if ($up0 == 'update_ket' and $up1 and $up2 ) {   //admin
    // sendMessage_tbot($chat_id, $up0.$up1);
   // $oid = 'ObjectId("695717ee8d9bcc741ec16bf3")';
    $set_values = ["input" => $up2];   //admin
    $update = new MongoDB\Driver\BulkWrite();
    $update->update(
        ['ket' => $up1], ['$set' => $set_values], ['multi' => false, 'upsert' => false]
    );                              
    $result = $conn->executeBulkWrite("$dbname.$collection_setting", $update);
    if ($result->getModifiedCount() == 1) { 
        sendMessage_tbot($chat_id_admin, "Record successfully updated ".$up1."=>".$up2);
    } else {  
        sendMessage_tbot($chat_id_admin, "Error while updating record ");
    }
    return false;
    }












if ($text == '/coba') {
    /////////////////////////////
   $data1 = [
            'id' => (string)$chat_id,
            'nama' => 'nama',
            'kelas' => 'kelas',
            'role' => "siswa",
            'edit' => 0,
            'delete' => 0,

            'select' => 0

            ];

      // insert_db( $data1, $chat_id, $dbname, $collection_user);
     //  delete_db("695307ff319bcab3e20910b2", $chat_id, $dbname,$collection_user);
      // update_db("69532e43fa687104a7042a82",$chat_id, $data1, $dbname,$collection_user);
     //  read_db("69532e43fa687104a7042a82",$chat_id,$dbname,$collection_user);
     //  read_all_db($chat_id,$dbname,$collection_user);
     //  count_db($chat_id,$dbname,$collection_user) ;
     //sendMessage_tbot($chat_id, $oidValue11 );
     //sendMessage_tbot($chat_id, count_db($chat_id,$dbname,$collection_user));

       
    }


 }





//  sendMessage_tbot($chat_id_admin, json_encode($update['message']['contact']['phone_number']));

// sendMessage_tbot($chat_id_admin, json_encode($update));

////////////  /daftar

 

///////////////////////////////////////////////////////
/////delete//////////////////////////////////////////////
    // $regex = '/^\d\d/';


if(preg_match('/^\d\d/', $callback_data) or preg_match('/^_/', $callback_data) or preg_match('/^#/', $callback_data) ){   
    ///delete ^00  , no1
    $chat_idq = $update['callback_query']['message']['chat']['id'];
    $message_id = $update['callback_query']['message']['message_id'];
    $botToken = BOT_TOKEN;
    $apiURL = "https://api.telegram.org/bot" . $botToken . "/";
    $deleteUrl = $apiURL . "deleteMessage?chat_id=" . $chat_idq . "&message_id=" . $message_id;
    $response = file_get_contents($deleteUrl);
    }
   
if( $callback_data == 'no1' or $callback_data == '00kontak'){   
    ///delete ^00  , no1
    $chat_idq = $update['callback_query']['message']['chat']['id'];
    $message_id = $update['callback_query']['message']['message_id'];
    $botToken = BOT_TOKEN;
    $apiURL = "https://api.telegram.org/bot" . $botToken . "/";
    $deleteUrl = $apiURL . "deleteMessage?chat_id=" . $chat_idq . "&message_id=" . $message_id;
    $response = file_get_contents($deleteUrl);
    }


// $chat_id = $update['message']['chat']['id'];
// $text = $update['message']['text'];

if($text == '/mulai' or $text == '/daftar' or preg_match('/^#/', $text) or preg_match('/^del/', $text))
        ///delete /mulai /daftar
    {                               
    $message_id = $update['message']['message_id'];
    $botToken = BOT_TOKEN;
    $apiURL = "https://api.telegram.org/bot" . $botToken . "/";
    $deleteUrl = $apiURL . "deleteMessage?chat_id=" . $chat_id. "&message_id=" . $message_id;
    $response = file_get_contents($deleteUrl);
    // sendMessage_tbot($chat_id, '$message_id' );
    }


 ////////////////end delete /////   
////////////////////////////////////////////


if ($text == "local"  ) {

$data['chat_id'] = $update['message']['chat']['id'];
$keyboard = [
    [
        ['text' => 'Share My Location', 'request_location' => true]
    ]
];
$data['reply_markup'] = json_encode([
    'keyboard' => $keyboard,
    'one_time_keyboard' => true,
    'resize_keyboard' => true
]);
$data['text'] = 'Please tap the button below to share your location.';


}

}




/////////////////////////<daftar> /////////////////////////////////////////
 if($chat_id){


// $chat_id = $update['message']['chat']['id'];
// $text = $update['message']['text'];

/////////#daftar

// sendMessage_tbot($chat_id, "Record sudah ada");

 $pecah = (explode(',',$text));
     $txt0= $pecah['0'];
     $txt1= $pecah['1'];
     $txt2= $pecah['2'];

///////////////////////////////////////////////////
if ($txt0 == $adm_new_user && $txt1 ) {
////////////////////////////////////////////////////

    // sendMessage_tbot($chat_id, "daftar");

	
        if($count2 >= 1){

        echo json_encode(

                array("message" => "Record sudah ada")
            );

    //   sendMessage_tbot($chat_id, "Record sudah ada");

        }else{

           $data1 = [
            'id' => (string)$chat_id,
            'nama' => (string)$txt1,
            'kelas' => '',
            'role' => "siswa",
            'edit' => 0,
            'delete' => 0,
            'no' => (string)$count_user+1,
            'select' => 0

            ];


        // insert record
        $insert = new MongoDB\Driver\BulkWrite();
        $insert->insert($data1);

        $result = $conn->executeBulkWrite("$dbname.$collection_user", $insert);
       // $result = $conn->executeBulkWrite("$coll", $insert);
        // verify
     if ($result->getInsertedCount() == 1) {
          
        //  sendMessage_tbot($chat_id, "Record successfully created");


          

$url_img = 'https://isekolah.my.id/myWebhook/img_reg/pilihkelas.JPG'; // Mendapatkan file_id
$caption1 = "pilih grup";
$inlineKeyboard = [
         [
                        ['text' => 'TKR', 'callback_data' => '#TKR'],
                        ['text' => 'DPIB', 'callback_data' => '#DPIB']
                        ],
                    
                        [
                        ['text' => 'TKJ', 'callback_data' => 'TKJ'],
                        ['text' => 'TITL', 'callback_data' => 'TITL']
                        ],
                       
                        [
                        ['text' => 'TPL', 'callback_data' => 'TPL'],
                        ['text' => 'ELIN', 'callback_data' => 'ELIN']
                        ],
                        
                        [
                        ['text' => 'TPM', 'callback_data' => 'TPM'],
                        ['text' => 'GEO', 'callback_data' => 'GEO']
                        ]
];
// sendMessage_tbot($chat_idq, "jno9=".$callback_data);
// sendMessage_tbot($chat_idq, "kno9=".$result3[0]['09']);
sendpoto($chat_id,$url_img,$inlineKeyboard,$caption1);
// send('sendMessage', $parameters, $botToken);  




        } else {
            echo json_encode(
                    array("message" => "Error while saving record")
            );
       sendMessage_tbot($chat_id, "Error while saving record");
        }

        
        }
}

}
/////////////////////////////
if($callback_querys){

// $callback_data = $update['callback_query']['data'];
if( $callback_data == "#TKR"){   
$chat_idq = $update['callback_query']['message']['chat']['id'];
$text2 =$callback_H;
// sendMessage_tbot($chat_idq,'jurusan '.$text2); 


$data1 = ['jurusan' => $text2];
updateidnosesi_db($chat_idq, $data1, $dbname,$collection_user);


$url_img = 'https://isekolah.my.id/myWebhook/img_reg/pilihkelas.JPG'; // Mendapatkan file_id
$caption1 = "pilih grup";
$inlineKeyboard = [
         [
            ['text' => 'X TKRA', 'callback_data' => '_X TKRA'],
            ['text' => 'X TKRB', 'callback_data' => '_XI TKRB'],
             ['text' => 'X TKRC', 'callback_data' => '_XII TKRC']
        ],
        // Second row of buttons (optional)
        // First row of buttons
        [
            ['text' => 'XI TKRA', 'callback_data' => '_X TKRA'],
            ['text' => 'XI TKRB', 'callback_data' => '_XI TKRB'],
             ['text' => 'XI TKRC', 'callback_data' => '_XII TKRC']
        ],
         // First row of buttons
        [
            ['text' => 'XII TKRA', 'callback_data' => '_X TKRA'],
            ['text' => 'XII TKRB', 'callback_data' => '_XI TKRB'],
             ['text' => 'XII TKRC', 'callback_data' => '_XII TKRC']
        ]
];
// sendMessage_tbot($chat_idq, "jno9=".$callback_data);
// sendMessage_tbot($chat_idq, "kno9=".$result3[0]['09']);
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);

/*
  $botToken = BOT_TOKEN;
$response = "Pilih Kelas:";
  $keyboard = [
    'inline_keyboard' => [
        // First row of buttons
         [
            ['text' => 'X TKRA', 'callback_data' => '_X TKRA'],
            ['text' => 'X TKRB', 'callback_data' => '_XI TKRB'],
             ['text' => 'X TKRC', 'callback_data' => '_XII TKRC']
        ],
        // Second row of buttons (optional)
        // First row of buttons
        [
            ['text' => 'XI TKRA', 'callback_data' => '_X TKRA'],
            ['text' => 'XI TKRB', 'callback_data' => '_XI TKRB'],
             ['text' => 'XI TKRC', 'callback_data' => '_XII TKRC']
        ],
         // First row of buttons
        [
            ['text' => 'XII TKRA', 'callback_data' => '_X TKRA'],
            ['text' => 'XII TKRB', 'callback_data' => '_XI TKRB'],
             ['text' => 'XII TKRC', 'callback_data' => '_XII TKRC']
        ]
    ]
];
$encodedKeyboard = json_encode($keyboard);
$parameters = array(
    'chat_id' => $chat_idq,
    'text' => $response,
    'reply_markup' => $encodedKeyboard
);
send('sendMessage', $parameters, $botToken); 
*/ 
}


if( $callback_data == "_DPIB"){   
$chat_idq = $update['callback_query']['message']['chat']['id'];

$text1 =$callback_H;
sendMessage_tbot($chat_idq,'jurusan '.$text1); 

$data1 = ['jurusan' => $text1];
updateidnosesi_db($chat_idq, $data1, $dbname,$collection_user);

  $botToken = BOT_TOKEN;
$response = "Pilih Kelas:";
  $keyboard = [
    'inline_keyboard' => [
        // First row of buttons
        [
            ['text' => 'X DPIB', 'callback_data' => '_X DPIB'],
            ['text' => 'XI BPIB', 'callback_data' => '_XI DPIB'],
             ['text' => 'XI DPIB', 'callback_data' => '_XII DPIB']
        ]
    ]
];
$encodedKeyboard = json_encode($keyboard);
$parameters = array(
    'chat_id' => $chat_idq,
    'text' => $response,
    'reply_markup' => $encodedKeyboard
);
send('sendMessage', $parameters, $botToken);  
}





if(preg_match('/^_/', $callback_data)){   
// sendMessage_tbot($chat_idq, "/if");
$text11 = trim($callback_data,"_");
// sendMessage_tbot($chat_idq,'kelas '.$text11); 

$data1 = ['kelas' => $text11];
updateidnosesi_db($chat_idq, $data1, $dbname,$collection_user);

$url_img = 'https://isekolah.my.id/myWebhook/img_reg/kontak.JPG'; // Mendapatkan file_id
$caption1 = "";
$inlineKeyboard = [
         [
            ['text' => 'Lanjut', 'callback_data' => '#0kontak']       
        ]
        
];
// sendMessage_tbot($chat_idq, "jno10=".$callback_data);
// sendMessage_tbot($chat_idq, "kno10=".$result3[0]['10']);
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
   }   //sendMessage_tbot($chat_id, $txt0."&".$txt1."&".$txt2);


if( $callback_data == '#0kontak' ){
    // sendMessage_tbot($chat_idq, "/if ".$callback_data);
 

$botToken = BOT_TOKEN;

$response = "#Klik - Kirim Kontak - untuk lanjut:";
  $keyboard = [
     'keyboard' => [
        [
            ['text' => 'Kirim Kontak', 'request_contact' => true]
        ]
    ],
    'one_time_keyboard' => true,
    'resize_keyboard' => true
];

// Encode the keyboard array into a JSON object
$encodedKeyboard = json_encode($keyboard);

// Prepare the data for the API request
$data = array(
    'chat_id' => $chat_idq,
    'text' => $response,
    'reply_markup' => $encodedKeyboard
);

    $url = "https://api.telegram.org/bot" . $botToken . "/sendMessage";
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data)
        )
    );
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    
// }

}


if (($update['message']['contact'])) {
    $chat_id = $update['message']['chat']['id'];
    sendMessage_tbot($chat_idq,'jurusan '.$update);
// sendMessage_tbot($chat_id, json_encode($update['message']['contact']['phone_number']));

 $data1 = ['nohp' => json_encode($update['message']['contact']['phone_number'])];
 updateidnosesi_db($chat_id, $data1, $dbname,$collection_user);
 sendMessage_tbot($chat_id, "Selamat berhasik terdaftar");
// sendMessage_tbot($chat_id,'no hp '.$data1); 

}


$text = 'Keyboard is now hidden.';

$remove_keyboard = json_encode([
    'remove_keyboard' => true,
    // 'selective' => true // Optional: Use "selective" to only hide for specific users in a group.
]);

 $url = "https://api.telegram.org/bot" . $botToken . "/sendMessage";

$data = [
    'chat_id' => $chat_id,
    'text' => $text,
    'reply_markup' => $remove_keyboard
];
 
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data)
        )
    );
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

















//////////////////////////end daftar//////////////////////////////////////////






// $regex = '/^data/';


// if (($update['callback_query'])) {
    $botToken = BOT_TOKEN;
    $callback_query_id = $update['callback_query']['id'];
    $callback_data = $update['callback_query']['data'];
    $chat_idq = $update['callback_query']['message']['chat']['id'];
    $message_id = $update['callback_query']['message']['message_id'];
    // sendMessage_tbot($chat_id, "berhasik kirim");
    // del_msg($chat_id,$callbackid);
//    sendMessage_tbot($chat_id, json_encode($update['callback_query']['data']));



if($callback_data == "data_A"){
$response = "Click a button below:";
$keyboard = [
    'inline_keyboard' => [
        // First row of buttons
        [
            ['text' => 'Option A1', 'callback_data' => 'data_A'],
            ['text' => 'Option B1', 'callback_data' => 'data_B'],
            ['text' => 'Option D1', 'callback_data' => 'no1']
        ],
        // Second row of buttons (optional)
        [
            ['text' => 'Visit Google1', 'url' => 'https://www.google.com'] // URL button example
        ]
    ]
];
$encodedKeyboard = json_encode($keyboard);
$parameters = array(
    'chat_id' => $chat_idq,
    'text' => $response,
    'reply_markup' => $encodedKeyboard
);
send('sendMessage', $parameters, $botToken);

}





// }
/// end callback_quer

}


///////>
if ($chat_id) {
    $chat_id = $update['message']['chat']['id'];
    $text1 = $update['message'];
    $jsonString1 = json_encode($text1);
    // sendMessage_tbot($chat_id, $jsonString1);
    $text = $update['message']['text'];
        $filter = ['id' => (string)$chat_id ];
	$option = [];
        $options = [
                'projection' => [
                '_id' => 0.0
           ]
          ];

	$read = new MongoDB\Driver\Query($filter, $options);

	//fetch records
	$records = $conn->executeQuery("$dbname.$collection_user", $read);

        echo	$res1= json_encode(iterator_to_array($records)); //echo
 	$result1= json_decode($res1, true); 
 	$count1= json_encode(count($result1)); //echo
	 $result2= json_decode($res1, true);

        $nama = $result2['0']["nama"];
        $kelas = $result2['0']["kelas"];
        $_id = $result2[0]["_id"]["$oid"];
        $edit = $result2['0']["edit"];
        $delete = $result2['0']["delete"];
        $select = $result2['0']["select"];
        $res3 = json_encode($result2['0']);

        // var_dump($result2) ;

       $jsonString = json_encode($res1);
       //  sendMessage_tbot($chat_id_admin, $jsonString);
        //sendMessage_tbot($chat_id_admin, $_id);
        //  $myObject = (object) ['oid' => '6571556e40995a947d0e4029']; // Example of creating a stdClass object
        // echo $myObject->oid;
//sendMessage_tbot($chat_id_admin, $text);

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

       sendMessage_tbot($chat_id, "Hello!Selamat Datang di isekolah bot. \nsilakan cek /cek");
    //    sendMessage_tbot($chat_id, 'Ini adalah <a href="https://www.example.com">contoh</a> link dari bot PHP!');







    }


    




if ($text == '/if') {
/////////////////////////////

$botToken = BOT_TOKEN;

$response = "Klik - Kirim Kontak - untuk lanjut:";
  $keyboard = [
     'keyboard' => [
        [
            ['text' => 'Kirim Kontak', 'request_contact' => true],
             ['text' => 'Visit Google', 'url' => 'https://isekolah.my.id/myWebhook/cetak.php?id='.$chat_id]
        ]
    ],
    'one_time_keyboard' => true,
    'resize_keyboard' => true
];

// Encode the keyboard array into a JSON object
$encodedKeyboard = json_encode($keyboard);

// Prepare the data for the API request
$parameters = array(
    'chat_id' => $chat_id,
    'text' => $response,
    'reply_markup' => $encodedKeyboard
);

send('sendMessage', $parameters, $botToken);



    }



///////////////////////////
if($text == "/cetak"){
///////////////////////////
 $botToken = BOT_TOKEN;
$response = "Click a button below:";
  $keyboard = [
    'inline_keyboard' => [
        // First row of buttons
        [
            ['text' => 'Option A', 'callback_data' => 'data_A'],
            ['text' => 'Option B', 'callback_data' => 'data_B']
        ],
        // Second row of buttons (optional)
        [
            ['text' => 'Visit Google', 'url' => 'https://isekolah.my.id/myWebhook/cetak.php?id='.$chat_id] // URL button example
        ]
    ]
];



}



function sendTelegramRequest($method, $data) {
    global $botToken;
    // Replace <YOUR_BOT_API_TOKEN> with your actual token from @BotFather
    $url = "https://api.telegram.org/bot$botToken/".$method;
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

// Data for the message and inline keyboard


// To handle button presses (callback queries), you will need a separate script 
// that processes incoming updates from Telegram and checks for 'callback_query' data.










if ($text == $adm_cetak_user) {
/////////////////////////////////
// if ($text == "/ctk") {
/////////////////////////////////
/*

$text = 'Klik link  <a href="https://isekolah.my.id/myWebhook/cetak_d.php?id='.$chat_id.'">dowload</a>';

//$text = 'Klik link  <a href="https://isekolah.my.id/myWebhook/cetak_f.php?id='.$chat_id.'">Genered</a> tampilkan  <a href="https://isekolah.my.id/myWebhook/cetak/'.$chat_id.'.pdf">Tampil</a>';
$url = "https://api.telegram.org/bot$botToken/sendMessage";

$parameters = [
    'chat_id' => $chat_id,
    'text' => $text,
    'parse_mode' => 'HTML' // Penting untuk mengaktifkan mode HTML
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo $response;

*/





 $text = 'Pili Kategori Undu atau tampilkan:';

 $inlineKeyboard = 
 [
    'inline_keyboard' => 
     [
           [
                    ['text' => 'save F ','url' => "https://isekolah.my.id/myWebhook/cetak1.php?id=".$chat_id.'&ex=F'],
                    ['text' => 'open F', 'url' => "https://isekolah.my.id/myWebhook/cetak/".$chat_id.'.pdf']
                  
           ],
               
          [
                    ['text' => 'View Or downloan I ','url' => "https://isekolah.my.id/myWebhook/cetak1.php?id=".$chat_id.'&ex=I']           
            
       
          ],
          [
                    ['text' => 'Download D ','url' => "https://isekolah.my.id/myWebhook/cetak1.php?id=".$chat_id.'&ex=D']   
           ],    
           
           [
                    ['text' => 'String S ','url' => "https://isekolah.my.id/myWebhook/cetak1.php?id=".$chat_id.'&ex=S']   
           ]     
          
  ]

     
 ];


 $parameters = [
     'chat_id' => $chat_id,
     'text' => $text,
     'reply_markup' => $inlineKeyboard // Add the inline keyboard markup
 ];


 sendTelegramRequest('sendMessage', $parameters);
 
   
 }



/////////////////////////////////
if ($text == '/cek') {
/////////////////////////////////
if($count2  >= 1)   {
    sendMessage_tbot($chat_id, "anda sudah terdaftar"); 
    sendMessage_tbot($chat_id, 'Nama ='.$nm2."\nKelas = ".$kls2."\nUsername =".$username);
    sendMessage_tbot($chat_id, $chat_id);




    
    }else{
        sendMessage_tbot($chat_id, "anda belum terdaftar"); 
    }

 }





///////////////////////////////////
if ($text == '/qr10' && $count1 == 1) {
/////////////////////////////////
        
    $url= 'temp/'.$chat_id.'.png';
    $pesan= date("Y-m-d H:i:s")."\n by : ".$nama;
    //sendMessage_tbot($chat_id, $url);
    photo_tbot($chat_id,$url,$pesan);
    }

///////////////////////////////////
if ($text == '/qr20' && $count1 == 1) {
/////////////////////////////////
        
    $url= 'logo/'.$chat_id.'.png';
    $pesan= date("Y-m-d H:i:s")."\n by : ".$nama;
    //sendMessage_tbot($chat_id, $url);
    photo_tbot($chat_id,$url,$pesan);
    }


/////////////////////////////////////////
if ($text == '/qr1' && $count1 == 1) {
///////////////////////////////////
    include "phpqrcode/qrlib.php"; 

    // nama folder tempat penyimpanan file qrcode
    $penyimpanan = "temp/";

    // membuat folder dengan nama "temp"
    if (!file_exists($penyimpanan))
    mkdir($penyimpanan);

     // isi qrcode yang ingin dibuat. akan muncul saat di scan

     $isi =  [   'id' => (string)$chat_id,
            'nama' => $nama,
            'kelas' => $kelas,
            'role' => "siswa"
            ];

     // $json2=json_decode($isi);
     // $json = json_decode($json2, true);
     $jsonString = json_encode($isi);
     $str1 = base64_decode($jsonString);
     //   echo $jsonString;
     sendMessage_tbot($chat_id, "qr code dibuat");


     /**/
     // perintah untuk membuat qrcode dan menyimpannya dalam folder temp
     // atur level pemulihan datanya dengan QR_ECLEVEL_L | QR_ECLEVEL_M | QR_ECLEVEL_Q | QR_ECLEVEL_H 
     // QRcode::png($isi, $penyimpanan.$chat_id'.'.png', QR_ECLEVEL_H);
       QRcode::png($res3, 'temp/'.$chat_id.'.png', QR_ECLEVEL_H);
     // QRcode::png($res3, $penyimpanan.'qrcodeku_H.png', QR_ECLEVEL_H, 10, 15);
    ///////////////////////
   
     sendMessage_tbot($chat_id, "qr code telah sukses dibuat");
    }



/////////////////////////////////////////
if ($text == '/qr2' && $count1 == 1) {
///////////////////////////////////
    include "phpqrcode/qrlib.php"; 
        
    $penyimpanan = "temp/";
    $logo = "logo/";

    // membuat folder dengan nama "temp"
        if (!file_exists($penyimpanan))
        mkdir($penyimpanan);
    // membuat folder dengan nama "logo"
        if (!file_exists($logo))
        mkdir($penyimpanan);



    $filepath = 'temp/'.$chat_id.'.png';
    $filelog = 'logo/'.$chat_id.'.png';

    // Image (logo) to be drawn
    $logopath = $urlpoin.'/Logo-Tut.png';
    // qr code content


    $filter3 = ['id' => (string)$chat_id ];
    $option = [];
    $options3 = [
                    'projection' => [
                    '_id' => 0.0,
                    'role' => 0.0

            ]
            ];
	$read3 = new MongoDB\Driver\Query($filter3, $options3);
	$records3 = $conn->executeQuery("$dbname.$collection_user", $read3);
    $res3= json_encode(iterator_to_array($records3)); //echo
 	$result3= json_decode($res3, true); 
 	$count3= json_encode(count($result3)); //echo
	$result3= json_decode($res3, true);
    $res30 = json_encode($result3['0']);
   $res31 = base64_encode($res30);

        // $str2 = base64_decode($str3 );         // dekresi json
        // $json = json_decode($str2, true);
        // var_dump($json) ;


        //////////////////////////////////////////////////////

        QRcode::png($res30,$filepath , QR_ECLEVEL_H, 20);

        /////////////////////////////////////////////////////////

        $QR = imagecreatefrompng($filepath);
        $logo = imagecreatefromstring(file_get_contents($logopath));

        imagecolortransparent($logo , imagecolorallocatealpha($logo , 0, 0, 0, 127));
        imagealphablending($logo , false);
        imagesavealpha($logo , true);

        $QR_width = imagesx($QR);
        $QR_height = imagesy($QR);

        $logo_width = imagesx($logo);
        $logo_height = imagesy($logo);

        // Scale logo to fit in the QR Code
        $logo_qr_width = $QR_width/3;
        $scale = $logo_width/$logo_qr_width;
        $logo_qr_height = $logo_height/$scale;

        imagecopyresampled($QR, $logo, $QR_width/3, $QR_height/3, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);

        // Save QR code again, but with logo on it
        imagepng($QR,$filelog);

        
            sendMessage_tbot($chat_id, "qr code telah sukses dibuat");



    }


 // update user   updateUser
     $pecah = (explode(',',$text));
     $txt0= $pecah['0'];
     $txt1= $pecah['1'];
     $txt2= $pecah['2'];
     //sendMessage_tbot($chat_id, $txt0."&".$txt1."&".$txt2);

//////////////////////////////////////////////////
if ($txt0 == $result_adm[0]['updateUser'] && $txt1  && $count1 == 1) {
////////////////////////////////////////////////

     //sendMessage_tbot($chat_id, "edit1");



           $data1 = [
            'id' => (string)$chat_id,
            // 'nama' => (string)$txt1,
            // 'kelas' => (string)$txt2,
            // 'role' => "siswa",
            // 'edit' => 0
            ];



        // update record
        $update = new MongoDB\Driver\BulkWrite();
        $update->update(
            // ['_id' => new MongoDB\BSON\ObjectId($id)],
            ["idu" => $txt1],
            ['$set' => $data1],
            ['multi' => false, 'upsert' => false]
        );

        $result = $conn->executeBulkWrite("$dbname.$collection_user", $update);

        // verify
        if ($result->getModifiedCount() == 1) {
            echo json_encode(
                array("message" => "Record successfully updated")
            );
        sendMessage_tbot($chat_id, "Record successfully updated");
        } else {
            echo json_encode(
                    array("message" => "Error while updating record")
            );

        sendMessage_tbot($chat_id, "Error while updating record");
       }
       }


//////////////////////////////////////////////////////////
if ($txt0 == '/del'&&  $count1 == 1) {
////////////////////////////////////////////////////////

       // delete record
        $delete = new MongoDB\Driver\BulkWrite();
        $delete->delete(
            // ['_id' => new MongoDB\BSON\ObjectId($id)],
            ["id" => (string)$chat_id,'delete' => 1],
            ['limit' => 0]
        );

        $result = $conn->executeBulkWrite("$dbname.$collection_user", $delete);

        //print_r($result);

        // verify
        if ($result->getDeletedCount() == 1) {
            echo json_encode(
                array("message" => "Record successfully deleted")
            );
        sendMessage_tbot($chat_id, "Record successfully deleted");

        } else {
            echo json_encode(
                    array("message" => "Error while deleting record")
            );
        sendMessage_tbot($chat_id, "Error while deleting record");

        }
        }


}


//end text
 $FILENAME = 'output_image.pdf'; // Replace with the actual local path to your PDF file
// $chat_id = $update['message']['chat']['id'];
// Check if the file exists
if (!file_exists($FILENAME)) {
    die("Error: File not found at " . $FILENAME);
}

// Telegram API endpoint for sendDocument method
$url = "https://api.telegram.org/bot" . $botToken . "/sendDocument";

// Create CURL object
// $ch = curl_init();

// Create CURLFile object from the local path
// realpath() is used to get the absolute path
$cFile = new CURLFile(realpath('output_image.pdf'));

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Add the document and chat_id to the POST fields array
curl_setopt($ch, CURLOPT_POSTFIELDS, [
    "chat_id" =>$chat_id,
    "document" => $cFile,
    "caption" => "Here is your PDF document." // Optional caption
]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // May be necessary depending on server config

// Execute the cURL request
$result = curl_exec($ch);

// Check for errors
if (curl_errno($ch)) {
    echo 'cURL error: ' . curl_error($ch);
} else {
    // Show the API response
    var_dump($result);
}

// Close cURL session
curl_close($ch);




////////photo//////////////////////////

if (($update['message']['photo'])) {
    $chat_id = $update['message']['chat']['id'];
    $photo1 = $update['message']['photo'][0]['file_id'];
    $photo = $update['message'];

    $jsonString = json_encode($photo);
   // sendMessage_tbot($chat_id_admin, $jsonString);

$token = "8291470736:AAHMwfbO6ABPoe3OtzRujXmaLzXJaMPphIQ";
$url = "https://api.telegram.org/bot".BOT_TOKEN."/sendPhoto";
$url1 = "https://api.telegram.org/bot8291470736:AAHMwfbO6ABPoe3OtzRujXmaLzXJaMPphIQ/sendPhoto";
$chat_id = $update['message']['chat']['id'];
$file_id = $update['message']['photo'][0]['file_id']; // Mendapatkan file_id
$caption = $update['message']['caption'];
$first_name = $update['message']['chat']['first_name'];
$last_name = $update['message']['chat']['last_name'];
$username = $update['message']['chat']['username'];
$caption1 = "user:@".$username."-fn:".$first_name."-ln:".$last_name;
// sendMessage_tbot($chat_id_admin, $caption);
//  "cap_kirm-tugas" : "kirim",
//     "cap_propil" : "propil",
//     "cap_simpan" : "simpan"
$ktugas=$result_adm[0]['cap_kirm-tugas'];

$spropil=$result_adm[0]['cap_propil'];
$simage=$result_adm[0]['cap_simpan'];



$pecah1 = (explode(',',$caption));
 $cap0= $pecah1['0'];
 $cap1= $pecah1['1'];
$cap2= $pecah1['2'];

// sendMessage_tbot($chat_id_admin, $update);

if($caption == $adm_photo_propil){
    $botToken = "8291470736:AAHMwfbO6ABPoe3OtzRujXmaLzXJaMPphIQ";
    $filePath = './profil/';

    // Check for different file types
  if (isset($update['message']['photo'])) {
        // Photos come in different sizes; get the largest one (last element in array)
        $photo_sizes = $update['message']['photo'];
        $largest_photo = end($photo_sizes);
        $file_id = $largest_photo["file_id"];
        // $file_name = $file_id . ".jpg"; // Telegram doesn't provide a filename for photos
        $file_name = $chat_id . ".jpg";

        $api_url = "https://api.telegram.org/bot{$botToken}/getFile?file_id={$file_id}";
        $file_info_json = file_get_contents($api_url);
        $file_info = json_decode($file_info_json, TRUE);

        $telegram_file_path = $file_info["result"]["file_path"];

            $download_url = "https://api.telegram.org/file/bot{$botToken}/{$telegram_file_path}";
            $local_save_path = $filePath . $file_name;

            // Ensure the download directory exists
            if (!is_dir($filePath)) {
                mkdir($filePath, 0755, true);
            }

            file_put_contents($local_save_path, file_get_contents($download_url));
            
            $confirmation_text = "File '$file_name' saved successfully.";
            sendMessage_tbot($chat_id, $confirmation_text);
        }
   
}


if($caption == $adm_photo_simpan){

   $botToken = "8291470736:AAHMwfbO6ABPoe3OtzRujXmaLzXJaMPphIQ";
    $filePath = './download/';

    // Check for different file types
  if (isset($update['message']['photo'])) {
        // Photos come in different sizes; get the largest one (last element in array)
        $photo_sizes = $update['message']['photo'];
        $largest_photo = end($photo_sizes);
        $file_id = $largest_photo["file_id"];
        // $file_name = $file_id . ".jpg"; // Telegram doesn't provide a filename for photos
        $file_name = uniqid() . ".jpg";

        $api_url = "https://api.telegram.org/bot{$botToken}/getFile?file_id={$file_id}";
        $file_info_json = file_get_contents($api_url);
        $file_info = json_decode($file_info_json, TRUE);

        $telegram_file_path = $file_info["result"]["file_path"];

            $download_url = "https://api.telegram.org/file/bot{$botToken}/{$telegram_file_path}";
            $local_save_path = $filePath . $file_name;

            // Ensure the download directory exists
            if (!is_dir($filePath)) {
                mkdir($filePath, 0755, true);
            }

            file_put_contents($local_save_path, file_get_contents($download_url));
            
            $confirmation_text = "File '$file_name' saved successfully.";
            sendMessage_tbot($chat_id, $confirmation_text);
        }
   
}









//if($caption == $spropil){

/*



    $message = $update["message"];
    $filePath = './download/';
    $file_name = "downloaded_file"; // Default filename

    // Check for different file types
    if (isset($message["document"])) {
        $file_id = $message["document"]["file_id"];
        $file_name = $message["document"]["file_name"];
    } elseif (isset($message["photo"])) {
        // Photos come in different sizes; get the largest one (last element in array)
        $photo_sizes = $message["photo"];
        $largest_photo = end($photo_sizes);
        $file_id = $largest_photo["file_id"];
        // $file_name = $file_id . ".jpg"; // Telegram doesn't provide a filename for photos
        $file_name = uniqid() . ".jpg";
        // file_get_contents("https://api.telegram.org/bot{$botToken}/sendMessage?chat_id=".$update['message']['chat']['id']."&text=".json_encode($file_id)."");
    } elseif (isset($message["audio"])) {
        $file_id = $message["audio"]["file_id"];
        $file_name = $message["audio"]["file_name"] ?? $file_id . ".mp3";
    } elseif (isset($message["video"])) {
        $file_id = $message["video"]["file_id"];
        $file_name = $message["video"]["file_name"] ?? $file_id . ".mp4";
    }


    if ($file_id) {

         $api_url = "https://api.telegram.org/bot{$botToken}/getFile?file_id={$file_id}";
        $file_info_json = file_get_contents($api_url);
        $file_info = json_decode($file_info_json, TRUE);

        if (isset($file_info["result"]["file_path"])) {

            $telegram_file_path = $file_info["result"]["file_path"];
            

            $download_url = "https://api.telegram.org/file/bot{$botToken}/{$telegram_file_path}";
            $local_save_path = $filePath . $file_name;

            // Ensure the download directory exists
            if (!is_dir($filePath)) {
                mkdir($filePath, 0755, true);
            }

            // Use cURL or file_get_contents to download and save the file
            file_put_contents($local_save_path, file_get_contents($download_url));
            
            // Optional: Send a confirmation message back to the user
            $chat_id = $message["chat"]["id"];
            $confirmation_text = "File '$file_name' saved successfully.";
            $send_message_url = "api.telegram.org" . urlencode($confirmation_text);
            file_get_contents($send_message_url);
            file_get_contents("https://api.telegram.org/bot{$botToken}/sendMessage?chat_id={$chat_id}&text={$confirmation_text }");

        }
    }
// }







if($caption == $simage){
$file_id = $update['message']['photo'][0]['file_id'];
$chat_id = $update['message']['chat']['id'];

$botToken = "8291470736:AAHMwfbO6ABPoe3OtzRujXmaLzXJaMPphIQ";
$apiURL = "api.telegram.org";
$filePathPrefix = "api.telegram.org";
$uploadDirectory = __DIR__ . '/images/'; // Directory to save images

// Ensure the upload directory exists and is writable
if (!is_dir($uploadDirectory)) {
    mkdir($uploadDirectory, 0755, true);
}

// Receive the webhook data from Telegram
$update = json_decode(file_get_contents("php://input"), TRUE);

if (isset($update['message']['photo'])) {

    // sendMessage_tbot($chat_id, "yhyuyiyu");
    // Get the photo array (the last element is the highest quality)
    $photoArray = $update['message']['photo'];
    $highestQualityPhoto = end($photoArray);
    $fileId = $highestQualityPhoto['file_id'];


    

    // 1. Get the file path using the getFile method
    // $getFileUrl = $apiURL . "getFile?file_id=" . $fileId;
    $getFileUrl = "https://api.telegram.org/bot".$botToken."/getFile?file_id=" . $file_id;
    $fileResponse = json_decode(file_get_contents($getFileUrl), TRUE);

    if ($fileResponse['ok']) {
       
        $filePath = $fileResponse['result']['file_path'];
        $downloadUrl = $filePathPrefix . $filePath;
         $chat_Id = $update['message']['chat']['id'];
         sendMessage_tbot($chat_id, json_encode($downloadUrl));
        // Determine file extension and name
        $extension = pathinfo($filePath, PATHINFO_EXTENSION);
         $fileName = $chat_Id .'.'.uniqid() . '.jpg';
        // $fileName = $chat_Id . '.jpg';
        $savePath = $uploadDirectory . $fileName;

        // 2. Download the file from Telegram servers to your cPanel
        $ch = curl_init($downloadUrl);
        $fp = fopen($savePath, 'wb');
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_exec($ch);
        curl_close($ch);
        fclose($fp);

        // Optional: Send a confirmation message back to the user
        $chatId = $update['message']['chat']['id'];
        file_get_contents($apiURL . "sendMessage?chat_id=$chatId&text=" . urlencode("Image saved as $fileName"));
         sendMessage_tbot($chat_id, "Berhasil terkirim !");
    }
}
}
*/


///////////////////////////
if($caption == $adm_photo_tugas){
///////////////////////////

   $curl = curl_init();
   curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => array('chat_id' => $chat_id_admin,'photo' => $file_id,'caption' => $caption1),
   ));

   $response = curl_exec($curl);

   curl_close($curl);
   echo $response;
    sendMessage_tbot($chat_id, "Berhasil terkirim !");
   }
   //sendMessage_tbot($chat_id, $caption."&".$cap0."&".$cap1."&".$cap2);

/////////////////////////////////
if($cap0 == "kirim" && $cap1 ){
/////////////////////////////////

        $filter = ['select' => 1];
	$option = [];
	$read = new MongoDB\Driver\Query($filter, $option);

	//fetch records
	$records = $conn->executeQuery("$dbname.$collection_user", $read);

	$res1= json_encode(iterator_to_array($records)); //echo
        //echo $_id = $res1->["_id"];  
        $result1= json_decode($res1, true); 
 	$count1= json_encode(count($result1)); //echo
	 $result2= json_decode($res1, true);

        foreach ($result2 as $document) {
        // echo $document['id'] . "\n";
       //sendMessage_tbot($chat_id, $document['id']);

       pht($document['id'],$file_id,$cap1,$chat_id,);

        }
      //   }else{
       //      sendMessage_tbot($chat_id, "tdk terkirim");

          }
 }
 
 
 

?>
