<?php
$coll = isset($_GET["coll"])?$_GET["coll"]:"";
$action = isset($_GET["action"])?$_GET["action"]:"";
// required headers
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");
$data = json_decode(file_get_contents("php://input", true));



// include database file
include_once 'mongodb_config.php';
$db = new DbManager();
$conn = $db->getConnection();



/*

// "https://isekolah.my.id/esp32_restapi/rest_api-esp32.php?action=add&coll=esp32.coba";
  
*/

////////////////////////////////////////////
if ($action == "daftar") {
////////////////////////////////////////////
    $ids = $data->id;

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

//fetch records
$records = $conn->executeQuery("$coll", $read);

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

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

        }else{

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

        //$result = $conn->executeBulkWrite("$dbname.$collection", $insert);
        $result = $conn->executeBulkWrite("$coll", $insert);
        // verify
        if ($result->getInsertedCount() == 1) {
            echo json_encode(
                array("message" => "Record successfully created")
            );
        } else {
            echo json_encode(
                    array("message" => "Error while saving record")
            );
        }
        }
}

//"https://isekolah.my.id/esp32_restapi/rest_api-esp32.php?action=id&coll=esp32.coba";
//////////////////////////////////////////////
if ($action == "id-data") {
///////////////////////////////////////////////
$ids = $data->id;

$filter = ['id' => (string)$ids ];
$option = [];
$read = new MongoDB\Driver\Query($filter, $option);

//fetch records
$records = $conn->executeQuery("$coll", $read);

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


echo json_encode(
            array("count" =>$count1,"data" => $result1)
    );


 // echo $result2['0']["nama"];

// var_dump($result2) ;
}

////////////////////////////////////////////////
if ($action == "update") {
/////////////////////////////////////////////
$_id = $data->_id;
$id = $data->id;
$nama = $data->nama;
$kelas = $data->kelas;

$edit = $data->edit;

if((int)$del == 0){

echo json_encode(
		array("message" => "Record gagal update")
	);
}else{



 $data1 = [
            'id' => $id,
            'nama' => $nama,
            'kelas' => $kelas
            ];

//echo json_encode(
//		array("message" =>  $data1)
//	);

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


['_id' => new MongoDB\BSON\ObjectId((string)$_id)], ['$set' => $data1]


);

$result = $conn->executeBulkWrite("$coll", $update);

// verify
if ($result->getModifiedCount() == 1) {
    echo json_encode(
		array("message" => "Record successfully updated")
	);
} else {
    echo json_encode(
            array("message" => "Error while updating record")
    );
}
}
}
//////////////////////////////////////////////////////////
if ($action == "delete") {
////////////////////////////////////////////////////////
$id = $data->id;
$_id = $data->_id;

$del = $data->del;

if((int)$del == 0){

echo json_encode(
		array("message" => "Record gagal deleted")
	);
}else{



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

$result = $conn->executeBulkWrite("$coll", $delete);

//print_r($result);

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


 // echo $result2['0']["nama"];

// var_dump($result2) ;
}
}


///////////////////////////////////////////////////////////////
if ($action == "sendp") {
///////////////////////////////////////////////////////////////




$bot_id ="6566404423:AAExFg4d97VDcacjyUxl05TLTgSYYieJxJM";
$chat_id ="304835260";
$caption =" nama :".$nama."\n kelas :".$kelas."\n Sekolah :".$sekolah;

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.telegram.org/bot6566404423:AAExFg4d97VDcacjyUxl05TLTgSYYieJxJM/sendPhoto',
  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),'caption' => $caption),
));

$response = curl_exec($curl);

curl_close($curl);
// echo $response;
// var_dump($response);
$result6= json_decode($response, true);
	
	$ok =$result6['ok'];
    if( $ok == 1){
         echo "<center> tugas berhasil terkirim!<br/>";
    echo "<center> ";
    echo $result6["result"]["chat"]["id"];
    echo "</br>";
    echo $result6["result"]["from"]["username"];
    // echo $result6["result"]["chat"]["id"];
    // header("location: ../../siswa/index.php?page=send&msg=ok");
    }
}













































if ($action == "all") {


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

//fetch records
$records = $conn->executeQuery("$coll", $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);
//  echo "\n";
// if($count1 > 1){
// $jum = [{'conut' =>$count1} ];
//  echo $jum  ;

// //echo $count1 ;
// }else if($count1 == 1){
// $jum = [{'data' => $res1,'conut' =>$count1 }];
//  echo $jum  ;
// }

 // echo $result2['0']["nama"];

// var_dump($result2) ;
}

//  "https://isekolah.my.id/esp32_restapi/rest_api-esp32.php?action=del&coll=esp32.coba";
//  "https://isekolah.my.id/esp32_restapi/rest_api-esp32.php?action=update&coll=esp32.coba";
///////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

if ($action == "add") {


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

//$result = $conn->executeBulkWrite("$dbname.$collection", $insert);
$result = $conn->executeBulkWrite("$coll", $insert);
// verify
if ($result->getInsertedCount() == 1) {
    echo json_encode(
		array("message" => "Record successfully created")
	);
} else {
    echo json_encode(
            array("message" => "Error while saving record")
    );
}
}

?>