<?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_cash_report_summary_<?php echo $this->Session->id(session_id()); ?>.csv", "_blank");
        });
    });
</script>
<div id="<?php echo $printArea; ?>">
    <?php
    $msg = '<b style="font-size: 18px;">' . "Customer Cash Report" . '</b><br />';
    $msg .= '<b style="font-size: 16px;">' . TABLE_VIEW_BY . ': '."Cash Report Summary".'</b><br /><br />';
    $excelContent .= "CustomerCash Report"."\n";
    $excelContent .= TABLE_VIEW_BY.": Cash Report 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;
    ?>
	<!-- overflow: scroll; height: 660px; -->
	<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 "Phone Number"; ?></th>
            <th><?php echo "Room Type"; ?></th>
			<th><?php echo "Room Number"; ?></th>
			<th style="width: 120px !important;"><?php echo "Total Amount"; ?></th>
			<th><?php echo "Date"; ?></th>
			<th><?php echo "Code"; ?></th>
			<th style="width: 120px !important;"><?php echo "Received Amount"; ?></th>
			<th style="width: 120px !important;"><?php echo "Payment Method"; ?></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 "Received By"; ?></th>
        </tr>
        <?php
        // general condition
        $col = implode(',', $_POST);
        $col = explode(",", $col);
        $condition = '';
        if ($col[1] != '') {
            $condition != '' ? $condition .= ' AND ' : '';
			$condition .= '"' . dateConvert($col[1]) . '" <= DATE_FORMAT(orders.order_date, "%Y-%m-%d")';
        }
        if ($col[2] != '') {
            $condition != '' ? $condition .= ' AND ' : '';
			$condition .= '"' . dateConvert($col[2]) . '" >= DATE_FORMAT(orders.order_date, "%Y-%m-%d")';
            
        }
        $condition != '' ? $condition .= ' AND ' : '';
      	$condition .= 'orders.status BETWEEN 2 AND 5';
        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 .= 'orders.company_id=' . $col[4];
        }else{
            $condition != '' ? $condition .= ' AND ' : '';
            $condition .= 'orders.company_id IN (SELECT company_id FROM user_companies WHERE user_id = '.$user['User']['id'].')';
        }
        if ($col[5] != '') {
            $condition != '' ? $condition .= ' AND ' : '';
            $condition .= 'orders.branch_id=' . $col[5];
        }else{
            $condition != '' ? $condition .= ' AND ' : '';
            $condition .= 'orders.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 .= 'orders.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;
		$totalAmountReceive = 0;
		$totalBalance = 0;
		$subTotalAmountReceive = 0;
		$oldRoomId=0;
        $oldRoomName='';
		$totalAmountCheckOut = 0;
		$totalAmountPaid = 0;
		$oldOrderId = 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="12" style="font-size: 14px;">Service</td></tr> -->
			
            <?php
            $index=1;
            $oldCustomerId='';
            $oldCustomerName='';
            $subTotalAmount=0;
            $subTotalQty=0;
            $totalAmount=0;
            $index = 1;
			$ishasInvoice = 1;
           $query = mysql_query("SELECT
		   							orders.id AS order_id,
                                    orders.customer_id,
									front_desk_apply_deposits.created AS date,
                                    (SELECT CONCAT_WS(' ',customer_code,name) FROM customers WHERE id=orders.customer_id) AS customer_name,
									(SELECT IFNULL(mobile_number,'NA') FROM customers WHERE id=orders.customer_id) AS phone_number,
                                    (SELECT name FROM room_types WHERE id IN(SELECT room_type_id FROM rooms WHERE rooms.id = order_services.room_id)) AS room_type,
									order_services.room_id,
									(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 = front_desk_apply_deposits.created_by) AS created_by,
                                    (qty + qty_free) AS qty,
									order_services.unit_price AS pricePerRoom,
                                    start_date,
                                    end_date,
                                    rcl.kwh_start,
                                    rcl.kwh_end,
                                    start_time,
                                    end_time,
									front_desk_apply_deposits.total_deposit AS deposit_amount,
									(SELECT name FROM pos_pay_methods WHERE id=front_desk_apply_deposits.pos_pay_method_id) AS payment_method,
                                    orders.status
                                FROM orders
									INNER JOIN order_services ON orders.id=order_services.order_id
									LEFT JOIN front_desk_apply_deposits ON front_desk_apply_deposits.order_id = orders.id
									LEFT JOIN room_control_logs AS rcl ON rcl.order_id = orders.id AND orders.room_id = rcl.room_id
                                WHERE " . $condition. " AND orders.is_clean = 0
                                ORDER BY orders.id, customer_name, room_type, date ASC");
            while($data=mysql_fetch_array($query)){
                $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 if($data["status"] == "5"){
					$labelStatus = "Already Checkout";
                	$labelColor = "color: #e74c3c;";
				}
                ?>
				<?php 
					$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)){
						$invoiceData = mysql_fetch_array($queryInvoice);
						
					}
					if($oldOrderId != $data['order_id']){
						
						if($oldRoomName !=""){
							$totalAmountPaid = $invoiceData['total_amount'] - $invoiceData['total_deposit'];
					?>
							<tr>
								<td style='border-bottom:none;' colspan='6'></td>
								<td><?php echo $invoiceData['date']; ?></td>
								<td><?php echo $invoiceData['code']; ?></td>
								<td style="text-align: center;"><?php echo "$ ". number_format($invoiceData['total_amount'] - $invoiceData['total_deposit'] , 2); ?></td>
								<td style="text-align: center;"><?php echo $invoiceData['payment_method']; ?></td>
								<td style="text-align: center;"><?php echo "$ 0.00";?></td>
								<td style="text-align: center; color:red;"><?php echo "Payment Check Out"; ?></td>
								<td style="text-align: center; "><?php echo $invoiceData['created_by']; ?></td>
							</tr>
							<tr style="font-weight: bold; background-color: #74b9ff;">
								<td colspan="3" class="first" style="color: #fff; font-size: 14px;"><?php echo $invoiceData['date']; ?></td>
								<td colspan="2"></td>
								<td style="color: #fff; text-align: center; font-weight: bold;"><?php echo "$ ". number_format($totalAmount, 2); ?></td>
								<td colspan="2"></td>
								<td style="color: #fff; text-align: center; font-weight: bold;"><?php echo "$ ". number_format($totalAmountReceive + $totalAmountPaid, 2); ?></td>
								<td colspan=""></td>
								<td style="color: #fff; text-align: center; font-weight: bold;"><?php echo "$ ". number_format($totalBalance - $totalAmountPaid, 2); ?></td>
								<td colspan="2" style="color: #fff; text-align: right;font-size: 14px;text-decoration: underline;"></td>
							</tr>
						<?php
							$subTotalAmount	  	= 0;
							$totalAmount	  	= 0;
							$totalAmountReceive = 0;
							$totalBalance 		= 0;
						}
						$subTotalAmountReceive	= 0;
						$subTotalAmountReceive	= $data['deposit_amount'];
					}else{
						$ishasInvoice = 0;
						$totalAmountPaid = 0;
						$subTotalAmountReceive	+= $data['deposit_amount'];
					}
				?>
				<tr>
					<?php 
					if($oldOrderId != $data['order_id']){
					?>
						<td style='border-top:1px solid#C1DAD7;'class="first"><?php echo $index++; ?></td>
						<td style='border-top:1px solid#C1DAD7;'><?php echo $data['customer_name']; ?></td>
						<td style='border-top:1px solid#C1DAD7;'><?php echo $data['phone_number']; ?></td>
						<td style='border-top:1px solid#C1DAD7;'><?php echo $data['room_type']; ?></td>
						<td style='border-top:1px solid#C1DAD7;'><?php echo $data['room_name']; ?></td>
						<td style="text-align: center;"><?php echo "$ ". number_format($data['pricePerRoom'] * $data['qty'], 2); ?></td>
					<?php
					}else{
						echo "<td style='border-bottom:none;' colspan='6'></td>";
					}
					?>
					<td><?php echo $data['date']; ?></td>
					<td><?php echo ''; ?></td>
					<td style="text-align: center;"><?php echo "$ ". number_format($data['deposit_amount'] , 2); ?></td>
					<td style="text-align: center;"><?php echo $data['payment_method']; ?></td>
					<td style="text-align: center;"><?php echo "$ ". number_format(($data['pricePerRoom'] * $data['qty']) - $subTotalAmountReceive, 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'];
                    $oldOrderId				= $data['order_id'];
					$subTotalAmount	  		+= $data['pricePerRoom'];
					$totalAmount	  		= $data['pricePerRoom'] * $data['qty'];
					
					$oldCustomerId     	 	= $data['customer_id'];
                    $oldCustomerName  	 	= $data['customer_name'];
					
					$totalAmountCheckOut    = $invoiceData['total_amount'] -  $invoiceData['total_deposit'];
					$totalBalance 			= ($data['pricePerRoom'] * $data['qty']) - $subTotalAmountReceive;
					$totalAmountReceive	 	+= $data['deposit_amount'];
					$oldRoomId			 	= $data['room_id'];
					$oldRoomName		 	= $data['room_name'];
                }
                if(mysql_num_rows($query)){ 
					if($ishasInvoice==1){
                ?>
               <tr>
					<td style='border-bottom:none;' colspan='6'></td>
					<td><?php echo $invoiceData['date']; ?></td>
					<td><?php echo $invoiceData['code']; ?></td>
					<td style="text-align: center;"><?php echo "$ ". number_format($invoiceData['total_amount'] - $invoiceData['total_deposit'] , 2); ?></td>
					<td style="text-align: center;"><?php echo $invoiceData['payment_method']; ?></td>
					<td style="text-align: center;"><?php echo "$ 0.00";?></td>
					<td style="text-align: center; color:red;"><?php echo "Payment Check Out"; ?></td>
					<td style="text-align: center; "><?php echo $invoiceData['created_by']; ?></td>
				</tr>
			<?php }?>
                <tr style="font-weight: bold; background-color: #74b9ff;">
					<td colspan="3" class="first" style="color: #fff; font-size: 14px;"><?php echo $invoiceData['date']; ?></td>
					<td colspan="2"></td>
					<td style="color: #fff; text-align: center; font-weight: bold;"><?php echo "$ ". number_format($totalAmount, 2); ?></td>
					<td colspan="2"></td>
					<td style="color: #fff; text-align: center; font-weight: bold;"><?php echo "$ ". number_format($totalAmountReceive + $totalAmountPaid, 2); ?></td>
					<td colspan=""></td>
					<td style="color: #fff; text-align: center; font-weight: bold;"><?php echo "$ ". number_format($totalBalance - $totalAmountPaid, 2); ?></td>
					<td colspan="2" style="color: #fff; 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);

?>