<?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/customer_check_in_summary_" . $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/customer_check_in_summary_<?php echo $this->Session->id(session_id()); ?>.csv", "_blank");
        });
    });
</script>
<div id="<?php echo $printArea; ?>">
    <?php
    $msg = '<b style="font-size: 18px;">' . "Room Energy Usage" . '</b><br />';
    $msg .= '<b style="font-size: 16px;">' . TABLE_VIEW_BY . ': ' . "Room Energy Usage" . '</b><br /><br />';
    $excelContent .= "Customer Check In/Out" . "\n";
    $excelContent .= TABLE_VIEW_BY . ": Room Energy Usage\n\n";
    if ($_POST['date_from'] != '') {
        $msg .= REPORT_FROM . ': ' . $_POST['date_from'];
        $excelContent .= REPORT_FROM . ': ' . $_POST['date_from'];
    }
    if ($_POST['date_to'] != '') {
        $msg .= ' ' . REPORT_TO . ': ' . $_POST['date_to'];
        $excelContent .= ' ' . REPORT_TO . ': ' . $_POST['date_to'] . "\n\n";
    }
    echo $this->element('/print/header-report', array('msg' => $msg));

    ?>
    <table id="<?php echo $tblName; ?>" class="table_report">
        <tr>
            <th style="width: 120px !important;" class="first">
                <?php echo TABLE_NO; ?>
            </th>
            <th>
                <?php echo "Room Type"; ?>
            </th>
            <th>
                <?php echo "Floor"; ?>
            </th>
            <th>
                <?php echo "Room Name"; ?>
            </th>
            <th style="width: 150px !important;">
                <?php echo "Swtich On"; ?>
            </th>
            <th style="width: 150px !important;">
                <?php echo "Swtich off"; ?>
            </th>
            <th style="width: 200px !important;">
                <?php echo "Total turn period"; ?>
            </th>
            <th style="width: 80px !important;">
                <?php echo "Swtich on meter(KWH)"; ?>
            </th>
            <th style="width: 80px !important;">
                <?php echo "Swtich off meter(KWH)"; ?>
            </th>
            <th style="width: 80px !important;">
                <?php echo "Energy consumed(KWH)"; ?>
            </th>
            <th style="width: 120px !important;">
                <?php echo "Type"; ?>
            </th>
            <th style="width: 120px !important;">
                <?php echo "Status"; ?>
            </th>
        </tr>
        <?php
        // general condition
        $col = implode(',', $_POST);
        $col = explode(",", $col);
        $condition = '';
        if ($col[1] != '') {
            $condition != '' ? $condition .= ' AND ' : '';
            $condition .= '"' . dateConvert($col[1]) . '" <= DATE(on_date)';
        }
        if ($col[2] != '') {
            $condition != '' ? $condition .= ' AND ' : '';
            $condition .= '"' . dateConvert($col[2]) . '" >= DATE(on_date)';
        }
        $condition != '' ? $condition .= ' AND ' : '';
        if ($col[3] == '') {
            $condition .= 'room_control_logs.status>=0';
        } else {
            $condition .= 'room_control_logs.status=' . $col[3];
        }
        if ($col[4] != '') {
            $condition != '' ? $condition .= ' AND ' : '';
            $condition .= 'room_control_logs.room_type_id =' . $col[4] . '';
        }
        if ($col[5] != '') {
            $condition != '' ? $condition .= ' AND ' : '';
            $condition .= 'room_control_logs.floor_id =' . $col[5] . '';
        }
        if ($col[6] != '') {
            $condition != '' ? $condition .= ' AND ' : '';
            $condition .= 'room_control_logs.is_clean =' . $col[6] . '';
        }
        // if ($col[5] != '') {
        //     $condition != '' ? $condition .= ' AND ' : '';
        //     $condition .= 'company_id=' . $col[5];
        // }else{
        //     $condition != '' ? $condition .= ' AND ' : '';
        //     $condition .= 'company_id IN (SELECT company_id FROM user_companies WHERE user_id = '.$user['User']['id'].')';
        // }
        // if ($col[6] != '') {
        //     $condition != '' ? $condition .= ' AND ' : '';
        //     $condition .= 'branch_id=' . $col[6];
        // }else{
        //     $condition != '' ? $condition .= ' AND ' : '';
        //     $condition .= 'branch_id IN (SELECT branch_id FROM user_branches WHERE user_id = '.$user['User']['id'].')';
        // }
        // if ($col[7] != '') {
        //     $condition != '' ? $condition .= ' AND ' : '';
        //     $condition .= 'created_by=' . $col[7];
        // }
        // if ($col[8] != '') {
        //     $condition != '' ? $condition .= ' AND ' : '';
        //     $condition .= 'customer_id=' . $col[8];
        // }
        
        // declare
        $grandTotalAmount = 0;
        $excelContent .= "\n" . 'Product'; ?>
        <!-- <tr style="font-weight: bold;"><td class="first" colspan="6" style="font-size: 14px;">Product</td></tr> -->
        <?php
        $index = 1;
        $arrCode = array();
        $arrProduct = array();
        $arrCustomer = array();
        $arrLocation = array();
        $oldCustomerId = '';
        $oldCustomerName = '';
        $subTotalAmount = 0;
        $subTotalQty = 0;
        $totalAmount = 0;
        $totalQty = 0;
        // if ($col[7] == '' && $col[8] == '' && $col[9] == '') {
            $excelContent .= "\n\n" . 'Service'; ?>
            <tr>
                <td colspan="6">&nbsp;</td>
            </tr>
            <tr style="font-weight: bold;">
                <td class="first" colspan="6" style="font-size: 14px;">Service</td>
            </tr>
            <?php
            $index = 1;
            $oldCustomerId = '';
            $oldCustomerName = '';
            $subTotalAmount = 0;
            $subTotalQty = 0;
            $totalAmount = 0;
            $index = 1;
            $query = mysql_query("SELECT
                                    rooms.name AS roomName,
                                    room_types.name AS typeName,
                                    floors.name AS floorName, 
                                    on_date, 
                                    off_date, 
                                    kwh_start, 
                                    kwh_end, 
                                    (kwh_end - kwh_start) AS consumed,
									room_control_logs.energy_consume_rate_id,
                                    room_control_logs.is_clean,
                                    room_control_logs.status
                                    FROM room_control_logs 
                                        INNER JOIN rooms ON rooms.id=room_control_logs.room_id
                                        INNER JOIN floors ON floors.id=room_control_logs.floor_id 
                                        INNER JOIN room_types ON room_types.id=room_control_logs.room_type_id 
                                WHERE " . $condition . " AND room_control_logs.device_id !=0
                                ORDER BY room_control_logs.on_date DESC");
            while ($data = mysql_fetch_array($query)) {

                $subTotalQty = 0;
                $labelStatus = "OFF";
                $labelType = "Occupied Session";
                $labelColor = "color: #e74c3c;";
                if ($data["status"] == "1") {
                    $labelStatus = "ON";
                    $labelColor = "color: #2ecc71;";
                }
                if ($data["is_clean"] == "1") {
                    $labelType = "Clean Session";
                } else if ($data["is_clean"] == "2") {
                    $labelType = "Unknown Session";
                }
                $startDate = new DateTime($data['on_date']);
                $endDate = new DateTime($data['off_date']);
                $dateDiff = $startDate->diff($endDate);
				$consumed = $data['consumed'];
				$range = "";
				$energyCal = "";
				if ($consumed > 0 && $consumed <= 10) {
					$range = "Tier 1";
					$energyCal = ($consumed * 380) + ($consumed * 480) + ($consumed * 610);
				} elseif ($consumed <= 50) {
					$range = "Tier 2";
					$energyCal = ($consumed * 380) + ($consumed * 480) + ($consumed * 610);
				} elseif ($consumed <= 200) {
					$range = "Tier 3";
					$energyCal = ($consumed * 380) + ($consumed * 480) + ($consumed * 610);
				} else {
					$range = "Tier 4";
					$energyCal = ($consumed * 380) + ($consumed * 480) + ($consumed * 610);
				}

				$energyConsumeRates = mysql_query("SELECT rate FROM energy_consume_rates WHERE name =  LIKE '".$range."' AND is_active = 1");
				$fetchEnergyConsumeRate = mysql_fetch_array($energyConsumeRates);
                ?>

                <tr>
                    <td class="first">
                        <?php echo $index++; ?>
                    </td>
                    <td>
                        <?php echo $data['typeName']; ?>
                    </td>
                    <td>
                        <?php echo $data['floorName']; ?>
                    </td>
                    <td>
                        <?php echo $data['roomName']; ?>
                    </td>
                    <td style="text-align: center;">
                        <?php echo $data['on_date']; ?>
                    </td>
                    <td style="text-align: center;">
                        <?php echo $data['off_date']; ?>
                    </td>
                    <td style="text-align: center;">
                        <?php echo $dateDiff->format('%H h, %I mn, %S s'); ?>
                    </td>
                    <td style="text-align: center;">
                        <?php echo $data['kwh_start']; ?>
                    </td>
                    <td style="text-align: center;">
                        <?php echo $data['kwh_end']; ?>
                    </td>
                    <td style="text-align: center;">
                        <?php echo $data['consumed']; ?>
                    </td>
                    <td style="text-align: center;">
                        <?php echo $labelType ?>
                    </td>
					<td style="text-align: center;">
                        <?php echo $fetchEnergyConsumeRate['rate']; ?>
                    </td>
                    <td style="text-align: center; <?php echo $labelColor; ?>">
                        <?php echo $labelStatus; ?>
                    </td>
                </tr>
            <?php
            }
       // } ?>
    </table>
</div>
<br />
<div class="buttons" style="display:none">
    <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 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);

?>