<?php session_start();

if($_SESSION["invcox"] == ""){
    header("location:login.php?action=need");
} else {
include("config.php");?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Arnim Holidays Accounting Software</title>

<link href="style.css" rel="stylesheet" type="text/css" />

<style type="text/css">
    .dashboard-container {
      background: #eaf1f1;
      padding: 20px;
      border-radius: 12px;
      width: fit-content;
      margin: auto;
      box-shadow: 0 0 8px rgba(0,0,0,0.2);
    }
    h2 { text-align: center; margin-bottom: 20px; }
    th, td {
      width: 30px; height: 30px; text-align: center;
      vertical-align: middle; border-radius: 6px;
      font-size: 13px; position: relative;
    }
    th { background:#f8f8f8; font-weight:bold; white-space:nowrap; padding:8px 10px; }

    .available { color:#9c989a;  }
    .booked {  color:#000; }
    .hold {   color:#000; }
    .check-in { color:#000; }
    .Check-out {   color:#fff; }

    .friday-row td, .friday-row th { background:#b5e2f5 !important; }
    .saturday-row td{ background:#ffe2b5 !important; }
	.saturday-row th { background:#ffe2b5 !important; }
    .today-row td, .today-row th {
        background:#db4197 !important;
        color:#fff; font-weight:bold;
    }

    /* Tooltip */
/*#hotelTable td:hover::after {
      content: attr(data-info);
      position: absolute;
      top: -25px;
      left: 50%;
      transform: translateX(-50%);
      background-color: #333;
      color: #fff;
      font-size: 12px;
      padding: 3px 6px;
      border-radius: 4px;
      white-space:normal;
	 width: 150px;
      z-index: 10;
    }*/
.tooltip-box {
    position: absolute;
    top: -10px;
    left: 50%;
    transform: translate(-50%, -100%);
    background: #333;
    color: #fff;
    padding: 6px 8px;
    font-size: 12px;
    border-radius: 6px;
    width: 160px;
    z-index: 100;
    display: none;
    white-space: normal;
}

.cell {

  height:100%;

  border-radius:6px;

  display:flex;

  align-items:center;

  justify-content:center;

  font-size:12px;

  user-select:none;
  position:relative;
  transition:transform 0.15s ease, background 0.15s ease;

}

.cell:hover {transform:scale(1.08);filter:brightness(1.1)}

 
.status-avail {
    background: linear-gradient(180deg, #fff, rgba(31, 122, 31, 0.04));
    border: 1px solid #8B8B8B;
}
.status-checkin {
    border: 1px solid #8B8B8B;
	background: #1d6e8f;
background: linear-gradient(90deg,rgba(29, 110, 143, 1) 0%, rgba(79, 196, 163, 1) 60%);


}

.status-hold {
    background: linear-gradient(180deg, #fff, #e67e22);
    border: 1px solid #8B8B8B;
}
.status-booked {
    background: linear-gradient(180deg, #fff, #34d159);
    border: 1px solid #8B8B8B;
}

.status-checkout {
    
    border: 1px solid #8B8B8B;
	
	
background: #828282;
background: linear-gradient(0deg,rgba(130, 130, 130, 1) 0%, rgba(0, 0, 0, 0.88) 55%);
}

 
</style>

<?php include("calendar.php"); ?>
</head>

<body>

<table width="95%" align="center" cellpadding="0" cellspacing="1" class="box-wrap">
<tr><td><?php include("top.php")?></td></tr>

<tr><td class="center_page_white">

<table width="100%" cellspacing="1" cellpadding="0">
<tr><td class="round_box">

<form method="post" enctype="multipart/form-data">
  <h2>Hotel Reservation Dashboard </h2>
  <table width="300" border="0" align="center" cellpadding="2" cellspacing="2">
  <tbody>
    <tr>
      <td> <select name="month" id="month" onChange="this.form.submit();">
    <option value="">Select Month</option>
    <?php
    $months = array(
        1=>"January", 2=>"February", 3=>"March", 4=>"April",
        5=>"May", 6=>"June", 7=>"July", 8=>"August",
        9=>"September", 10=>"October", 11=>"November", 12=>"December"
    );

    // Use current month if not selected
    $currentMonth = date("n");
    $selectedMonth = isset($_POST['month']) ? (int)$_POST['month'] : $currentMonth;

    foreach ($months as $num => $name) {
        $selected = ($selectedMonth == $num) ? "selected" : "";
        echo "<option value='$num' $selected>$name</option>";
    }
    ?>
</select>


</td>
      <td> <select name="year" id="year" onChange="this.form.submit();">
    <option value="">Select Year</option>
    <?php
    $currentYear = date("Y");
    $selectedYear = isset($_POST['year']) ? (int)$_POST['year'] : $currentYear;

    for ($y = $currentYear - 3; $y <= $currentYear + 3; $y++) {
        $selected = ($selectedYear == $y) ? "selected" : "";
        echo "<option value='$y' $selected>$y</option>";
    }
    ?>
</select>

		</td>
    </tr>
  </tbody>
</table>
</form>
	
<div class="dashboard-container">
  
    <table id="hotelTable">
      <thead><tr><th>Room →</th></tr></thead>
      <tbody id="dashboardBody"></tbody>
    </table>
</div>

<script>
/* ---------------------------
   ROOM LIST FROM DATABASE
----------------------------- */

function load_data(){
	
const rooms = [
<?php
$result = mysql_query("select * from hotel_room order by room_no asc");
$first = true;
while($row = mysql_fetch_array($result)){
    if(!$first) echo ",";
    echo '"' . $row["room_no"] . '"';
    $first = false;
}
?>
];

/* Month setup */
//const month = 10; // November
//const year = 2025;
//const month = document.getElementById("month").value; 
//const year  = document.getElementById("year").value; 

const month = <?= isset($_POST['month']) ? ($_POST['month'] - 1) : date("n") - 1 ?>; 
const year  = <?= isset($_POST['year'])  ? $_POST['year']        : date("Y") ?>;
	
const daysInMonth = new Date(year, month+1, 0).getDate();
const weekdays = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];

const today = new Date();
const isCurrentMonth = today.getMonth() === month && today.getFullYear() === year;
const todayDate = isCurrentMonth ? today.getDate() : null;

/* ---------------------------
   BOOKING DATA WITH FULL INFO
----------------------------- */
const bookedCells = {
<?php
// Get month and year from GET parameters
$month = isset($_POST['month']) ? (int)$_POST['month'] : date('n');
$year  = isset($_POST['year']) ? (int)$_POST['year'] : date('Y');

// Get first and last date of the month
$firstDate = "$year-$month-01";
$lastDate  = date("Y-m-t", strtotime($firstDate));
	
$q = mysql_query("
SELECT customer.customer_name, bookings.room_no, bookings.bill_id, 
       bookings.check_in, bookings.status, bookings.rprice 
FROM bookings
JOIN customer ON customer.id = bookings.customer_id
WHERE bookings.check_in >= '$firstDate'
AND bookings.check_in <= '$lastDate'
ORDER BY bookings.check_in ASC
");

$first = true;
while($row = mysql_fetch_array($q)) {
    if(!$first) echo ",";
    $day = (int)substr($row["check_in"], 8, 2);

    echo '"' . $row["room_no"] . '-' . $day . '" : "'
        . $row["status"] . '|'
        . $row["customer_name"] . '|'
        . $row["bill_id"] . '|'
        . $row["rprice"] . '"';
    $first = false;
}
?>
};

/* Parse info string: "Booked|Name|Bill|Date" */
  fetch(`get_bookings.php?month=${month}&year=${year}`)
    .then(response => response.json())
    .then(bookedCells => {
        buildTable(bookedCells, month, year); // your existing JS code to draw table
    });

const tbody = document.getElementById("dashboardBody");
   tbody.innerHTML = "";
/* ---------------------------
   BUILD DASHBOARD
----------------------------- */
for(let day=1; day<=daysInMonth; day++){
    const tr = document.createElement("tr");

    const dateObj = new Date(year, month, day);
    const dayName = weekdays[dateObj.getDay()];

    const dateCell = document.createElement("th");
    dateCell.textContent = `${day} - ${dayName}`;
    tr.appendChild(dateCell);

    if(dayName==="Fri") tr.classList.add("friday-row");
    if(dayName==="Sat") tr.classList.add("saturday-row");
    if(day===todayDate) tr.classList.add("today-row");

    rooms.forEach(room=>{
        const td = document.createElement("td");
        const key = `${room}-${day}`;
        const info = parseInfo(bookedCells[key]);

        if(info){
            td.textContent = room;
            td.dataset.info =
                `Status: ${info.status},\nCustomer: ${info.customer},\n,Bill: ${info.bill},\n Rent: ${info.date}`;

if(info.status==="Booked") {
    td.className="booked";
    td.innerHTML = `<div class="cell status-booked">${room}</div>`;
}
else if(info.status==="Hold") {
    td.className="hold";
    td.innerHTML = `<div class="cell status-hold">${room}</div>`;
}
else if(info.status==="Check-in") {
    td.className="check-in";
    td.innerHTML = `<div class="cell status-checkin">${room}</div>`;
}
else if(info.status==="Check-out") {
    td.className="Check-out";
    td.innerHTML = `<div class="cell status-checkout">${room}</div>`;
}

			
			
           
        } else {
            td.className = "available";
            td.dataset.info = "Available";
            td.innerHTML = `<div class="cell status-avail">${room}</div>`; 
        }

        tr.appendChild(td);
    });

    tbody.appendChild(tr);
}

/* Add room headers */
const headerRow = document.querySelector("thead tr");
 headerRow.innerHTML = "<th>Room →</th>";
	
rooms.forEach(r=>{
    let th = document.createElement("th");
    th.textContent = r;
    headerRow.appendChild(th);
});
	
	
}
	
	
function parseInfo(infoString){
    if(!infoString) return null;
    let p = infoString.split("|");
    return { status:p[0], customer:p[1], bill:p[2], date:p[3] };
}


document.addEventListener("click", function (e) {
    // close all tooltips
    document.querySelectorAll(".tooltip-box").forEach(t => t.remove());

    const td = e.target.closest("td");
    if (!td || !td.dataset.info) return;

    const tooltip = document.createElement("div");
    tooltip.className = "tooltip-box";
    tooltip.innerText = td.dataset.info;

    td.style.position = "relative";
    td.appendChild(tooltip);
    tooltip.style.display = "block";

    e.stopPropagation();
});

</script>

</td></tr></table>

</td></tr>

<tr><td><?php include("bot.php")?></td></tr>
</table>
<script language="javascript">
	
window.onload = function(){
    load_data();
};
	
	</script>
</body>
</html>

<?php } ?>
