<?php
include '../../connect.php';
session_start();

// Validasi parameter GET dan POST
if (!isset($_GET['bilikID']) || empty($_GET['bilikID'])) {
    echo "<script>alert('Ralat: ID bilik tidak sah.'); window.location.href = '../listSemakKelulusan.php';</script>";
    exit;
}

$bilikID = $_GET['bilikID'];
$catatan = isset($_POST['catatan']) ? strtoupper($_POST['catatan']) : '';

$query = "SELECT bilikID FROM tempahan_bilik WHERE bilikID='".$bilikID."'";
$strQuery = mysqli_query($conn,$query);

	if($strQuery)
	{
		$query1= "UPDATE `tempahan_bilik` SET status='BATAL', catatan='".$catatan."' WHERE bilikID='".$bilikID."'";
		$strQuery1 = mysqli_query($conn,$query1);
		
		if($strQuery1)
		{
			$sql = "SELECT * FROM tempahan_bilik WHERE bilikID='$bilikID'";
			$result = mysqli_query($conn,$sql);
			$row = mysqli_fetch_array($result);

			 $tarikhMesyuaratDari =$row['tarikh'];
			 $tarikhMesyuaratHingga =$row['tarikhHingga'];		
			 $masaDari = $row['masaDari'];
			 $masaHingga= $row['masaHingga'];
			 $jenisBilik = $row['jenisBilik'];

			$sql1="SELECT MIN(bilikID) as minID FROM tempahan_bilik WHERE jenisBilik='$jenisBilik' AND '$tarikhMesyuaratDari' BETWEEN tarikh AND tarikhHingga AND status ='SENARAI MENUNGGU'";
			//$sql1="SELECT bilikID FROM tempahan_bilik WHERE tarikh='$tarikhMesyuaratDari' AND tarikhHingga='$tarikhMesyuaratHingga' AND masaDari BETWEEN '$masaDari' AND '$masaHingga' AND masaHingga BETWEEN '$masaDari' AND '$masaHingga' AND jenisBilik='$jenisBilik' AND status ='SENARAI MENUNGGU';";
			$result1 = mysqli_query($conn,$sql1);
			$row1=mysqli_num_rows($result1);
			
			
			if($row1>=1)
			{
				$sql2="SELECT MIN(bilikID) as minID FROM tempahan_bilik WHERE jenisBilik='$jenisBilik' AND '$tarikhMesyuaratDari' BETWEEN tarikh AND tarikhHingga AND status ='SENARAI MENUNGGU'";
				//$sql2="SELECT bilikID FROM tempahan_bilik WHERE tarikh BETWEEN '$tarikhMesyuaratDari' AND '$tarikhMesyuaratHingga' AND masaDari BETWEEN '$masaDari' AND '$masaHingga' AND masaHingga BETWEEN '$masaDari' AND '$masaHingga' AND jenisBilik='$jenisBilik' AND status ='SENARAI MENUNGGU' ";
				$result2 = mysqli_query($conn,$sql1);
				$row2=mysqli_fetch_array($result2);
				
				$query2= "UPDATE `tempahan_bilik` SET status='SEDANG DIPROSES' WHERE bilikID='".$row2['minID']."'";
				$strQuery2 = mysqli_query($conn,$query2);
				
				if($strQuery2)
				{
					echo "<script>";
					echo "window.location.href = '../listSemakKelulusan.php';</script>";
					exit;
				}
				else
				{
					echo 'MySQL Error update: ' . mysqli_error($conn);
					exit;
				}
			}
			else
			{
				echo 'MySQL Error update: No query ' . mysqli_error($conn);
					exit;
			}
	
		}
		else
		{
			echo 'MySQL Error select *: ' . mysqli_error($conn);
			exit;
		}
	}
	else
	{
		echo 'MySQL Error batal: ' . mysqli_error($conn);
		exit;
	}

?>