<?php

require_once("../lib/dbconn.php");
$host=$pmshost;
$port=$pmsport;

$nomor_room = $_GET['nomor_room'];
$tanggal_ci = $_GET['tanggal_ci'];
$tanggal_co = $_GET['tanggal_co'];
$nama = trim($_GET['nama']);
$idguest= $_GET['idguest'];
$booking_id= $_GET['booking_id'];

if($nama==""){
	echo"error, tidak ada nama";
	exit;
}
if($tanggal_ci==""){
	echo"error, tidak ada tanggal checkin";
	exit;
}
if($tanggal_co==""){
	echo"error, tidak ada tanggal checkout";
	exit;
}
//PERTAMA BACA DULU KALAU KOSONG BARU ISI
$package =chr(2)."0103E".chr(3); //READ CARD
$package2 =chr(2)."0103H|R".$nomor_room."|N ".$nama."|D".$tanggal_ci."|O".$tanggal_co."|1".$booking_id.chr(3); //CHECKIN 4 desember 2015 jam 1610

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
    exit;
} else {
	  $result = socket_connect($socket, $host, $port);
	  //PERTAMA BACA DULU KALAU KOSONG BARU ISI
	  $package =chr(2)."0103E".chr(3); //READ CARD
  
		  if ($result === false) {
		    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
		    exit;
		   }else {
			   socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec'=>30, 'usec'=>10)); //SET TIME OUT 30detik
			   $test = socket_write($socket, $package, strlen($package));
			   $result = socket_read($socket,2048) or die('Could not read from socket');
				//echo $result;
				if($result){
					$nostx=str_replace(chr(2),"",$result);	
					$nordx=str_replace(chr(3),"",$nostx);	
					
					if(trim($nordx)=="03010|R|D|O|N|"){
						 socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec'=>30, 'usec'=>10)); //SET TIME OUT 30detik
			  			$test = socket_write($socket, $package2, strlen($package2));
			  			$result = socket_read($socket,2048) or die('Could not read from socket');
			  			if($result){
							
							$nostx=str_replace(chr(2),"",$result);	
							$nordx=trim(str_replace(chr(3),"",$nostx));	
							
							//LOG HERE
							$action ="add guest";
							@mysql_query("insert into tbl_card_log (action, nama, room_number,checkin_date, checkout_date, result,booking_id) values ('$action','$nama','$nomor_room','$tanggal_ci','$tanggal_co','$nordx','$booking_id')"); 
							
							echo "sukses";
							socket_close($socket);
							exit;
						} 
					}else{
						if(trim($nordx)=="03018"){ //KALAU TIDAK ADA KARTU DI SLOT
							echo "Masukkan kartu dan ulangi proses";	
						}else{
							echo"kartu ini sudah terisi, harap ganti dengan kartu lain ".$nordx;
						}
						socket_close($socket);
						exit;
					}
				
			}else{
				echo "no reply";
				socket_close($socket);
				exit;
			}

	}
}
?>