
<?php
$priceDecimal = 2;
$sqlSetting   = mysql_query("SELECT * FROM s_module_detail_settings WHERE id = 40 AND is_active = 1");
while($rowSetting = mysql_fetch_array($sqlSetting)){
    if($rowSetting['id'] == 40){
        $priceDecimal = $rowSetting['value'];
    }
}
$rnd = rand();
$tblName = "tbl" . rand();
$printArea = "printArea" . $rnd;
$btnPrint = "btnPrint" . $rnd;
$btnExport = "btnExport" . $rnd;

include('includes/function.php');

/**
 * export to excel
 */
$filename="public/report/occupancy_report_" . $this->Session->id(session_id()) . ".csv";
$fp=fopen($filename,"wb");
$excelContent = '';

?>
<script type="text/javascript">
    $(document).ready(function(){
        $("#<?php echo $btnPrint; ?>").click(function(){
            w=window.open();
            w.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
            w.document.write('<link rel="stylesheet" type="text/css" href="<?php echo $this->webroot; ?>css/style.css" /><link rel="stylesheet" type="text/css" href="<?php echo $this->webroot; ?>css/table.css" /><link rel="stylesheet" type="text/css" href="<?php echo $this->webroot; ?>css/button.css" /><link rel="stylesheet" type="text/css" href="<?php echo $this->webroot; ?>css/print.css" media="print" />');
            w.document.write($("#<?php echo $printArea; ?>").html());
            w.document.close();
            w.print();
            w.close();
        });
        
        $("#<?php echo $btnExport; ?>").click(function(){
            window.open("<?php echo $this->webroot; ?>public/report/occupancy_report_<?php echo $this->Session->id(session_id()); ?>.csv", "_blank");
        });
    });
</script>
<div id="<?php echo $printArea; ?>">
    <?php
    $msg = '<b style="font-size: 18px;">' .  "Occupancy Report" . '</b><br />';
    // $msg .= '<b style="font-size: 16px;">' . TABLE_VIEW_BY . ': '."Customer Arrival/Departure Summary".'</b><br /><br />';
    $excelContent .= "Occupancy Report"."\n";
    if (isset($_POST['monthSelect']) && $_POST['monthSelect'] != '' && isset($_POST['yearSelect']) && $_POST['yearSelect'] != '') {
        $months = [
            1 => "January", 2 => "February", 3 => "March",
            4 => "April", 5 => "May", 6 => "June",
            7 => "July", 8 => "August", 9 => "September",
            10 => "October", 11 => "November", 12 => "December"
        ];
    
        $monthName = $months[$_POST['monthSelect']] . " " . $_POST['yearSelect']; // Get the month name from the array
        $msg .= $monthName;
        $excelContent .= $monthName . "\n";
    }

    echo $this->element('/print/header-report',array('msg'=>$msg));
    ?>
    <table id="<?php echo $tblName; ?>" class="table" style="">

    <?php
    $year = date("Y");
    $month = date("m");
    $numDays = cal_days_in_month(CAL_GREGORIAN, $month, $year);

    ?>

        <?php
        // general condition
        $col = implode(',', $_POST);
        $col = explode(",", $col);
        $condition = '';

        $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
        // $status = " AND orders.status IN(2,3) ";

        function fetchRoomTypeAvailability($roomTypeId, $formattedDay, $type = 0) {
            // Query to count the total number of rooms of this type
            $totalRoomsQuery = mysql_query("
                SELECT COUNT(id) AS total
                FROM rooms
                WHERE room_type_id = {$roomTypeId}
            ");
            $totalRoomsResult = mysql_fetch_array($totalRoomsQuery);
            $totalRooms = $totalRoomsResult['total'];

            $occupiedRoomsQuery = mysql_query("
				SELECT COUNT(r.id) AS occupancy
				FROM rooms AS r
				INNER JOIN room_types AS rt ON rt.id = r.room_type_id
				WHERE rt.id = {$roomTypeId} 
				AND EXISTS (
					SELECT 1
					FROM orders
					INNER JOIN order_services ON orders.id = order_services.order_id
					LEFT JOIN order_night_audits ona ON orders.id = ona.order_id
					WHERE order_services.room_id = r.id
						AND (
							(order_services.is_night_audit = 1 
							AND ona.night_audit_report_date != '0000-00-00 00:00:00' 
							AND DATE_FORMAT(ona.night_audit_report_date, '%Y-%m-%d') = '{$formattedDay}')
							OR
							(order_services.is_night_audit = 0 
							AND '{$formattedDay}' BETWEEN order_services.start_date 
							AND DATE_SUB(order_services.end_date, INTERVAL 1 DAY))
						)
					GROUP BY order_services.room_id
				)
			");


            if (mysql_num_rows($occupiedRoomsQuery)) {
                $occupiedResult = mysql_fetch_array($occupiedRoomsQuery);
                $occupiedRooms = $occupiedResult['occupancy'];
        
                $occupancyPercentage = ($totalRooms > 0) ? round(($occupiedRooms / $totalRooms) * 100, 0) : 0;
        
                if ($type == 1) {
                    return "{$occupancyPercentage}%";
                } else {
                    return "{$occupiedRooms}";
                }
            } else {
                if ($type == 1) {
                    return "0%";
                } else {
                    return "0";
                }
            }
        }

        function fetchTotalOccupancy($formattedDay) {
            $totalOccupancyQuery = mysql_query("
				SELECT COUNT(DISTINCT r.id) AS totalOccupancy
				FROM rooms AS r
				WHERE EXISTS (
					SELECT 1
					FROM orders
					INNER JOIN order_services ON orders.id = order_services.order_id
					LEFT JOIN order_night_audits ona ON orders.id = ona.order_id
					WHERE order_services.room_id = r.id
					AND (
						(order_services.is_night_audit = 1 
						AND ona.night_audit_report_date != '0000-00-00 00:00:00' 
						AND DATE_FORMAT(ona.night_audit_report_date, '%Y-%m-%d') = '{$formattedDay}')
						OR
						(order_services.is_night_audit = 0 
						AND '{$formattedDay}' BETWEEN order_services.start_date 
						AND DATE_SUB(order_services.end_date, INTERVAL 1 DAY))
					)
					GROUP BY order_services.room_id
				)
			");

            $result = mysql_fetch_array($totalOccupancyQuery);
            return $result['totalOccupancy'];
        }
        
        function fetchTotalRooms() {
            $totalRoomsQuery = mysql_query("SELECT COUNT(id) AS total FROM rooms");
            $result = mysql_fetch_array($totalRoomsQuery);
            return $result['total'];
        }
        
        $totalRooms = fetchTotalRooms();
        ?>
        <div id="availability" style="width: 100%; overflow: auto;">
            <div class="scrollable-table">
                <table id="<?php echo $tblName; ?>" class="table">
                    <colgroup>
                        <col class="room-type">
                        <?php for ($i = 1; $i <= $daysInMonth; $i++) { echo '<col>'; } ?>
                    </colgroup>
                    <thead>
                        <tr>
                            <th class="room-type" style="padding-right: 170px;"></th> <!-- Room type column header -->
                            <?php for ($day = 1; $day <= $daysInMonth; $day++) {
                                $suffix = ($day % 10 == 1 && $day != 11) ? 'st' : (($day % 10 == 2 && $day != 12) ? 'nd' : (($day % 10 == 3 && $day != 13) ? 'rd' : 'th'));
                                echo "<th class='room-type' style='padding-right: 20px; padding-left: 20px;'>{$day}{$suffix}</th>";
                                $excelContent .= "\t" . $day . $suffix;
                            } ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $queryRoomTypes = mysql_query("SELECT id, name FROM room_types WHERE is_active = 1");
                        $excelContent .= "\t";
                        while ($fetchRoomType = mysql_fetch_array($queryRoomTypes)) {
                            echo '<tr><td class="room-type">' . $fetchRoomType['name'] . '</td>';
                            $excelContent .= "\n" . $fetchRoomType['name'];
                            for ($i = 1; $i <= $daysInMonth; $i++) {
                                $formattedDay = sprintf('%04d-%02d-%02d', $year, $col[0], $i);
                                $availableByType = fetchRoomTypeAvailability($fetchRoomType['id'], $formattedDay);
                                echo '<td class="availability-cell" data-room="' . $fetchRoomType['name'] . '" data-day="' . $i . '">' . $availableByType . '</td>';
                                $excelContent .= "\t" . $availableByType;
                            }
                            echo '</tr>';
                            
                        }

                        // Additional row for total occupancy and overall rate
                        echo '<tr><td class="room-type">Total Occupancy Room</td>';
                        $excelContent .= "\nTotal Occupancy Room";
                        for ($i = 1; $i <= $daysInMonth; $i++) {
                            $formattedDay = sprintf('%04d-%02d-%02d', $year, $col[0], $i);
                            $totalOccupancy = fetchTotalOccupancy($formattedDay);
                            $occupancyRate = ($totalRooms > 0) ? round(($totalOccupancy / $totalRooms) * 100, 0) : 0;
                            echo '<td class="total-occupancy-cell" style="font-weight: bold;">' . $totalOccupancy . '</td>';
                            $excelContent .= "\t" . $totalOccupancy;
                        }
                        echo '</tr>';
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
        <div id="availability" style="width: 100%; padding-top: 30px;">
            <div class="scrollable-table">
                <table id="<?php echo $tblName; ?>" class="table">
                    <colgroup>
                        <col class="room-type">
                        <?php for ($i = 1; $i <= $daysInMonth; $i++) { echo '<col>'; } ?>
                    </colgroup>
                    <thead>
                        <tr>
                            <th class="room-type" style="padding-right: 170px;"></th> <!-- Room type column header -->
                            <?php 
                                $excelContent .= "\n\n";
                                for ($day = 1; $day <= $daysInMonth; $day++) {
                                    $suffix = ($day % 10 == 1 && $day != 11) ? 'st' : (($day % 10 == 2 && $day != 12) ? 'nd' : (($day % 10 == 3 && $day != 13) ? 'rd' : 'th'));
                                    echo "<th style='padding-right: 20px; padding-left: 20px;'>{$day}{$suffix}</th>";
                                $excelContent .= "\t" . $day . $suffix;
                            } ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $queryRoomTypes = mysql_query("SELECT id, name FROM room_types WHERE is_active = 1");
                        $excelContent .= "\t";
                        while ($fetchRoomType = mysql_fetch_array($queryRoomTypes)) {
                            echo '<tr><td class="room-type">' . $fetchRoomType['name'] . '</td>';
                            $excelContent .= "\n" . $fetchRoomType['name'];
                            for ($i = 1; $i <= $daysInMonth; $i++) {
                                $formattedDay = sprintf('%04d-%02d-%02d', $year, $col[0], $i);
                                $availableByType = fetchRoomTypeAvailability($fetchRoomType['id'], $formattedDay, 1);
                                echo '<td class="availability-cell" data-room="' . $fetchRoomType['name'] . '" data-day="' . $i . '">' . $availableByType . '</td>';
                                $excelContent .= "\t" . $availableByType;
                            }
                            echo '</tr>';
                            
                        }

                        $totalDaysWithOccupancy = 0;
                        $sumOfOccupancyRates = 0;

                        // Additional row for total occupancy and overall rate
                        echo '<tr><td class="room-type">Total Occupancy Rate</td>';
                        $excelContent .= "\nTotal Occupancy Rate";
                        for ($i = 1; $i <= $daysInMonth; $i++) {
                            $formattedDay = sprintf('%04d-%02d-%02d', $year, $col[0], $i);
                            $totalOccupancy = fetchTotalOccupancy($formattedDay);
                            $occupancyRate = ($totalRooms > 0) ? round(($totalOccupancy / $totalRooms) * 100, 0) : 0;
                            if ($occupancyRate > 0) {
                                $totalDaysWithOccupancy++;
                                $sumOfOccupancyRates += $occupancyRate;
                            }
                            echo '<td class="total-occupancy-cell" style="font-weight: bold;">' . $occupancyRate . '%</td>';
                            $excelContent .= "\t" . $occupancyRate . '%';
                        }
                        echo '</tr>';

                        $averageOccupancy = $totalDaysWithOccupancy > 0 ? ($sumOfOccupancyRates / $totalDaysWithOccupancy) : 0;

                        echo '<tr><td class="room-type">Average Occupancy Rate</td>';
                        echo '<td style="font-weight: bold;">' . $averageOccupancy . '%</td>';
                        echo '</tr>';

                        $excelContent .= "\nAverage Occupancy Rate\t" . $averageOccupancy . '%';
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
<br />
<div class="buttons" >
    <button type="button" id="<?php echo $btnPrint; ?>" class="positive">
        <img src="<?php echo $this->webroot; ?>img/button/printer.png" alt=""/>
        <?php echo ACTION_PRINT; ?>
    </button>
    <button style="" type="button" id="<?php echo $btnExport; ?>" class="positive">
        <img src="<?php echo $this->webroot; ?>img/button/csv.png" alt=""/>
        <?php echo ACTION_EXPORT_TO_EXCEL; ?>
    </button>
</div>
<div style="clear: both;"></div>
<?php

$excelContent = chr(255).chr(254).@mb_convert_encoding($excelContent, 'UTF-16LE', 'UTF-8');
fwrite($fp,$excelContent);
fclose($fp);

?>