<?php
session_start();
if(!isset($_SESSION['user'])) {
	header("location: ../index.php");
	exit;
}

include "../dbconnect.php";

$client_id = '62';
$outlet_id = '1';
/*print_r($_POST);*/
/*exit;*/
if (isset($_POST['saveSetting'])) {
	$dine_switch = $_POST['dinein-switch'];
	$dine_radios = $_POST['dine-radios'];
	$res_dine = $_POST['res-dine'];
	$delivery_switch = $_POST['delivery-switch'];
	$delivery_radios = $_POST['delivery-radios'];
	$res_deliver = $_POST['res-deliver'];
	$comm_after = $_POST['comm-after'];
	$reminder_switch = $_POST['reminder-switch'];
	$reminder_after = $_POST['reminder-after'];
	if ($dine_switch == 'on' || $delivery_switch == 'on' || $reminder_switch == 'on') {
		mysql_query("UPDATE `feedback_config` SET `enable_fb_dine_in` = '1', `dine_in_fb_mode` = '$dine_radios', `dine_in_response_type` = '$res_dine', `enable_fb_delivery` = '1', `delivery_fb_mode` = '$delivery_radios', `delivery_response_star` = '$res_deliver', `online_fb_after_mts` = '$comm_after', `online_fb_resend` = '1', `online_resend_after` = '$reminder_after' WHERE `client_id` = '$client_id' AND `outlet_id` = '$outlet_id'");
		
	} else {
		mysql_query("UPDATE `feedback_config` SET `enable_fb_dine_in` = '0', `dine_in_fb_mode` = '', `dine_in_response_type` = '', `enable_fb_delivery` = '0', `delivery_fb_mode` = '', `delivery_response_star` = '', `online_fb_after_mts` = '', `online_fb_resend` = '0', `online_resend_after` = '' WHERE `client_id` = '$client_id' AND `outlet_id` = '$outlet_id'");
	}
	header("location: feedback_settings.php");
}


if (isset($_POST['save-email'])) {
	// echo "<pre>";
	// print_r($_POST);
	// exit;	

	$clientid = $_POST['clientid'];
	// $outledID = $_POST['outledID'];
	$alert_switch = $_POST['alert-switch'];
	$recive_alert = $_POST['recive-alert'];
	// $outletid = $_POST['outletid'];
	if ($alert_switch == 'on') {
		$qry1 = mysql_query("SELECT UnitId FROM unit_master");
		while($row1 = mysql_fetch_assoc($qry1)){
			// print_r($row);
			$emailId = $_POST['outlet-alert-emails#'.$row1['UnitId']];
			$outletid = $row1['UnitId'];
			if(!empty($emailId)){
				// echo count($emailId);
				// echo "<br>";
				foreach ($emailId as $value) {
					$qry2 = mysql_query("SELECT `outlet_id`, `email_id` FROM `feedback_alert_mails` WHERE `outlet_id` = '$outletid' AND `email_id` = '$value'");
					if (mysql_num_rows($qry2) < 1) {
						if($value!=''){
							// echo "INSERT INTO `feedback_alert_mails`(`client_id`,`outlet_id`,`email_id`) VALUES('$clientid','$outletid','$value')";
							$qry3 = mysql_query("INSERT INTO `feedback_alert_mails`(`client_id`,`outlet_id`,`email_id`) VALUES('$clientid','$outletid','$value')");
						}
					}
				}
			}
		}

		$emails = $_POST['alert-emails'];
		if (!empty($emails)) {
			foreach ($emails as $value1) {
				$qry4 = mysql_query("SELECT `outlet_id`, `email_id` FROM `feedback_alert_mails` WHERE `outlet_id` = '0' AND `email_id` = '$value1'");
				if (mysql_num_rows($qry4) < 1) {
					if ($value1 != '') {
						mysql_query("INSERT INTO `feedback_alert_mails`(`client_id`,`outlet_id`,`email_id`) VALUES('$clientid','0','$value1')");
					}
				}
			}
		}
	}

	if ($alert_switch == 'on') {
		mysql_query("UPDATE `feedback_config` SET `enable_fb_alert` = '1', `fb_alert_value` = '$recive_alert' WHERE `client_id` = '$clientid' AND `outlet_id` = '$outlet_id'");
	} else {
		mysql_query("UPDATE `feedback_config` SET `enable_fb_alert` = '0', `fb_alert_value` = '' WHERE `client_id` = '$clientid' AND `outlet_id` = '$outlet_id'");
	}
	header("location: feedback_settings.php");
}


if ($_POST['act'] == 'delete_email') {
	$unitid = $_POST['unitid'];
	$emailid = $_POST['emailid'];

	$del_qry = mysql_query("DELETE FROM `feedback_alert_mails` WHERE `outlet_id` = '$unitid' AND `email_id` = '$emailid'");
}

if ($_POST['act'] == 'delete_alloutlet_email') {
	$unitid = $_POST['unitid'];
	$emailid = $_POST['emailid'];

	$del_qry = mysql_query("DELETE FROM `feedback_alert_mails` WHERE `outlet_id` = '0' AND `email_id` = '$emailid'");
}

if ($_POST['act'] == 'dinein_on') {
	$mode = $_POST['mode'];

	if ($mode == 'true') {
		$qry = mysql_query("UPDATE `feedback_config` SET `enable_fb_dine_in` = '1' WHERE `client_id` = '$client_id' AND `outlet_id` = '$outlet_id' ");
	}
}

if ($_POST['act'] == 'dinein_off') {
	$mode = $_POST['mode'];

	if ($mode == 'false') {
		$qry = mysql_query("UPDATE `feedback_config` SET `enable_fb_dine_in` = '0' WHERE `client_id` = '$client_id' AND `outlet_id` = '$outlet_id' ");
	}
}

if ($_POST['act'] == 'delivery_on') {
	$mode = $_POST['mode'];

	if ($mode == 'true') {
		$qry = mysql_query("UPDATE `feedback_config` SET `enable_fb_delivery` = '1' WHERE `client_id` = '$client_id' AND `outlet_id` = '$outlet_id' ");
	}
}

if ($_POST['act'] == 'delivery_off') {
	$mode = $_POST['mode'];

	if ($mode == 'false') {
		$qry = mysql_query("UPDATE `feedback_config` SET `enable_fb_delivery` = '0' WHERE `client_id` = '$client_id' AND `outlet_id` = '$outlet_id' ");
	}
}

if ($_POST['act'] == 'reminder_on') {
	$mode = $_POST['mode'];

	if ($mode == 'true') {
		$qry = mysql_query("UPDATE `feedback_config` SET `online_fb_resend` = '1' WHERE `client_id` = '$client_id' AND `outlet_id` = '$outlet_id' ");
	}
}

if ($_POST['act'] == 'reminder_off') {
	$mode = $_POST['mode'];

	if ($mode == 'false') {
		$qry = mysql_query("UPDATE `feedback_config` SET `online_fb_resend` = '0' WHERE `client_id` = '$client_id' AND `outlet_id` = '$outlet_id' ");
	}
}

if ($_POST['act'] == 'alert_on') {
	$mode = $_POST['mode'];

	if ($mode == 'true') {
		$qry = mysql_query("UPDATE `feedback_config` SET `enable_fb_alert` = '1' WHERE `client_id` = '$client_id' AND `outlet_id` = '$outlet_id' ");
	}
}

if ($_POST['act'] == 'alert_off') {
	$mode = $_POST['mode'];

	if ($mode == 'false') {
		$qry = mysql_query("UPDATE `feedback_config` SET `enable_fb_alert` = '0' WHERE `client_id` = '$client_id' AND `outlet_id` = '$outlet_id' ");
	}
}


/*if (isset($_POST['cbSubmit'])) {
	$fbno = $_POST['fbno'];
	$outletid = $_POST['outletid'];
	$invoiceid = $_POST['invoiceid'];
	print_r($_POST);
	$qry = mysql_query("SELECT fbr.*, goh.`feedback_done`, fbr.`order_source_name` FROM `guest_order_history` AS goh RIGHT JOIN `feedback_response` AS fbr ON goh.`SaleDate` = fbr.`sale_date` WHERE goh.`feedback_done` = 0 AND fbr.`outlet_id` = '$outletid' AND fbr.`invoice_id` = '$invoiceid'");
	while ($row = mysql_fetch_array($qry)) {
		$ord_src = $row['order_source_name'];

		$que_qry = mysql_query("SELECT * FROM `feedback_ques` WHERE `fb_ques_enable` = 1 AND`client_id` = '75' AND `outlet_id` = '$outlet_id'");
		while($que_row = mysql_fetch_array($que_qry)) {
			$ques_for = $que_row['fb_ques_for'];
			$fb_ques = $que_row['fb_ques'];

			if($ord_src == 'Outlet') {
				if ($ques_for == 'Both' || $ques_for == 'Dine-In') {
					$fbinputname = strtolower(str_replace(' ', '_', $que_row['fb_ques']));
					// $fbinput = $_POST['call_'.$fbinputname];
					echo ($_POST['call_'.$fbinputname]);
				}
			} elseif ($ord_src != 'Outlet') {
				if ($ques_for == 'Both' || $ques_for == 'Delivery') {
					$fbinputname = strtolower(str_replace(' ', '_', $que_row['fb_ques']));
				}
			}
		}
	}
}*/


/*if ($_GET['act'] == 'cbfeedback') {
	echo $inputvalue = $_GET['inputvalue'];
	echo $email = $_GET['email'];
}*/
    

if (isset($_POST['cbSubmit']) AND $_POST['cbSubmit']=='cbSubmit') {
	
	$outletid = $_POST['outletid'];
	$invoice_id = $_POST['invoiceid'];
	/* cODE ADDED BY JAI */
	$fc = mysql_query("SELECT `enable_fb_alert`, `fb_alert_value`, `loyalty_points_given` FROM `feedback_config` LIMIT 1");
	$fcr = mysql_fetch_assoc($fc);
	$enable_fb_alert = $fcr['enable_fb_alert'];
	$fb_alert_value = $fcr['fb_alert_value'];
	$loyalty_points_given = $fcr['loyalty_points_given'];
	/* ------------ */
	$sm_qry = mysql_query("SELECT `LoginName`, `StaffName` FROM `staff_master` WHERE `LoginName` = '".$_SESSION['user']."'");
	$sm_row = mysql_fetch_array($sm_qry);
	$agent_id = $sm_row['LoginName'];
	$agent_name = $sm_row['StaffName'];

	$qry_goh = mysql_query("SELECT * FROM guest_order_history WHERE UnitId='$outletid' AND InvoiceId='$invoice_id' AND feedback_done = 0 AND (OrderStatus != 'Rejected' AND OrderStatus != 'Cancelled') LIMIT 1");
	if (mysql_num_rows($qry_goh) > 0) {
		$row_goh = mysql_fetch_assoc($qry_goh);
		
		$invoice_no = $row_goh['InvoiceNumber'];
		$sale_date = $row_goh['SaleDate'];
		$city = $row_goh['City'];
		$order_type = $row_goh['DeliveryOption'];
		$SourceId = $row_goh['SourceId'];
		$order_source = $row_goh['SourceOfOrder'];
		$guest_name = $row_goh['FirstName'].''.$row_goh['LastName'];
		$guest_phone = $row_goh['GuestPhone'];

		$comments = $_POST['cbcomments'];
		$anniversary = $_POST['cbanniversary'];
		$birthday = $_POST['cbdob'];
		$email = $_POST['cbemail'];

		if($birthday !=''){
			$birthday = date('Y-m-d', strtotime($_POST['cbdob']));
		}
		if($anniversary !=''){
			$anniversary = date('Y-m-d', strtotime($_POST['cbanniversary']));
		}

		/* Get Unit Name */
		$unit_sql = mysql_query("SELECT UnitName FROM unit_master WHERE UnitId=$outletid");
		$unit_row = mysql_fetch_assoc($unit_sql);
		$unit_name = $unit_row['UnitName'];

		/* Get City Name */
		$city_sql = mysql_query("SELECT scity_id FROM city WHERE city_id=$city");
		$city_row = mysql_fetch_assoc($city_sql);
		$scity_id = $city_row['scity_id'];

		$super_city_sql = mysql_query("SELECT scity_id, scity_name FROM supercity WHERE scity_id=$scity_id");
		$super_city_row = mysql_fetch_assoc($super_city_sql);
		$super_city_name = $super_city_row['scity_name'];


		$qry_ins = mysql_query("INSERT INTO `feedback_response`(`fb_no`, `client_id`, `outlet_id`, `invoice_id`, `invoice_no`, `sale_date`, `response_date_time`, `city`, `city_name`, `outlet_name`, `order_type`, `order_source`, `order_source_name`, `guest_name`, `guest_mob_no`, `guest_email`, `fb_comments`, `response_by`, `agent_id`, `agent_name`, `points_collected`) VALUES(NULL, '$client_id', '$outletid', '$invoice_id', '$invoice_no', '$sale_date', CURRENT_TIMESTAMP, '$scity_id', '$super_city_name', '$unit_name', '$order_type', '$SourceId', '$order_source', '$guest_name', '$guest_phone', '$email', '$comments', 'agent', '$agent_id', '$agent_name', '$loyalty_points_given')");
		if ($qry_ins) {
			$last_id = mysql_insert_id();
			$ans_wt = 0;
			for ($i=1; $i<=$_POST['no_ques']; $i++) {
				if(isset($_POST['call_'.$i])){
					/* [ques3] => delivery_and_packaging#3-1-Poor*/
					$data = $_POST['call_'.$i];
					$d1 = explode('#', $data);
					$ques = $d1[0]; 
					$d2 = explode('-', $d1[1]);
					$ques_id = $d2[0];
					$opt_wt = $d2[1];
					$opt_txt = $d2[2];

					$ans_wt += $opt_wt;
					

					mysql_query("INSERT INTO `feedback_response_details`(`fb_no`, `fb_ques_id`, `fb_ques`, `guest_ans`, `ans_wt`) VALUES ('$last_id','$ques_id','$ques','$opt_txt','$opt_wt')");
				}
			}
			mysql_query("UPDATE guest_order_history SET feedback_done = 1 WHERE UnitId='$outletid' AND InvoiceId = '$invoice_id' AND feedback_done < 1 AND (OrderStatus!='Rejected' AND OrderStatus!='Cancelled') LIMIT 1");
			
			/* Send Mail if answaer less than avarage */
			if($enable_fb_alert > 0){
				$avg_wt = ($ans_wt/$_POST['no_ques']);
				if($avg_wt <= $fb_alert_value){
					/* Send Mail */
					$recipients = array();
					$fbm_sql = mysql_query("SELECT email_id FROM feedback_alert_mails WHERE outlet_id='0' OR outlet_id='$outletid'");
					while ($fbm_row = mysql_fetch_assoc($fbm_sql)) {
						$recipients[] = $fbm_row['email_id'];
					}

					$as = "{\"UnitId\":\"$outletid\",\"InvoiceId\":\"$invoice_id\",\"fb_no\":\"$last_id\"}";					
					$curl = curl_init();
					curl_setopt_array($curl, array(
					  CURLOPT_URL => "http://rezol.in/bbk_feedback/feedback/mail.php?outletid=$outletid&invoiceid=$invoice_id&fbno=$last_id",
					  CURLOPT_RETURNTRANSFER => true,
					  CURLOPT_ENCODING => "",
					  CURLOPT_MAXREDIRS => 10,
					  CURLOPT_TIMEOUT => 30,
					  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					  CURLOPT_CUSTOMREQUEST => "POST",
					  CURLOPT_POSTFIELDS => $as,
					  CURLOPT_HTTPHEADER => array(
					    "cache-control: no-cache",					    	    
					    "Token: base64_encode('feedback_token')"				    
					  ),
					));

					$content_html = curl_exec($curl);

					$err = curl_error($curl);

					curl_close($curl);
					/* Send Mail */
										 
					include("class.phpmailer.php");
					include("class.smtp.php");

					$mail = new PHPMailer(); 
					$mail->IsSMTP();
					$mail->Host = "host.solutionzconsulting.in";
					$mail->SMTPAuth = true;
					$mail->Username = "feedbackalert@rezol.in";
					$mail->Password = "fb18alert415";
					$from = 'feedbackalert@rezol.in';
					$mail->From = $from;
					$mail->FromName = "Rezol Feedback";
					$mail->IsHTML(true);
					foreach($recipients as $email)
					{
					   $mail->AddAddress($email);
					}
					

					$mail->Subject = "Feedback Alert - $unit_name, Invoice No: $invoice_id"; 
					$mail->Body    = $content_html;      

					if(!$mail->Send()) { 
					     # sending mail failed
					    echo $msg="Unknown Error has Occured. Please try again Later.";
					    echo $mail->ErrorInfo;
					} else {
					    echo $msg="Your Message has been sent. We'll keep in touch with you soon.";
					} 

					$mail = new PHPMailer();
					foreach($recipients as $email)
					{
					   $mail->AddAddress($email);
					}

					/*$mail->AddAddress($sendmail,"Subject");*/
			   /* $mail->Subject = "Feedback Alert - $unit_name, Invoice No: $invoice_id"; 
			    $mail->Body    = $content_html;      

			    if(!$mail->Send()) { 
			   		 # sending mail failed
			        $msg="Unknown Error has Occured. Please try again Later.";
			    } else {
			        $msg="Your Message has been sent. We'll keep in touch with you soon.";
			    } 
					*/
				}
			}
			

			/*header("location:feedback_callback.php");*/



		}
	}
}


if ($_GET['act'] == 'notint') {
	$outletid = $_GET['oid'];
	$invoice_id = $_GET['invid'];
	
	mysql_query("UPDATE guest_order_history SET feedback_done = 2 WHERE UnitId='$outletid' AND InvoiceId = '$invoice_id' AND feedback_done < 1 AND (OrderStatus!='Rejected' AND OrderStatus!='Cancelled') LIMIT 1");

}