<?php 

include("koneksi.php");
$koneksi3=open_koneksi_1(); 

	$hasil_rec = mysqli_query($koneksi3,"SELECT * FROM `rec` WHERE sts='0' ORDER BY id DESC;" );
		$rowx = mysqli_fetch_array($hasil_rec);

$rfid=$rowx['rfid'];
$userid=$rowx['iduser'];
$npsn=$rowx['npsn'];
$id=$rowx['id'];



	    $koneksi=open_koneksi_2($npsn);  
		$result = mysqli_query($koneksi,"SELECT * FROM siswa WHERE id='".$userid."'");
		if($result) //result select user
		{	
			if(mysqli_num_rows($result)<>0) //result mysql_num_rows select user
			{	
			    
			    	$hasil_rec = mysqli_query($koneksi3,"UPDATE `rec` SET sts='1' WHERE id='".$id."' ;" );

				$data2=mysqli_fetch_array($result);
			
				$nama=addslashes($data2['nama']);$idkel='-'; $kelompok='-';
			$no=addslashes($data2['nohp_ortu']);
				
				$pembeda=rand(11111,99999);
				$path='img/'.$pembeda.'-'.$userid.'.jpeg';

				 $file = fopen($path,"w");
 				 $gambar=substr($pict,22);
   				 fwrite($file, base64_decode($gambar));
   				 fclose($file);
				 
				 	            $hasil_sekolah=mysqli_query($koneksi,"SELECT * FROM `sekolah` ");
								$datasch=mysqli_fetch_array($hasil_sekolah);
								$namasch=$datasch['nama_sekolah'];
				 
				 				$hasil_kel=mysqli_query($koneksi,"SELECT * FROM `tbkelompok` ");
								$datakel=mysqli_fetch_array($hasil_kel);
								$asal   = $lotx.','.$longx;
								$tujuan = $datakel['koordinat'];
									//hitung jarak
									 $posisi=strpos($tujuan,",");
                                    $posisi2=strpos($tujuan,".");
                                    if (($posisi !== FALSE) && ($posisi2 !== FALSE)) {
									
									$pecah = explode(",", $tujuan);
									$lat2=$pecah[0];
                                    $long2=$pecah[1];
									$jarak=floor(jarak_gps($lotx,$longx,$lat2,$long2));
                                    } else {$jarak='';}
									
							
								    $tujuan="";$dari="";$nilaiJarak=$jarak." m";$nilaiJarak_meter=$jarak;$nilaitempuh_detik=$jarak / 2;$nilaitempuh=$nilaitempuh_detik." s";
								    if($lotx=='0')
								    {$luar_area="(Dalam Area)";$nilaiJarak='0'; $nilaitempuh='0';} else{
								    	if($nilaiJarak_meter > 300){ $luar_area="(Luar Area)";} else {$luar_area="(Dalam Area)";}
								    }
date_default_timezone_set('Asia/Makassar'); 						//	}
$date = date('Y-m-d H:i:s', time());

				$query = "INSERT INTO tbpresensi(iduser,nama,img,lotx,longx,alamat,jarak_value_m,jarak_text,tempuh_value_s,tempuh_text,tgl) VALUES ('$userid','$nama','-', '0', '0', '-', 0, '0' ,0, '0', '$date')";
		//echo $query;
				$hasil = mysqli_query($koneksi,$query);
			
			
				if($hasil) //insert tbpresensi
				{
					date_default_timezone_set('Asia/Makassar'); 
					$tanggal= date('Y-m-d');
					$jamabsen= date('H:i:s');
					
					$hari=strday($tanggal);
					$resultjam = mysqli_query($koneksi,"SELECT * FROM tbabsen_jam WHERE id IN (SELECT idjam FROM tbabsen_shift WHERE (".$hari."='1') ) ");
					
					if(mysqli_num_rows($resultjam)<>0) // mysql_num_rows tbabsen_jam
					{	
						$data3=mysqli_fetch_array($resultjam);
						$masuk=$data3['masuk'];
						$pulang=$data3['pulang'];
						$awal_masuk=$data3['awal_masuk'];
						$akhir_masuk=$data3['akhir_masuk'];
						//ABSENSI MASUK
						if($awal_masuk <= $jamabsen) //absen terlalu pagi
						{
							if($masuk >= $jamabsen)
							{ //Masuk Tepat Waktu
								$hasil_absen=mysqli_query($koneksi,"SELECT * FROM tbabsen WHERE (tanggal='$tanggal') and (iduser='$userid') ");
								 $dataabsen=mysqli_fetch_array($hasil_absen);
								if(mysqli_num_rows($hasil_absen)==0)
								{
									mysqli_query($koneksi,"INSERT INTO tbabsen(iduser,nama,idkel,kelompok,tanggal,masuk,sts_masuk) VALUES ('$userid','$nama','$idkel','$kelompok','$tanggal','$jamabsen','MTW')");
									$message='[BOT] Ananda '.$nama.' telah Absen Masuk '.$tanggal.' Jam '.$jamabsen. ',Ket : Masuk Tepat Waktu , dari '.$namasch.' (WA BOT tidak perlu dibalas)';
								    send_wa($no,$message);
								} else {
								 $message='[BOT] Ananda '.$nama.' telah Absen Masuk '.$tanggal.' Jam '.$jamabsen. ',Ket :  Masuk Tepat Waktu, dari '.$namasch.' (WA BOT tidak perlu dibalas)';
								 send_wa($no,$message);
							
								}
							//====================================
							} elseif($akhir_masuk >= $jamabsen)
							{//TM : Telat Masuk	
								$hasil_absen=mysqli_query($koneksi,"SELECT * FROM tbabsen WHERE (tanggal='$tanggal') and (iduser='$userid') ");
								if(mysqli_num_rows($hasil_absen)==0)
								{
								mysqli_query($koneksi,"INSERT INTO tbabsen(iduser,nama,idkel,kelompok,tanggal,masuk,sts_masuk) VALUES ('$userid','$nama','$idkel','$kelompok','$tanggal','$jamabsen','TM')");
								
								$message='[BOT] Ananda '.$nama.' telah Absen Masuk '.$tanggal.' Jam '.$jamabsen. ', Ket : Terlambat Masuk, dari '.$namasch.' (WA BOT tidak perlu dibalas)';
								send_wa($no,$message);
							    } else {
								$message='[BOT] Ananda '.$nama.' telah Absen Masuk '.$tanggal.' Jam '.$jamabsen. ', ket: Terlambat Masuk, dari '.$namasch.' (WA BOT tidak perlu dibalas)';
								send_wa($no,$message);
								}
							//=======================================					
							} elseif(($akhir_masuk < $jamabsen) && ($pulang > $jamabsen)) 					
							{//PULANG
								$hasil_absen=mysqli_query($koneksi,"SELECT * FROM tbabsen WHERE (tanggal='$tanggal') and (iduser='$userid') ");
								if(mysqli_num_rows($hasil_absen)==0)
								{ //PC : Pulang Cepat jika belum ada absen masuk
								 mysqli_query($koneksi,"INSERT INTO tbabsen(iduser,nama,idkel,kelompok,tanggal,pulang,sts_pulang) VALUES ('$userid','$nama','$idkel','$kelompok','$tanggal','$jamabsen','PC')");
								 //==================================
								} else if ($dataabsen['sts_pulang']=='')
								{
								  mysqli_query($koneksi,"UPDATE tbabsen SET pulang='$jamabsen',sts_pulang='PC' WHERE (tanggal='$tanggal') and (iduser='$userid')");
								} 
								$message='[BOT] Ananda '.$nama.' telah Absen Pulang '.$tanggal.' Jam '.$jamabsen. ', ket: Pulang Cepat, dari '.$namasch.' (WA BOT tidak perlu dibalas)';
							
								        send_wa($no,$message);
								
							
								
							} else {
								$hasil_absen=mysqli_query($koneksi,"SELECT * FROM tbabsen WHERE (tanggal='$tanggal') and (iduser='$userid') ");
								 $dataabsen=mysqli_fetch_array($hasil_absen);
								if(mysqli_num_rows($hasil_absen)==0)
								{
								 mysqli_query($koneksi,"INSERT INTO tbabsen(iduser,nama,idkel,kelompok,tanggal,pulang,sts_pulang) VALUES ('$userid','$nama','$idkel','$kelompok','$tanggal','$jamabsen','PTW')");
								} else 
								 if ($dataabsen['sts_pulang']=='')
								 {
								 mysqli_query($koneksi,"UPDATE tbabsen SET pulang='$jamabsen',sts_pulang='PTW' WHERE (tanggal='$tanggal') and (iduser='$userid') ");
								 }

								$message='[BOT] Ananda '.$nama.' telah Absen Pulang '.$tanggal.' Jam '.$jamabsen. ', ket: Pulang Tepat Waktu, dari '.$namasch.' (WA BOT tidak perlu dibalas)';
							
							
								        send_wa($no,$message);
															
							
					//	echo $nama;
							}														
							
						} else { //absen terlalu pagi
						
						}
						

					} else { // mysql_num_rows tbabsen_jam
					
						//	echo "Tidak Ada jadwal  hari ini";			
					}
				} else //insert tbpresensi
				{   //$MyJson['pesan']=$dsts;
					$MyJson['status']='01';
					//echo json_encode($MyJson);
				//	echo "012";
				}
		//	} else //cek data tbpresensi
		//		{   //$MyJson['pesan']=$dsts;
		//			$MyJson['status']='01';
		//			echo json_encode($MyJson);
		//		}
			} else //result mysql_num_rows select user
			{
					$MyJson['status']='01';
					//echo json_encode($MyJson);
				//	echo "011";
			}
		}else { //result select user
		$MyJson['status']='01';
		//echo json_encode($MyJson);
	//	echo "010";
		}


function jarak_gps($lat1,$long1,$lat2,$long2)
{
$E11 = 6378.14;
$B14=deg2rad($lat1);
$C15=deg2rad($long1);

$B15=deg2rad($lat2);
$C14=deg2rad($long2);

$jarak =acos(sin($B14)*sin($B15)+cos($B14)*cos($B15)*cos($C15-$C14))*$E11;
$jarak_m=$jarak*1000;
return $jarak_m;
}

function strday($tanggal)
{
$day = date('D', strtotime($tanggal));
$dayList = array(
	'Sun' => 'minggu',
	'Mon' => 'senin',
	'Tue' => 'selasa',
	'Wed' => 'rabu',
	'Thu' => 'kamis',
	'Fri' => 'jumat',
	'Sat' => 'sabtu'
);
return $dayList[$day];
}

function send_wa3($number,$pesan){
     $n=strlen($number);
     if($n > 8){
// API URL
$url = 'http://103.164.173.180:8000/send-message';
//$url = 'http://103.164.173.174:8000/send-media';
$number=$row['hp'];
$pesan=$row['pesan'];
//$caption=$row['caption'];
// Create a new cURL resource
$ch = curl_init($url);

// Setup request to send json via POST
$data = array(
    //'caption' => $caption,
    'number' => $number,
    'message' => $pesan,
    //'file' => $pesan,
    
    'token' => 'NtvYSaNcOPhHxFyQ23'
);
$payload = json_encode($data);

// Attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

// Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

// Return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the POST request
$result = curl_exec($ch);
$data = json_decode($result);
$status=$data->status;
}
}

function send_wa($number,$pesan){
 $n=strlen($number);
  if($number <> '0818001122'){
 if($n > 8){
    $url="http://103.164.173.180/whatsapp_api.php";
$data = array("hp" => $number,"pesan" => $pesan); // data u want to post   
$data_string = json_encode($data);                                                                                   
 $api_key = "Xh83!sA";   
 $password = "HshFla72nsFa,s==ds0adsd028-=29ndgala";                                                                                                                 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url);    
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
curl_setopt($ch, CURLOPT_POST, true);                                                                   
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     
curl_setopt($ch, CURLOPT_USERPWD, $api_key.':'.$password);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(   
    'Accept: application/json',
    'Content-Type: application/json')                                                           
);             
$result = curl_exec($ch);
curl_close($ch);  
return $result;
}
}
    
}



function send_notif($tokens,$title, $message)
{

 $url = 'https://fcm.googleapis.com/fcm/send';
 
 $msg = array
 (
 'body' => "$message",
 'title' => "$title",
 "smallIcon" => "drawable/icon",
  'sound' => 'default',
  'vibrate' => true
 );

 $fields = array
 (
 'to' => '/topics/'.$tokens,
 'notification' => $msg,
 'priority' => 'high'
 );
 $headers = array(
 'Authorization:key = AAAAp7zrRNA:APA91bFaIg5hHmZUXljjVvBZMIiYXTVa6QGzuN22eaQ97c2Q9RJjrIpJgClAmF7ACkn1hXsxEIzuqXq33b4IEt81YompPUbwY2Hc0nrM6l_csLlbC-Yecq2AO26msfne76IwkIW-ggQx',
 'Content-Type: application/json'
 );
 
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_POST, true);
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);  
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
 $result = curl_exec($ch);           
 if ($result === FALSE) {
 die('Curl failed: ' . curl_error($ch));
 }
 curl_close($ch);
 return $result;
}

?>