<?php 
	date_default_timezone_set('Asia/Kuala_Lumpur');

    if(isset($_GET['date'])){
        $getDate = $_GET['date'];
    }else{
        header("Location: ?pagecontent=reservation_checklist&date=".date("Y-m-d"));
    }
	

	if(!isset($_GET['rvno']) && !isset($_GET['date'])){exit;}
?>

<div class="right_col" role="main">
	<div class="">
		<div class="page-title">
			<div class="title_left">
				<h3>Checklist - <?php echo $getDate;?> | <a href="?pagecontent=communication"><button class="btn btn-primary">Update Comm</button></a></h3>
			</div>
		</div>
		<div class="clearfix"></div>
		
		<div class="row">
			<div class="col-md-12 col-sm-12 col-xs-12">
				<div class="x_panel">
					<div class="x_content">
						<table id="datatable" class="table table-striped table-bordered">
							<thead>
								<tr>
								    <th>Reservation</th>
									<th>Guest</th>
									<th>Room</th>
                                    <?php
                                        $resultCM = mysqli_query($conn,"SELECT * FROM communication_materials");
                                        while($rowCM = mysqli_fetch_assoc($resultCM)){
                                            if($rowCM['cm_message'] == NULL){break;} 
                                    ?>
									<th><?php echo $rowCM['cm_title']; ?></th>
                                    <?php } ?>
								</tr>
							</thead>
							<tbody>
								<?php
								
									if(isset($_REQUEST['date'])){
										// $sql = "SELECT * FROM reservation WHERE '$getDate' BETWEEN rv_ci_date AND DATE_SUB(rv_co_date,INTERVAL 1 DAY) ORDER BY rv_ci_date DESC";
										$sql = "SELECT * FROM reservation WHERE rv_ci_date='$getDate' AND rv_status >= 2 ORDER BY rv_ci_date DESC";
									}
								
									$result = mysqli_query($conn,$sql);
									
									while($row = mysqli_fetch_array($result))
									{
								?>
								<tr style="<?php if($row['rv_status'] == 0 && $row['rv_ci_date'] == $getDate){echo 'background-color:#FFD5CC; font-weight: bold;';}elseif($row['rv_status'] > 1 && $row['r_id']){echo 'background-color:#D6FFD1; font-weight: bold;'; }elseif($row['rv_status'] > 1 && !$row['r_id']){echo 'background-color:#FFFAB3; font-weight: bold;';} ?>">
								    <td>
                                        <a onClick="navigator.clipboard.writeText('<?php echo $row['rv_no']; ?>')"><?php echo $row['rv_no']; ?></a><br>
                                        <?php
                                            echo platformTitle($row['rv_platform']); echo "<br>";
                                            echo reservationByOwnerIdToTitle($row['rv_byowner']);
                                        ?>
                                    </td>
									
									<td><a href="?pagecontent=reservation_checklist&rv=<?php echo $row['rv_id']; ?>"><?php echo $row['rv_guest']; ?></a></td>
									<td><a href="?pagecontent=report_profit_room&room=<?php echo $row['r_id']; ?>"><?php if($row['r_id']){echo getDetailFromTable('properties',getDetailFromTable('rooms',$row['r_id'])['p_id'])['pty_code']." ".getDetailFromTable('rooms',$row['r_id'])[1];} ?></a></td>
									
                                    <?php
                                        $resultCM = mysqli_query($conn,"SELECT * FROM communication_materials");
                                        while($rowCM = mysqli_fetch_assoc($resultCM))
                                        { 
                                            if($rowCM['cm_message'] == NULL){break;}
                                        
                                    ?>
                                    <td>
                                        <?php 
                                            if(resendBtn($row['rv_id'],$rowCM['cm_id'])){ ?>
                                                <a href="?pagecontent=reservation_checklist&date=<?php echo $getDate; ?>&control=<?php echo $rowCM['cm_id']; ?>&rv=<?php echo $row['rv_id']; ?>" target="_blank"><button class="btn btn-warning btn-block btn-xs">RESEND</button>
                                                <?php }else{ ?>
                                                <a href="?pagecontent=reservation_checklist&date=<?php echo $getDate; ?>&control=<?php echo $rowCM['cm_id']; ?>&rv=<?php echo $row['rv_id']; ?>" target="_blank"><button class="btn btn-primary btn-block btn-xs">SEND</button>
                                            <?php } 
                                        ?>
                                    </td>
                                    <?php } ?>
								</tr>
								<?php
									}
								?>
						</table>
					</div>
				</div>
			</div>
        </div>
		<div class="clearfix"></div>
		
    </div>
</div>

<?php
    function resendBtn($reservationId,$commControlId){
        global $conn;
        $result = mysqli_query($conn,"SELECT * FROM communication_control WHERE rv_id=$reservationId AND cm_id=$commControlId");
        return mysqli_num_rows($result);
    }

    if(isset($_REQUEST['greeting'])){
        $getRVId = $_REQUEST['greeting'];
        $getRVContact = getDetailByTable('reservation',$getRVId)['rv_contact'];

        $curl = curl_init();

        curl_setopt_array($curl, array(
        //   CURLOPT_URL => 'https://app.respond.io/api/v1/message/sendContent/'.$getRVContact,
        CURLOPT_URL => 'https://app.respond.io/api/v1/message/sendContent/'.$getRVContact,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>'{
            "body": [
                {
                    "type": "whatsapp_template",
                    "template": {
                        "name": "welcome_message2",
                        "languageCode": "en",
                        "components": [
                            {
                                "type": "body",
                                "text": "Dear, welcome to DzV Homestay. I am Azmil and I will assist you through check in with DzV Homestay. Kindly please provide booking/confirmation/reservation no. Thank you."
                            }
                        ]
                    }
                }
            ]
        }',
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Authorization: Bearer 35aea252ed4d90aa6904c44ff9837f232ff51c6dd6b628318127b24b214730b30bbd793fac5cc135853d85cbc927c25d8401f36e17ac0f17c9abcd7b8c4e1ef1'
        ),
        ));
        
        $response = curl_exec($curl);
        
        curl_close($curl);
        
        // $response = json_decode($response,TRUE);
        // sendMessage2(26236173,$response['message']);

        mysqli_query($conn,"UPDATE reservation SET rv_wa_greeting=1 WHERE rv_id=$getRVId");

        header('Location: https://app.respond.io/space/80806/message');
        
        exit();
    }

    if(isset($_REQUEST['control'])){
        $cmId = $_GET['control'];
        $rvId = $_GET['rv'];
        $getRVContact = getDetailByTable('reservation',$rvId)['rv_contact'];
        $message = getDetailByTable('communication_materials',$cmId)['cm_message'];
        $message = urldecode($message);
        $message = replaceCurls($rvId,$message);
        $message = urldecode($message);

        // sendMessage4($message);

        whatsappMessage($getRVContact,preg_replace("/\r\n|\r|\n/", '\n', $message));

        mysqli_query($conn,"INSERT INTO communication_control (rv_id,cm_id) VALUES ($rvId,$cmId)");

        header('Location: https://app.respond.io/space/80806/message');
        
        exit();
    }

    function replaceCurls($id,$message){
        global $conn;

        if(preg_match_all('/{([^}]*)}/', $message, $matches)){
            foreach($matches[1] as $match){
                    $detail = detailForWhatsapp($id)[$match];
                    $message = preg_replace("/{".$match."}/",$detail, $message);
            }
        }

        return $message;
    }

	function reservationByOwnerIdToTitle($id){
		switch($id){
			case 0 : $title = ""; break;
			case 1 : $title = "By Owner"; break;
		}
		
		return $title;
	}
?>