<?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();
        });

		$(".btnReprintReceiptPos").unbind("click").click(function(event){
			event.preventDefault();
			var id = $(this).attr('rel');
			var url = '';
			// var printVat = '<button type="submit" class="positive reprintInvoiceSalesVat" ><img src="<?php echo $this->webroot; ?>img/button/printer.png" alt=""/><span class="txtReprintInvoiceSalesVat"><?php echo ACTION_REPRINT_INVOICE; ?> VAT</span></button>';
			
			$("#dialog").html('<div class="buttons"><button type="submit" class="positive printCheckInform" ><img src="<?php echo $this->webroot; ?>img/button/printer.png" alt=""/><span class="txtPrintCheckInForm"><?php echo "Check In Form"; ?></span></button><button type="submit" class="positive reprintInvoiceSalesVat" style="display:none;"><img src="<?php echo $this->webroot; ?>img/button/printer.png" alt=""/><span class="txtPrintInvoiceTax"><?php echo ACTION_PRINT_TAX_INVOICE; ?></span></button><button type="submit" class="positive printInvoiceCommercial" ><img src="<?php echo $this->webroot; ?>img/button/printer.png" alt=""/><span class="txtPrintInvoiceCommercial"><?php echo ACTION_PRINT_COMMERCIAL_INVOICE; ?></span></button></div><div style="padding-top: 40px;"><label style="font-size:11px;"for="showRate">Show Rate</label><input type="checkbox" name="showRate" id="showRate" value="1"></div>');
			
			$(".printCheckInform").click(function () {
				var checkFilter = $("input[name='showRate']:checked").val();
				$.ajax({
					type: "POST",
					url: "<?php echo $this->base . '/point_of_sales'; ?>/printCheckInForm/" + id + "/" + checkFilter,
					beforeSend: function () {
						$(".loader").attr('src', '<?php echo $this->webroot; ?>img/layout/spinner.gif');
					},
					success: function (printInvoiceResult) {
						var 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(printInvoiceResult);
						w.document.close();
						$(".loader").attr('src', '<?php echo $this->webroot; ?>img/layout/spinner-placeholder.gif');
					}
				});
			});

			$(".printInvoiceCommercial").click(function () {
				$.ajax({
					type: "POST",
					url: "<?php echo $this->base . '/point_of_sales'; ?>/printReceiptCommercial/" + id,
					beforeSend: function () {
						$(".loader").attr('src', '<?php echo $this->webroot; ?>img/layout/spinner.gif');
					},
					success: function (printInvoiceResult) {
						var 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(printInvoiceResult);
						w.document.close();
						$(".loader").attr('src', '<?php echo $this->webroot; ?>img/layout/spinner-placeholder.gif');
					}
				});
			});
			$(".reprintInvoiceSalesVat").click(function () {
				$.ajax({
					type: "POST",
					url: "<?php echo $this->base . '/point_of_sales'; ?>/printReceiptTax/" + id,
					beforeSend: function () {
						$(".loader").attr('src', '<?php echo $this->webroot; ?>img/layout/spinner.gif');
					},
					success: function (printInvoiceResult) {
						var 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(printInvoiceResult);
						w.document.close();
						$(".loader").attr('src', '<?php echo $this->webroot; ?>img/layout/spinner-placeholder.gif');
					}
				});
			});
			$("#dialog").dialog({
				title: '<?php echo DIALOG_INFORMATION; ?>',
				resizable: false,
				modal: true,
				width: 'auto',
				height: 'auto',
				position: 'center',
				open: function (event, ui) {
					$(".ui-dialog-buttonpane").show();
				},
				buttons: {
					'<?php echo ACTION_CLOSE; ?>': function () {
						$(this).dialog("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 Check In/Out" . '</b><br />';
    $msg .= '<b style="font-size: 16px;">' . TABLE_VIEW_BY . ': '."Check In/Out Summary".'</b><br /><br />';
    $excelContent .= "Customer Check In/Out"."\n";
    $excelContent .= TABLE_VIEW_BY.": Check In/Out 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">
			<tr>
				<th style="width: 120px !important;" class="first"><?php echo TABLE_NO; ?></th>
				<th><?php echo TABLE_CUSTOMER_NAME; ?></th>
				<th><?php echo "Source"; ?></th>
				<th><?php echo "Phone Number"; ?></th>
				<th><?php echo "Room Type"; ?></th>
				<th><?php echo "Room No"; ?></th>
				<th style="width: 120px !important;"><?php echo "Check-In"; ?></th>
				<th style="width: 120px !important;"><?php echo "Check-Out"; ?></th>
				<th style="width: 120px !important;"><?php echo "No. Night"; ?></th>
				<th style="width: 120px !important;"><?php echo "Price"; ?></th>
				<th style="width: 120px !important;"><?php echo "Total Price"; ?></th>
				<th style="width: 120px !important;"><?php echo "Dis Amount"; ?></th>
				<th style="width: 120px !important;"><?php echo "Rec Amount"; ?></th>
				<th style="width: 120px !important;"><?php echo "Balance"; ?></th>
				<th style="width: 120px !important;"><?php echo "Status"; ?></th>
				<th style="width: 120px !important;"><?php echo "Created By"; ?></th>
			</tr>
			<?php
			// general condition
			$col = implode(',', $_POST);
			$col = explode(",", $col);
			$condition = '';
			if ($col[1] != '') {
				$condition != '' ? $condition .= ' AND ' : '';
				if($col[3] != "" && $col[3] == 3){
					$condition .= '"' . dateConvert($col[1]) . '" <= DATE_FORMAT(order_services.start_date, "%Y-%m-%d")';
				}else{
					$condition .= '"' . dateConvert($col[2]) . '" <= DATE_FORMAT(order_services.end_date, "%Y-%m-%d")';
				}
			}
			if ($col[2] != '') {
				$condition != '' ? $condition .= ' AND ' : '';
				if($col[3] != "" && $col[3] == 3){
					$condition .= '"' . dateConvert($col[2]) . '" >= DATE_FORMAT(order_services.start_date, "%Y-%m-%d")';
				}else{
					$condition .= '"' . dateConvert($col[2]) . '" >= DATE_FORMAT(order_services.end_date, "%Y-%m-%d")';
				}
				
			}
			$condition != '' ? $condition .= ' AND ' : '';
			if ($col[3] == '') {
				$condition .= 'orders.status>2';
			} else {
				if($col[3] == 3){
					$condition .= 'orders.status IN(3,5)';
				}else{
					$condition .= 'orders.status=' . $col[3];
				}
			}
			if ($col[4] != '') {
				$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[4].'))';
			}
			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;
			$totalAmountReceive = 0;
			$totalBalance = 0;
			$discount = 0;
			$totalAmountPaid = 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="16" style="font-size: 14px;">Service</td></tr> -->
				
				<?php
				$index=1;
				$oldCustomerId='';
				$oldCustomerName='';
				$subTotalAmount=0;
				$subTotalQty=0;
				$totalAmount=0;
				$index = 1;
				$query = mysql_query("SELECT
										customer_id,
										orders.id AS order_id,
										(SELECT CONCAT_WS(' ',customer_code,name) FROM customers WHERE id=customer_id) AS customer_name,
										(SELECT IFNULL(mobile_number,'NA') FROM customers WHERE id=customer_id) AS phone_number,
										(SELECT name FROM booking_agencies WHERE id=booking_agency_id) AS agency_name,
										(SELECT name FROM room_types WHERE id IN(SELECT room_type_id FROM rooms WHERE rooms.id = order_services.room_id)) AS room_type,
										(SELECT name FROM rooms WHERE rooms.id=order_services.room_id) AS room_name,
										(SELECT CONCAT_WS(' ',first_name, last_name) FROM users WHERE users.id = orders.created_by) AS created_by,
										(qty + qty_free) AS qty,
										order_services.unit_price AS pricePerRoom,
										order_services.discount_amount,
										order_services.start_date,
										order_services.end_date,
										
										order_services.start_time,
										order_services.end_time,
										(SELECT SUM(total_deposit) FROM front_desk_apply_deposits WHERE is_active = 1 AND front_desk_apply_deposits.order_id = orders.id) AS total_deposit,
										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)){

					$queryInvoice = mysql_query("SELECT created AS date,
												so_code AS code, 
												total_amount,
												total_deposit,
												(SELECT name FROM pos_pay_methods WHERE id=sales_orders.pos_pay_method_id) AS payment_method,
												(SELECT CONCAT_WS(' ',first_name, last_name) FROM users WHERE users.id = sales_orders.created_by) AS created_by,
												sales_order_services.unit_price,
												sales_order_services.qty
												FROM sales_orders 
												INNER JOIN sales_order_services ON sales_order_services.sales_order_id = sales_orders.id
												WHERE sales_orders.status = 2 
												AND sales_orders.order_id = {$data['order_id']}");
					if(mysql_num_rows($queryInvoice)){
						$isInvoice = 1;
						$invoiceData = mysql_fetch_array($queryInvoice);
						$totalAmountPaid = $invoiceData['total_amount'] - $invoiceData['total_deposit'];
					}

					$arrCustomer[] = $data['customer_name'];
					$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"){
						$labelStatus = "Stay in";
						$labelColor = "color: #2ecc71;";
					}else if($data["status"] == "2"){
						$labelStatus = "Reservation";
						$labelColor = "color: #8e44ad";
					}else{
						$labelStatus = "Already Checkout";
						$labelColor = "color: #e74c3c;";
					}
					?>
						<tr>
							<td class="first"><?php echo $index++; ?></td>
							<td><?php echo '<a href="" class="btnReprintReceiptPos" rel="' . $data['order_id'] . '">' . $data['customer_name'] . '</a>' ; ?></td>
							<td><?php echo $data['agency_name']; ?></td>
							<td><?php echo $data['phone_number']; ?></td>
							<td><?php echo $data['room_type']; ?></td>
							<td><?php echo $data['room_name']; ?></td>
							<td style="text-align: center;"><?php echo $data['start_date'] ." ". substr($data['start_time'], 0, 5); ?></td>
							<td style="text-align: center;"><?php echo $data['end_date'] ." ". substr($data['end_time'], 0, 5); ?></td>
							<td style="text-align: center;"><?php echo number_format($data['qty'], 0); ?></td>
							<td style="text-align: center;"><?php echo "$ ".number_format($data['pricePerRoom'], 2); ?></td>
			
							<td style="text-align: center;"><?php echo "$ ". number_format($data['pricePerRoom'] * $data['qty'], 2); ?></td>
							<td style="text-align: center;"><?php echo "$ ".number_format($data['discount_amount'], 2); ?></td>
							<td style="text-align: center;"><?php echo "$ ". number_format($data['total_deposit'] + $totalAmountPaid , 2); ?></td>
							<td style="text-align: center;"><?php echo "$ ". number_format(($data['pricePerRoom'] * $data['qty']) - $data['total_deposit'] - $data['discount_amount'], 2); ?></td>
							<td style="text-align: center; <?php echo $labelColor;?>"><?php echo $labelStatus; ?></td>
							<td style="text-align: center; "><?php echo $data['created_by']; ?></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'];
						$totalAmountReceive += $data['total_deposit'];
						$totalBalance 		+= ($data['pricePerRoom'] * $data['qty']) - $data['total_deposit'];
						$discount 			 = $data['discount_amount'];
					}
					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 Service'."\t\t\t\t".number_format($totalQty, 0)."\t\t"; ?>
					<tr style="font-weight: bold;">
						<td colspan="" class="first" style="font-size: 14px;">Total</td>
						<td style="text-align: left; font-weight: bold;"><?php echo sizeof(array_unique($arrCustomer)); ?></td>
						<td colspan="6"></td>
						<td style="text-align: center; font-weight: bold;"><?php echo number_format($totalQty, 0); ?></td>
						<td style="text-align: center; font-weight: bold;"><?php echo "$ ". number_format($subTotalAmount, 2); ?></td>
						<td style="text-align: center; font-weight: bold;"><?php echo "$ ". number_format($totalAmount, 2); ?></td>
						<td></td>
						<td style="text-align: center; font-weight: bold;"><?php echo "$ ". number_format($totalAmountReceive + $totalAmountPaid, 2); ?></td>
						<td style="text-align: center; font-weight: bold;"><?php echo "$ ". number_format($totalBalance - $totalAmountPaid - $discount, 2); ?></td>
						<td colspan="2" 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 type="button" id="<?php echo $btnExport; ?>" class="positive"  style="display:none;">
        <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);

?>