<?php
define('BOT_TOKEN', '8291470736:AAHMwfbO6ABPoe3OtzRujXmaLzXJaMPphIQ'); // Replace with your actual bot token
define('WEBHOOK_URL', 'https://isekolah.my.id/myWebhook/myWebhook.php'); // Replace with your HTTPS URL


///////////////////////////////////////////////////////////////////////////////////////////
$api_url = 'https://api.telegram.org/bot' . BOT_TOKEN . '/setWebhook?url=' . WEBHOOK_URL;
$response = file_get_contents($api_url);

if ($response) {
    echo "Webhook successfully set up!";
} else {
    echo "Failed to set up webhook.";
}

// date_default_timezone_set('Asia/Makassar'); 



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");
$urlsoal = "https://isekolah.my.id/myWebhook/soal/";
$urlreg = "https://isekolah.my.id/myWebhook/img_reg/";
$urlpoin= 'https://isekolah.my.id/myWebhook';
$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 = $update['message']['chat']['id'];
$chatcq_id = $update['callback_query']['message']['chat']['id'];
$username = $update['message']['chat']['username'];

date_default_timezone_set('UTC+9');
$mongoDateTime = new MongoDB\BSON\UTCDateTime();
$millisecondsString = (string)$mongoDateTime;

$timestamp_detik = $millisecondsString / 1000;

// 3. Tambahkan 1 jam menggunakan strtotime (menambahkan 3600 detik)
$timestamp_plus_1_jam = strtotime('-4 hour', $timestamp_detik);
$millisecondsString1=$timestamp_plus_1_jam*1000;
// 4. Format hasilnya (misal: Y-m-d H:i:s)


$tanggal_baru = date('Y-m-d H:i:s', $timestamp_plus_1_jam);
//sendMessage($chat_id,  $millisecondsString1);
//sendMessage($chat_id,  $tanggal_baru);
$text = $update['message']['text'];
// include database file
$date = new DateTime('now', new DateTimeZone('UTC'));
// Wrap it in a MongoDB\BSON\UTCDateTime object
$mongoDate = new MongoDB\BSON\UTCDateTime($date);
//  sendMessage($chat_id, json_encode($update));
/////////////////////////////////


$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']:"";








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

    $filter1 = ['id' => (string)$chat_id_admin,];
	//$options = ['projection' => ['_id' => 0.0]];
    $options1 = ['projection' => []];
	$read1 = new MongoDB\Driver\Query($filter1, $options1);
	$records1 = $conn->executeQuery("$dbname.$collection_user", $read1);
 	$res1= json_encode(iterator_to_array($records1)); //echo  
    $result1= json_decode($res1, true); 
    

    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($chat_id, $jsonString_adm[0]['soal']);
// echo var_dump($adm_soal[0]["idData"] );

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'];  
}




// $filter2 = [];
//      $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






    $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($chat_id, 'oid user='.$oidValue2 );
//sendMessage($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($chat_id, $nama );
//sendMessage($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($chat_id, 'sesi4='.$sesi4 );
//   sendMessage($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($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($chatcq_id,  json_encode($update['callback_query']));
    //sendMessage($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($chatcq_id,  $jsonString5);
    // sendMessage($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($chatcq_id,  $jsonString51);
    // sendMessage($chatcq_id, 'sesi51='.$sesi51 );


     $oidValue51= $result51[0]['_id']['$oid'];  //51)695132ce517b3df17e1e0c73d2
     $user51= $result51[0]['user']; 
     //    $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
     $skor51 = $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


    }
      //////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////////////////////////
$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($chatcq_id,  $jsonString41);
     
        $mysesi = $sesi4;
      
        $mysesi = $sesi5;
      
      
//sendMessage($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($chat_id, $file_path);
//     // Proceed to the next step with $file_path
// }

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





















 function insert_dt() {
        
    global $conn, $dbname, $chat_id,$nm2, $kls2,$text ,$collection_soal,$mysesi, $chatcq_id,$json_soal_pel;


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

    $data1 = ['id' => (string)$chatcq_id,
                'nama' => $nm2,
                'kelas' => $kls2, 
            'user' => $_txt1,
             'pel' => $json_soal_pel,
            'sesi' => (string)$mysesi
    ];

    sendMessage($chatcq_id, json_encode($data1));
    $insert = new MongoDB\Driver\BulkWrite();
    $insert->insert($data1);

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

    // verify
    if ($result->getInsertedCount() == 1) {
        echo json_encode(
            array("message" => "Record successfully created")
        );
       
         sendMessage($chat_id, "Record successfully created");
    } else {
        echo json_encode(
                array("message" => "Error while saving record")
        );
         sendMessage($chat_id, "Error while saving record");
    }

}

echo $pel= $jsonData['soal']['pelajaran'];

function inserts_dt() {
        
    global $conn, $dbname, $chat_id,$nm2, $kls2,$text ,$collection_soal,$sesi4,$mongoDate, $pel,$adm_Grup_soal;


    $pecah = (explode(',',$text));
        $_txt1= $pecah['1'];


    $data1 = [  'id' => (string)$chat_id,
                'nama' => $nm2,
                'kelas' => $kls2, 
                'user' => $_txt1,
                 'pel' => $pel,
                'sesi' => (string)($sesi4+1),
              'Gsoal' =>  $adm_Grup_soal
    ];

    //sendMessage($chat_id, json_encode($data1));
    $insert = new MongoDB\Driver\BulkWrite();
    $insert->insert($data1);
    $result = $conn->executeBulkWrite("$dbname.$collection_soal", $insert);

    // verify
    if ($result->getInsertedCount() == 1) {
        echo json_encode(
            array("message" => "Record successfully created")
        );
       
        // sendMessage($chat_id, "Record successfully created");
    } else {
        echo json_encode(
                array("message" => "Error while saving record")
        );
       //  sendMessage($chat_id, "Error while saving record");
    }

}



////////////////////////////////////////soal/////////////////////////////////////////sendMessage($chat_id, 'oid soalr='//.$oidValue3 );
   $callback_data = $update['callback_query']['data'];
$chat_idq = $update['callback_query']['message']['chat']['id'];
$message_id = $update['callback_query']['message']['message_id'];

$pecah = (explode(',',$text));
     $_txt0= $pecah['0'];
     $_txt1= $pecah['1'];
     $txt2= $pecah['2'];
//sendMessage($chat_id, $_txt0.$_txt1 );


if ($_txt0 == $adm_mulai_soal and ($count4 >= $result3[0]['kali'])) {
  inserts_dt();
    // sendMessage($chat_id, 'mulai sesi '.$sesi);
   //sendMessage($chat_id, $_txt0.$_txt1 );
/////////////////////////////
        //sendMessage($chat_id, "Hello!Selamat Datang to your bot.");
        $url_img = $urlsoal.$jsonData['img']['mulai']; // Mendapatkan file_id
        //$chat_id = $update['message']['chat']['id'];
        $caption1 = "Mata Pelajaran : ".$jsonData['soal']['pelajaran'];
        $inlineKeyboard = [
                [
                    ['text' => 'Mulai', 'callback_data' => 'no1']
                    
                ],
                // Second row of buttons (optional)
                [
                    ['text' => 'Petunjuk', 'url' => 'https://www.google.com'] // URL button example
                ] 
        ];
        sendpoto($chat_id,$url_img,$inlineKeyboard,$caption1);
        }



if(preg_match('/^no1/', $callback_data ) ){  
      sendMessage($chatcq_id, 'mulai sesi '.$sesi5 );
//insert_dt();
$url_img = $urlsoal.$jsonData['img']['1']; // Mendapatkan file_id
$caption1 = $jsonData['ket']['1'];;
$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']
        ] 
];

//if( $count4 <= $result3[0]['kali']){
    
     //   }
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
// //sendMessage($chat_idq, 'sesi='.$sesi5);
 // insert_dt() ;


// }
}



if(preg_match('/^01/', $callback_data)){  
$url_img = $urlsoal.$jsonData['img']['2']; // Mendapatkan file_id
$caption1 = $jsonData['ket']['2'];;
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => '02a'],
            ['text' => 'D BENAR', 'callback_data' => '02d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => '02b'],
            ['text' => 'E BENAR', 'callback_data' => '02e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => '02c'],
            ['text' => 'Semua Salah', 'callback_data' => '02s']
        ] 
];
// sendMessage($chat_idq, $chat_idq);
// sendMessage($chat_idq, "jno1=".$callback_data);
// sendMessage($chat_idq, "kno1=".$result3[0]['01']);
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);

//if($callback_data == $result3[0]['01']){
if($callback_data == $jsonData['jawab']['01']){
 $jsonData['jawab']['1'];
$data1 = ['01' => 1,'created_at' => $millisecondsString1];
sendMessage($chat_idq, 'benar');
}else{
$data1 = ['01' => 0,'created_at' => $millisecondsString1]; 
sendMessage($chat_idq, 'salah');
}

//sendMessage($chat_idq, 'sesi='.$sesi5);

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

}

if(preg_match('/^02/', $callback_data)){   
$url_img = $urlsoal.$jsonData['img']['3']; // Mendapatkan file_id
$caption1 = $jsonData['ket']['3'];;
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => '03a'],
            ['text' => 'D BENAR', 'callback_data' => '03d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => '03b'],
            ['text' => 'E BENAR', 'callback_data' => '03e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => '03c'],
            ['text' => 'Semua Salah', 'callback_data' => '03s']
        ] 
];
// sendMessage($chat_idq, "jno2=".$callback_data);
// sendMessage($chat_idq, "kno2=".$result3[0]['02']);
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
//if($callback_data == $result3[0]['02']){
    if($callback_data == $jsonData['jawab']['02']){
$data1 = ['02' => 1];
sendMessage($chat_idq, 'benar');
}else{
$data1 = ['02' => 0]; 
sendMessage($chat_idq, 'salah');
}
//sendMessage($chat_idq, 'sesi'.$sesi5);
 updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
}


if(preg_match('/^03/', $callback_data)){  
$url_img = $urlsoal.$jsonData['img']['4']; // Mendapatkan file_id
$caption1 = $jsonData['ket']['4'];;
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => '04a'],
            ['text' => 'D BENAR', 'callback_data' => '04d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => '04b'],
            ['text' => 'E BENAR', 'callback_data' => '04e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => '04c'],
            ['text' => 'Semua Salah', 'callback_data' => '04s']
        ] 
];
// sendMessage($chat_idq, "jno3=".$callback_data);
// sendMessage($chat_idq, "kno3=".$result3[0]['03']);
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
 //if($callback_data == $result3[0]['03']){
     if($callback_data == $jsonData['jawab']['03']){
$data1 = ['03' => 1];
sendMessage($chat_idq, 'benar');
}else{
$data1 = ['03' => 0]; 
sendMessage($chat_idq, 'salah');
}
//sendMessage($chat_idq, 'sesi='.$sesi5);
 updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
}


if(preg_match('/^04/', $callback_data)){   
$url_img = $urlsoal.$jsonData['img']['5']; // Mendapatkan file_id
$caption1 = $jsonData['ket']['5'];;
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => '05a'],
            ['text' => 'D BENAR', 'callback_data' => '05d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => '05b'],
            ['text' => 'E BENAR', 'callback_data' => '05e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => '05c'],
            ['text' => 'Semua Salah', 'callback_data' => '05s']
        ] 
];
// sendMessage($chat_idq, "jno4=".$callback_data);
// sendMessage($chat_idq, "kno4=".$result3[0]['04']);
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
//if($callback_data == $result3[0]['04']){
    if($callback_data == $jsonData['jawab']['04']){
$data1 = ['04' => 1];
sendMessage($chat_idq, 'benar');
}else{
$data1 = ['04' => 0]; 
sendMessage($chat_idq, 'salah');
}
//sendMessage($chat_idq, 'sesi='.$sesi5);
 updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
}


if(preg_match('/^05/', $callback_data)){   
$url_img = $urlsoal.$jsonData['img']['6']; // Mendapatkan file_id
$caption1 = $jsonData['ket']['6'];;
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => '06a'],
            ['text' => 'D BENAR', 'callback_data' => '06d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => '06b'],
            ['text' => 'E BENAR', 'callback_data' => '06e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => '06c'],
            ['text' => 'Semua Salah', 'callback_data' => '06s']
        ] 
];
// sendMessage($chat_idq, "jno5=".$callback_data);
// sendMessage($chat_idq, "kno5=".$result3[0]['05']);
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
//if($callback_data == $result3[0]['05']){
    if($callback_data == $jsonData['jawab']['05']){
$data1 = ['05' => 1];
sendMessage($chat_idq, 'benar');
}else{
$data1 = ['05' => 0]; 
sendMessage($chat_idq, 'salah');
}
//sendMessage($chat_idq, 'sesi='.$sesi5);
updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
}

if(preg_match('/^06/', $callback_data)){   
$url_img = $urlsoal.$jsonData['img']['7']; // Mendapatkan file_id
$caption1 = $jsonData['ket']['7'];;
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => '07a'],
            ['text' => 'D BENAR', 'callback_data' => '07d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => '07b'],
            ['text' => 'E BENAR', 'callback_data' => '07e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => '07c'],
            ['text' => 'Semua Salah', 'callback_data' => '07s']
        ] 
];
// sendMessage($chat_idq, "jno6=".$callback_data);
// sendMessage($chat_idq, "kno6=".$result3[0]['06']);
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
//if($callback_data == $result3[0]['06']){
   if($callback_data == $jsonData['jawab']['06']){ 
$data1 = ['06' => 1];
sendMessage($chat_idq, 'benar');
}else{
$data1 = ['06' => 0]; 
sendMessage($chat_idq, 'salah');
}
//sendMessage($chat_idq, 'sesi='.$sesi5);
updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
}

if(preg_match('/^07/', $callback_data)){   
$url_img = $urlsoal.$jsonData['img']['8']; // Mendapatkan file_id
$caption1 = $jsonData['ket']['8'];;
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => '08a'],
            ['text' => 'D BENAR', 'callback_data' => '08d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => '08b'],
            ['text' => 'E BENAR', 'callback_data' => '08e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => '08c'],
            ['text' => 'Semua Salah', 'callback_data' => '08s']
        ] 
];
// sendMessage($chat_idq, "jno7=".$callback_data);
// sendMessage($chat_idq, "kno7=".$result3[0]['07']);
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
//if($callback_data == $result3[0]['07']){
    if($callback_data == $jsonData['jawab']['07']){
$data1 = ['07' => 1];
sendMessage($chat_idq, 'benar');
}else{
$data1 = ['07' => 0]; 
sendMessage($chat_idq, 'salah');
}
//sendMessage($chat_idq, 'sesi='.$sesi5);
updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
}


if(preg_match('/^08/', $callback_data)){   
$url_img = $urlsoal.$jsonData['img']['9']; // Mendapatkan file_id
$caption1 = $jsonData['ket']['9'];;
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => '09a'],
            ['text' => 'D BENAR', 'callback_data' => '09d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => '09b'],
            ['text' => 'E BENAR', 'callback_data' => '09e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => '09c'],
            ['text' => 'Semua Salah', 'callback_data' => '09s']
        ] 
];
// sendMessage($chat_idq, "jno8=".$callback_data);
// sendMessage($chat_idq, "kno8=".$result3[0]['08']);
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
//if($callback_data == $result3[0]['08']){
    if($callback_data == $jsonData['jawab']['08']){
$data1 = ['08' => 1];
sendMessage($chat_idq, 'benar');
}else{
$data1 = ['08' => 0]; 
sendMessage($chat_idq, 'salah');
}
//sendMessage($chat_idq, 'sesi='.$sesi5);
updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
}

if(preg_match('/^09/', $callback_data)){   
$url_img = $urlsoal.$jsonData['img']['10']; // Mendapatkan file_id
$caption1 = $jsonData['ket']['10'];;
$inlineKeyboard = [
         [
            ['text' => 'A BENAR', 'callback_data' => '10a'],
            ['text' => 'D BENAR', 'callback_data' => '10d']         
        ],
        [
            ['text' => 'B BENAR', 'callback_data' => '10b'],
            ['text' => 'E BENAR', 'callback_data' => '10e']
        ],
        [
            ['text' => 'C BENAR', 'callback_data' => '10c'],
            ['text' => 'Semua Salah', 'callback_data' => '10s']
        ] 
];
// sendMessage($chat_idq, "jno9=".$callback_data);
// sendMessage($chat_idq, "kno9=".$result3[0]['09']);
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
//if($callback_data == $result3[0]['09']){
   if($callback_data == $jsonData['jawab']['09']){ 
$data1 = ['09' => 1];
sendMessage($chat_idq, 'benar');
}else{
$data1 = ['09' => 0]; 
sendMessage($chat_idq, 'salah');
}
//sendMessage($chat_idq, 'sesi='.$sesi5);
 updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
}


if(preg_match('/^10/', $callback_data)){   
$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']       
        ]
        
];
// sendMessage($chat_idq, "jno10=".$callback_data);
// sendMessage($chat_idq, "kno10=".$result3[0]['10']);
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
// sendMessage($chat_idq, "no10=".$callback_data );
//if($callback_data == $result3[0]['10']){
    if($callback_data == $jsonData['jawab']['10']){
$data1 = ['10' => 1,'end_at' => $millisecondsString1];
sendMessage($chat_idq, 'benar');
}else{
$data1 = ['10' => 0,'end_at' => $millisecondsString1]; 
sendMessage($chat_idq, 'salah');
}
//sendMessage($chat_idq, 'sesi='.$sesi5);
 updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
}

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

    $data1 = ['skor' => $skor51]; 
updateid_db($chat_idq, $data1, $dbname,$collection_soal,$sesi5);
sendMessage($chat_idq, 'selesai sesi '.$sesi5.  ' , User : '.$user51);



$created_at = $result51[0]['created_at'];
$end_at= $result51[0]['end_at'];
//sendMessage( $chat_id, $created_at);
//sendMessage( $chat_id, $end_at);
$ltime= $end_at-$created_at;
//sendMessage( $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( $chat_idq, "Waktu: " . $timeFormat);
 sendMessage( $chat_idq, "Waktu mengerjakan : " . $minutes." menit, ".$seconds." detik");
  $data1 = ['wkerja' => $skor51]; 
updateid_db($chat_idq, $data1, $dbname,$collection_soal,$minutes." menit, ".$seconds." detik");



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

$utcDateTime = new MongoDB\BSON\UTCDateTime($created_at);
$dateTime = $utcDateTime->toDateTime();
// sendMessage( $chat_idq, 'mulai = '.$dateTime->format('Y-m-d H:i:s') );


$utcDateTime1 = new MongoDB\BSON\UTCDateTime($end_at);
$dateTime1 = $utcDateTime1->toDateTime();
// sendMessage( $chat_idq, 'selesai = '.$dateTime1->format('Y-m-d H:i:s') );










}///soal
/*
// sendMessage( $chat_id, json_encode($result41[0]['created_at']));
  sendMessage($chat_id, json_encode($result41) );
 // Example object, e.g., retrieved from DB

// Cast the object to a string
$created_at = $result41[0]['created_at'];
$end_at= $result41[0]['end_at'];
sendMessage( $chat_id, $created_at);
sendMessage( $chat_id, $end_at);
$ltime= $end_at-$created_at;
sendMessage( $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( $chat_id, "Waktu: " . $timeFormat);
//sendMessage( $c




*/

/*
$created_at = $result41[0]['created_at'];
$end_at= $result41[0]['end_at'];

// Misalkan ini adalah timestamp milidetik yang Anda dapatkan dari MongoDB
// $millisFromMongoDB = $end_time; // Contoh: 1 Januari 2025 00:00:00 UTC
sendMessage( $chat_id, $millisecondsString1 );
// 2. Buat objek MongoDB\BSON\UTCDateTime
$utcDateTime = new MongoDB\BSON\UTCDateTime($created_at);
// 3. Konversi ke objek PHP DateTime
$dateTime = $utcDateTime->toDateTime();
// 4. Format output (opsional, untuk melihat hasilnya)
echo "Objek DateTime (WIB): " . $dateTime->format('Y-m-d H:i:s') . "\n"; // Akan menampilkan waktu Makassar

sendMessage( $chat_id, $dateTime->format('Y-m-d H:i:s') );


$utcDateTime1 = new MongoDB\BSON\UTCDateTime($end_at);
// 3. Konversi ke objek PHP DateTime
$dateTime1 = $utcDateTime1->toDateTime();
// 4. Format output (opsional, untuk melihat hasilnya)
echo "Objek DateTime (WIB): " . $dateTime1->format('Y-m-d H:i:s') . "\n"; // Akan menampilkan waktu Makassar

sendMessage( $chat_id, $dateTime1->format('Y-m-d H:i:s') );

*/




/*

$formatted_date = date('Y-m-d H:i:s', $milliseconds);
sendMessage( $chat_id, $formatted_date );


$start_time =json_encode($result4[0]['created_at']['$date']['$numberLong']);
$end_time= json_encode($result4[0]['end_at']['$date']['$numberLong']);

$start_time1 = trim($start_time,'"');
$end_time1 = trim($end_time,'"');

//$text1 = trim($callback_data,"_");
/////////////////////////////////////////////////////////////////
sendMessage( $chat_id, 'waktu start ='.$start_time1.'-'.$end_time1);
sendMessage( $chat_id, $end_time1 - $start_time1);


$milliseconds1 = $end_time1; // Contoh milidetik (123 milidetik)
$seconds1 = $milliseconds1 / 1000; // Konversi ke detik (float)

// Menggunakan date() untuk tanggal dan waktu dasar
// $formatted_date = date('Y-m-d H:i:s', $milliseconds);
// $formatted_date1 = date('Y-m-d H:i:s', $start_time1/1000);
// echo $formatted_date; // Output: 2023-03-15 08:00:00 (tergantung zona waktu)
// sendMessage( $chat_id, $formatted_date );
//sendMessage( $chat_id, $formatted_date1 );
//sendMessage( $chat_id, $formatted_date1 - $formatted_date);
$fin=$end_time1 - $start_time1;
$milliseconds = $end_time1;// Contoh: 1234567 milidetik
// sendMessage( $chat_id, $end_time1);
// sendMessage( $chat_id, $start_time1);
// Konversi milidetik ke detik
$seconds = round($milliseconds / 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( $chat_id, "Waktu: " . $timeFormat);
sendMessage( $chat_id, "Waktu: " . $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]);

    sendMessage($chat_id, 'user ='.$result_sk[0]['user']."\nJumlah Benar = ".$result_sk[0]['skor']."\nMata Pelajaran = ".$result_sk[0]['pel']."\ngrup Test = ".$result_sk[0]['Gsoal'] );
   }







     $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($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($chat_id, $newString );
   
    }


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

if ($use0 == '?user'  and  $use1 and $use2) {
    sendMessage($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($chat_id, "Record successfully deleted");
    } else {
    echo json_encode(
            array("message" => "Error while deleting record")
    );
    sendMessage($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($chat_id, "Record successfully updated keterangan");
        } 


        return false;

        }


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

    sendMessage($chat_id_admin, "update ket = ".$adm_input_ket.",2045357439,<isi ket>,".$inputKet." \ndataku = $adm_info_user\ngup soal = ". $adm_Grup_soal);
    sendMessage($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($chat_id_admin, $jsonString_adm ."\nmyupdate,<idData>,<input>"); 

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

if ($up0 == 'myupdate' and $up1 and $up2 ) {   //admin
    // sendMessage($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($chat_id_admin, "Record successfully updated Gsoal");
    } else {  
        sendMessage($chat_id_admin, "Error while updating record Gsoal");
    }
    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($chat_id, $oidValue11 );
     //sendMessage($chat_id, count_db($chat_id,$dbname,$collection_user));

       
    }









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

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

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

 

///////////////////////////////////////////////////////
/////delete//////////////////////////////////////////////
    // $regex = '/^\d\d/';
$callback_data = $update['callback_query']['data'];

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($chat_id, '$message_id' );
    }


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

$text = $update['message']['text'];
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> /////////////////////////////////////////

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

/////////#daftar

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

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

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

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

	
        if($count2 >= 1){

        echo json_encode(

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

    //   sendMessage($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($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($chat_idq, "jno9=".$callback_data);
// sendMessage($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($chat_id, "Error while saving record");
        }

        
        }
}



$callback_data = $update['callback_query']['data'];
if( $callback_data == "#TKR"){   
$chat_idq = $update['callback_query']['message']['chat']['id'];
$text2 = trim($callback_data,"#");
// sendMessage($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($chat_idq, "jno9=".$callback_data);
// sendMessage($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 = trim($callback_data,"#");
sendMessage($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($chat_idq, "/if");
$text11 = trim($callback_data,"_");
// sendMessage($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($chat_idq, "jno10=".$callback_data);
// sendMessage($chat_idq, "kno10=".$result3[0]['10']);
sendpoto($chat_idq,$url_img,$inlineKeyboard,$caption1);
   }   //sendMessage($chat_id, $txt0."&".$txt1."&".$txt2);


if( $callback_data == '#0kontak' ){
    // sendMessage($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($chat_idq,'jurusan '.$update);
// sendMessage($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($chat_id, "Selamat berhasik terdaftar");
// sendMessage($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($chat_id, "berhasik kirim");
    // del_msg($chat_id,$callbackid);
//    sendMessage($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 (($update['message']['text'])) {
    $chat_id = $update['message']['chat']['id'];
    $text1 = $update['message'];
    $jsonString1 = json_encode($text1);
    // sendMessage($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($chat_id_admin, $jsonString);
        //sendMessage($chat_id_admin, $_id);
        //  $myObject = (object) ['oid' => '6571556e40995a947d0e4029']; // Example of creating a stdClass object
        // echo $myObject->oid;
//sendMessage($chat_id_admin, $text);

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

       sendMessage($chat_id, "Hello!Selamat Datang di isekolah bot. \nsilakan cek /cek");
    //    sendMessage($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($chat_id, "anda sudah terdaftar"); 
    sendMessage($chat_id, 'Nama ='.$nm2."\nKelas = ".$kls2."\nUsername =".$username);
    sendMessage($chat_id, $chat_id);




    
    }else{
        sendMessage($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($chat_id, $url);
    photo($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($chat_id, $url);
    photo($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($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($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($chat_id, "qr code telah sukses dibuat");



    }


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

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

     //sendMessage($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($chat_id, "Record successfully updated");
        } else {
            echo json_encode(
                    array("message" => "Error while updating record")
            );

        sendMessage($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($chat_id, "Record successfully deleted");

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

        }
        }


}


//end text
CONST 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($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($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($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($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($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($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($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($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($chat_id, "Berhasil terkirim !");
   }
   //sendMessage($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($chat_id, $document['id']);

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

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

          }
 }
 
 
 
 // end photo







function sendpoto($chat_id,$url_img,$inlineKeyboard,$caption1) {

$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' => $url_img,'caption' => $caption1,'reply_markup' =>$replyMarkupInline ),
   ));

   $response = curl_exec($curl);

   curl_close($curl);
   //echo $response;
    //sendMessage($chat_id, "Berhasil terkirim !");
   }













function sendMessage($chat_id, $text) {
    $url = 'https://api.telegram.org/bot' . BOT_TOKEN . '/sendMessage';
    $data = [
        'chat_id' => $chat_id,
        'text' => $text,
    ];

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


function pht($chat_id,$file_id,$pesan,$chatid) {

$token = "8291470736:AAHMwfbO6ABPoe3OtzRujXmaLzXJaMPphIQ";
$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' => $file_id,'caption' => $pesan),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
sendMessage($chatid, "Berhasil terkirim ! ke -".$chat_id);

}


function photo($chat_id,$file_id,$pesan) {

$token = "8291470736:AAHMwfbO6ABPoe3OtzRujXmaLzXJaMPphIQ";
$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($file_id),'caption' => $pesan),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
//sendMessage($chatid, "Berhasil terkirim ! ke -".$chat_id);

}



info();




function info() {
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.telegram.org/bot' . BOT_TOKEN . '/getWebhookInfo',
  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('url' => WEBHOOK_URL),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
}


function set() {
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.telegram.org/bot' . BOT_TOKEN . '/setWebhook',
  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('url' => WEBHOOK_URL,'max_connections'=> 100),
));

$response = curl_exec($curl);
curl_close($curl);
echo $response;

}





/*
//////////////////////////////////////////////////////////////////////////////


$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.telegram.org/bot' . BOT_TOKEN . '/setWebhook',
  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('url' => WEBHOOK_URL,'max_connections'=100),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;


$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.telegram.org/bot'.BOT_TOKEN.'/deleteWebhook',
  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',
));

$response = curl_exec($curl);

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

function send($method, $data, $botToken) {
    $url = "https://api.telegram.org/bot" . $botToken . "/" . $method;
    $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);
    return $result;
}


function read_db($oid,$chat_id,$dbname,$collection) {
global $conn ;
$db = new DbManager();
$conn = $db->getConnection();


    $filter = ['_id' => new MongoDB\BSON\ObjectId($oid)];
	//$options = ['projection' => ['_id' => 0.0]];
    $options = [];
	$read = new MongoDB\Driver\Query($filter, $options);
	$records = $conn->executeQuery("$dbname.$collection", $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);
sendMessage($chat_id, $res1);
  return $res1;
}


function count_db($chat_id,$dbname,$collection) {
global $conn ;
$db = new DbManager();
$conn = $db->getConnection();


    $filter = ['id' => (string)$chat_id];
	//$options = ['projection' => ['_id' => 0.0]];
    $options = [];
	$read = new MongoDB\Driver\Query($filter, $options);
	$records = $conn->executeQuery("$dbname.$collection", $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);
sendMessage($chat_id, $count1);
return $count1;


}






function read_all_db($chat_id,$dbname,$collection) {
global $conn ;
$db = new DbManager();
$conn = $db->getConnection();
// read all records
//$filter = [['_id' => new MongoDB\BSON\ObjectId($oid)]];
$filter = [];
	//$options = ['projection' => ['_id' => 0.0]];
    $options = [];
	$read = new MongoDB\Driver\Query($filter, $options);
	$records = $conn->executeQuery("$dbname.$collection", $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);

sendMessage($chat_id,  $count1);
}


function update_db($oid,$chat_id, $set_values, $dbname,$collection) {
global $conn ;
$update = new MongoDB\Driver\BulkWrite();
$update->update(
	['_id' => new MongoDB\BSON\ObjectId($oid)], ['$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($chat_id, "Record successfully updated");
} else {
    echo json_encode(
            array("message" => "Error while updating record")
    );
    sendMessage($chat_id, "Error while updating record");
}

}

function updateid_db($chat_id, $set_values, $dbname,$collection,$sesi) {
global $conn ;
$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($chat_id, "Record successfully updated");
} else {
    echo json_encode(
            array("message" => "Error while updating record")
    );
    // sendMessage($chat_id, "Error while updating record");
}

}

function updateidnosesi_db($chat_id, $set_values, $dbname,$collection) {
global $conn ;
$update = new MongoDB\Driver\BulkWrite();
$update->update(
	['id' => (string)$chat_id], ['$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($chat_id, "Record successfully updated");
} else {
    echo json_encode(
            array("message" => "Error while updating record")
    );
    // sendMessage($chat_id, "Error while updating record");
}

}

function insert_db($data, $chat_id, $dbname,$collection) {
global $conn ;
$insert = new MongoDB\Driver\BulkWrite();
$insert->insert($data);

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

// verify
if ($result->getInsertedCount() == 1) {
    echo json_encode(
		array("message" => "Record successfully created")
	);
    // sendMessage($chat_id, "Record successfully created");
} else {
    echo json_encode(
            array("message" => "Error while saving record")
    );
    // sendMessage($chat_id, "Error while saving record");
}

}


function delete_db($oid, $chat_id, $dbname,$collection) {

global $conn ;
// delete record
$delete = new MongoDB\Driver\BulkWrite();
$delete->delete(
	['_id' => new MongoDB\BSON\ObjectId($oid)],
	['limit' => 0]
);

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

//print_r($result);

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


}

function deleteid_db($chat_id, $dbname,$collection) {
global $conn ;

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

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

//print_r($result);

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


}


function contak($chat_id) {
global $botToken ;

$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
$parameters = array(
    'chat_id' => $chat_id,
    'text' => $response,
    'reply_markup' => $encodedKeyboard
);

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


}




?>
