<?php

include_once ("includes/setup.inc.php");
//Header("Content-type: application/xml");
Header("Cache-Control: no-cache");

$num_errors = 0;
$klinik = fetch_postget_val("klinik_vat", $_POST, $_GET);
$appoint_date = fetch_postget_val("tkh_appointment", $_POST, $_GET);
$appoint_time = fetch_postget_val("timeslot", $_POST, $_GET);
$id_pet = fetch_postget_val("id_pet", $_POST, $_GET);
$remarks = fetch_postget_val("remarks", $_POST, $_GET);
$id = 0;
$dateTimeNow = dateTimeNow();

//double check right before insert
$date = date_create($appoint_date);
$indicator_Query = "select id_vatklinik_appointment 
					FROM m_vatklinik_appointment
					WHERE is_active AND id_vatklinik = ? AND appointment_date = ? AND appointment_time = ?";
$PDO_stmt = $PDO->prepare($indicator_Query);
$PDO_stmt->bindValue(1, $klinik, PDO::PARAM_INT);
$PDO_stmt->bindValue(2, date_format($date, "Y-m-d"), PDO::PARAM_STR);
$PDO_stmt->bindValue(3, $appoint_time, PDO::PARAM_STR);
$PDO_stmt->execute();
$appointmentTime_List = $PDO_stmt->fetch(PDO::FETCH_ASSOC);
if($appointmentTime_List['id_vatklinik_appointment'] > 0)
{
	echo "Masa Temu Janji telah penuh. Sila pilih masa yang lain";
	exit(0);
}

try
{
	$PASS_COUNTER = 0; //COUNTER FOR DOUBLE CONFIRM
	$PASS_VALUE = 1; //NUMBER OF QUERY TO EXECUTE. IMPORTANT FOR CHECKING!!

	//PDO INIT
	$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$PDO->beginTransaction();

	$indicator_Array = array();
	$indicator_Array[] = array('id_vatklinik', $klinik, PDO::PARAM_STR);
	$indicator_Array[] = array('id_pemilik', $my_details->usr_id, PDO::PARAM_INT);
	$indicator_Array[] = array('id_pemilik_pet', $id_pet, PDO::PARAM_STR);
	$indicator_Array[] = array('appointment_date', date_format($date, "Y-m-d"), PDO::PARAM_STR);
	$indicator_Array[] = array('appointment_time', $appoint_time, PDO::PARAM_STR);
	$indicator_Array[] = array('is_active', 1, PDO::PARAM_INT);
	$indicator_Array[] = array('remarks', $remarks, PDO::PARAM_STR);
	$indicator_Array[] = array('insert_by', $my_details->usr_id, PDO::PARAM_INT);
	$indicator_Array[] = array('tkh_insert', $dateTimeNow, PDO::PARAM_STR);
	
	if($id == 0)
	{
		$PASS_COUNTER += PDO_INSERT($PDO, 'm_vatklinik_appointment', $indicator_Array);
	}
	else
	{
		$whereCondition = "WHERE id_vatklinik_appointment = $id";
		$PASS_COUNTER += PDO_UPDATE($PDO, 'm_vatklinik_appointment', $indicator_Array, $whereCondition);
	}

	//*****************************************
	//COMMIT if PASS_COUNTER == PASS_VALUE
	//*****************************************
	if ($PASS_COUNTER == $PASS_VALUE)
	{
		$PDO->commit();
		echo $PASS_COUNTER;
	}
	else
	{
		$PDO->rollBack();
		echo -1;
	}
}
catch (Exception $e) 
{
	$PDO->rollBack();
	echo "Failed: " . $e->getMessage();
}

?>