<?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;">' . "Customer  In-House" . '</b><br />';
    $msg .= '<b style="font-size: 16px;">' . TABLE_VIEW_BY . ': '."Customer  In-House Summary".'</b><br /><br />';
    $excelContent .= "Customer  In-House"."\n";
    $excelContent .= TABLE_VIEW_BY.": Customer  In-House Summary\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));
    $excelContent .= TABLE_NO."\t".TABLE_CUSTOMER_NAME."\t".TABLE_PRODUCT_NAME."\t".TABLE_QTY."\t".TABLE_UOM."\t".GENERAL_AMOUNT;
    ?>
	<div style="">
		<table id="<?php echo $tblName; ?>" class="table" style="">
			<tr>
				<th style="width:100px;" class="first"><?php echo TABLE_NO; ?></th>
				<th style="width: 280px !important;"><?php echo TABLE_CUSTOMER_NAME; ?></th>
				<th style="width: 180px !important;"><?php echo "Room Type"; ?></th>
				<th style="width: 180px !important;"><?php echo "Room Name"; ?></th>
				<th style="width: 120px !important;"><?php echo "Stay"; ?></th>
				<th style="width: 120px !important;"><?php echo "Check In"; ?></th>
				<th style="width: 120px !important;"><?php echo "Check Out"; ?></th>
				<!-- <th style="width: 80px !important;"><?php echo "Energy(KWH)"; ?></th> -->
			</tr>
			<?php
			// general condition
			$col = implode(',', $_POST);
			$col = explode(",", $col);
			$condition = ' orders.status = 3';

			if ($col[1] != '') {
				$condition != '' ? $condition .= ' AND ' : '';
				$condition .= ' ("' . dateConvert($col[1]) . '" > DATE(order_services.start_date) AND "' . dateConvert($col[1]) . '" < DATE(order_services.end_date))';
			}
			if ($col[2] != '') {
				$condition != '' ? $condition .= ' AND ' : '';
				$condition .= '("' . dateConvert($col[2]) . '" > DATE(order_services.start_date) OR "' . dateConvert($col[2]) . '" < DATE(order_services.end_date))';
				
			}

			if ($col[3] != '') {
				$condition != '' ? $condition .= ' AND ' : '';
				$condition .= '(SELECT rt.id FROM room_types AS rt WHERE id IN (SELECT room_type_id FROM rooms WHERE id = orders.room_id AND room_type_id ='.$col[3].'))';
			}
			if ($col[4] != '') {
				$condition != '' ? $condition .= ' AND ' : '';
				$condition .= 'company_id=' . $col[4];
			}else{
				$condition != '' ? $condition .= ' AND ' : '';
				$condition .= 'company_id IN (SELECT company_id FROM user_companies WHERE user_id = '.$user['User']['id'].')';
			}
			if ($col[5] != '') {
				$condition != '' ? $condition .= ' AND ' : '';
				$condition .= 'branch_id=' . $col[5];
			}else{
				$condition != '' ? $condition .= ' AND ' : '';
				$condition .= 'branch_id IN (SELECT branch_id FROM user_branches WHERE user_id = '.$user['User']['id'].')';
			}
			if ($col[6] != '') {
				$condition != '' ? $condition .= ' AND ' : '';
				$condition .= 'created_by=' . $col[6];
			}
			if ($col[7] != '') {
				$condition != '' ? $condition .= ' AND ' : '';
				$condition .= 'customer_id=' . $col[7];
			}
			
			// 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;
			$date = date("Y-m-d");
			// if($col[7] == '' && $col[8] == '' && $col[9] == ''){ 
				$excelContent .= "\n\n".'Service'; ?>
				<!-- <tr><td style="" colspan="6">&nbsp;</td></tr> -->
				<tr style="font-weight: bold;"><td class="first" colspan="8" style="font-size: 14px; ">Service</td></tr>
				<?php
				$index=1;
				$oldCustomerId='';
				$oldCustomerName='';
				$subTotalAmount=0;
				$subTotalQty=0;
				$totalAmount=0;
				$index = 1;
			$query = mysql_query("SELECT
										orders.id AS orderId,
										customer_id,
										(SELECT name FROM customers WHERE id=customer_id) AS customer_name,
										(SELECT name FROM booking_agencies WHERE booking_agencies.id=orders.booking_agency_id) AS agency,
										(SELECT name FROM rooms WHERE id IN(SELECT room_id FROM order_services WHERE orders.room_id = order_services.room_id)) AS room_name,
										(SELECT abbr FROM room_types WHERE id IN(SELECT room_type_id FROM rooms WHERE rooms.id = order_services.room_id)) AS room_type,
										(qty + qty_free) AS qty,
										order_services.unit_price AS pricePerRoom,
										order_services.start_date,
										order_services.end_date,
										order_services.start_time,
										order_services.end_time,
										orders.status
									FROM orders
										INNER JOIN order_services ON orders.id=order_services.order_id
									WHERE " . $condition. " AND orders.is_clean = 0
									ORDER BY room_name,customer_name, room_type");
				while($data=mysql_fetch_array($query)){
					$arrCustomer[] = $data['orderId'];
					$subTotalQty     =0;
					$excelContent .= "\n".$index."\t".trim(preg_replace('/[\t|\s]/', '', $data['customer_name']))."\t".$data['room_type']."\t".number_format($data['qty'], 0)."\t\t"; 
				
					if($data["status"] == "3" && $data['start_date'] == $date ){
						$labelStatus = "Arrival";
						$labelColor = "color: #2ecc71;";
					}else if($data["status"] == "3" ){
						$labelStatus = "Departure";
						$labelColor = "color: #8e44ad";
					}
					?>

					<tr style="border:1px solid black;">
						<td class="first" style="text-align: center; "><?php echo $index++; ?></td>
						<td style=""><?php echo $data['customer_name'] ." - ". $data['agency']; ?></td>
						<td style=""><?php echo $data['room_type']; ?></td>
						<td style=""><?php echo $data['room_name']; ?></td>
						<td style="text-align: center; "><?php echo number_format($data['qty'], 0); ?></td>
						<td style="text-align: center; "><?php echo $data['start_date']; ?></td>
						<td style="text-align: center; "><?php echo $data['end_date']; ?></td>
						<!-- <td style="text-align: center; "><?php echo $data['kwh_end'] !=0 ? $data['kwh_end'] - $data['kwh_start'] : 0; ?></td> -->
						<!-- <td style="text-align: center; <?php echo $labelColor;?>"><?php echo $labelStatus; ?></td> -->
					</tr>
					<?php
						$subTotalQty      += $data['qty'];
						$totalQty         += $data['qty'];
						$oldCustomerId     = $data['customer_id'];
						$oldCustomerName   = $data['customer_name'];
						$subTotalAmount	  +=$data['pricePerRoom'];
						$totalAmount	  +=$data['pricePerRoom'] * $data['qty'];
					}
					if(mysql_num_rows($query)){ 
						$excelContent .= "\n".'Total'.trim(preg_replace('/[\t|\s]/', '', $oldCustomerName))."\t\t\t".number_format($subTotalQty, 0)."\t\t".number_format($subTotalAmount, $priceDecimal); ?>
					<?php $excelContent .= "\n".'Total'."\t\t\t\t".number_format($totalQty, 0)."\t\t"; ?>
					<tr style="font-weight: bold;">
						<td class="first" style="font-size: 14px;">Total Service</td>
						<td style="text-align: left; font-weight: bold;"><?php echo sizeof(array_unique($arrCustomer)); ?></td>
						<td></td>
						<td></td>
						<td style="text-align: center; font-weight: bold;"><?php echo number_format($totalQty, 0); ?></td>
						<td></td>
						<td></td>
						<!-- <td></td> -->
						<!-- <td style="text-align: right;font-size: 14px;text-decoration: underline;"></td> -->
					</tr>
				<?php 
					}
			// }?>
		</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="display:none" 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);

?>