<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Notification extends CI_Controller {

	public function __construct() {
		parent::__construct();
        date_default_timezone_set("Asia/Riyadh");
		$this->load->model('Notification_model');
		
		if(!$this->session->userdata('logged_in')) {
			redirect(base_url('Login'));
		}
		if($this->session->userdata['user_type'] != 1){
			$flashMsg = array('message'=>'Access Denied You don\'t have permission to access this Page',
							  'class'=>'error');
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url());
		}
 	}

	public function notification() {

		$template['page'] = 'Notification/notification';
		$template['menu'] = "Notification Templates";
		$template['smenu'] = "Change Notification Templates";
        $template['pTitle'] = "Notification Templates";
        $template['page_head'] = "Notification Templates";
        $template['pDescription'] = "Change Notification Templates";

		$template['notificationData'] = $this->Notification_model->getNotifData();
		$this->load->view('template',$template);
	}

	public function changeNotifData(){
		$url = 'Notification/notification';
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(!isset($_POST) || empty($_POST)){
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url($url));
		}
	    
		if(!isset($_POST['forgot_mail']) || empty($_POST['forgot_mail'])){
			unset($_POST['forgot_mail']);
		}
		if(!isset($_POST['forgot_sms']) || empty($_POST['forgot_sms'])){
			unset($_POST['forgot_sms']);
		}
		if(!isset($_POST['verify_mail']) || empty($_POST['verify_mail'])){
			unset($_POST['verify_mail']);
		}
		if(!isset($_POST['staff_reg_mail']) || empty($_POST['staff_reg_mail'])){
			unset($_POST['staff_reg_mail']);
		}
	    if(!isset($_POST['registration_mail']) || empty($_POST['registration_mail'])){
			unset($_POST['registration_mail']);
		}
	    if(!isset($_POST['registration_mail']) || empty($_POST['registration_mail'])){
			unset($_POST['registration_mail']);
		}
		if(!isset($_POST['checker_activation_mail']) || empty($_POST['checker_activation_mail'])){
			unset($_POST['checker_activation_mail']);
		}
		if(!isset($_POST['provider_activation_mail']) || empty($_POST['provider_activation_mail'])){
			unset($_POST['provider_activation_mail']);
		}

        $status = $this->Notification_model->updateNotif($_POST);
 		if($status){
 			$flashMsg['class'] = 'success'; 
 			$flashMsg['message'] = 'Settings Successfully Updated..!';
 		}
 		$this->session->set_flashdata('message',$flashMsg);
        redirect(base_url($url));
	}

	public function pushNotification() {
        $this->load->model('Event_model');
        $this->load->model('Region_model');

		$template['page'] = 'Notification/pushNotification';
		$template['menu'] = "Push Notification";
		$template['smenu'] = "Manage Push Notification";
        $template['pTitle'] = "Push Notification";
        $template['page_head'] = "Push Notification";
        $template['pDescription'] = "Manage Push Notification";

		$template['regionData'] = $this->Region_model->getRegionData('','1');
		$template['event_data'] = $this->Event_model->getEventData('','1','');
		$this->load->view('template',$template);
	}

	function sendPushNotif(){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(!isset($_POST) || empty($_POST) || 
		   !isset($_POST['event_id']) || empty($event_id = $_POST['event_id']) || 
		   !isset($_POST['notifMsg']) || empty($message = $_POST['notifMsg']) || 
		   !isset($_POST['tags']) || empty($cities = $_POST['tags'])){
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Notification/pushNotification'));
		}

        $this->load->model('Event_model');
		$event_data = $this->Event_model->getEventData($event_id,'');

		$cities = "'".implode("','",$cities)."'";
		$users = $this->Notification_model->getCityUsers($cities,'1');

		if(empty($users)){
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Notification/pushNotification'));
		}

		foreach($users AS $user){
			$userData = array('id'=>$event_data->event_id,
							  'title'=>$event_data->event_name,
							  'message'=>$message);
			$this->push_sent_cancel('1',$user['fcm_token'],$userData);
		}

		$flashMsg['class'] = 'success';
		$flashMsg['message'] = 'Push Send Successfully';
		$this->session->set_flashdata('message',$flashMsg);
        redirect(base_url('Notification/pushNotification'));
	}

	function reminderPush(){
		$date  = date('Y-m-d',strtotime(date("Y-m-d H:i:s")." +30 minutes"));
		$sTime = date('H:i',strtotime(date("Y-m-d H:i:s")." +30 minutes"));
		$eTime = date("H:i",strtotime(date("Y-m-d H:i:s")." +31 minutes"));

		$sql = "SELECT CUST.customer_id,CUST.fcm_token,BOK.id AS booking_id,BOK.bookId,EVT.event_name
				FROM booking AS BOK
				INNER JOIN customer AS CUST ON (CUST.customer_id=BOK.customer_id)
				INNER JOIN users AS USR ON (USR.id=CUST.customer_id)
				INNER JOIN events AS EVT ON (EVT.event_id=BOK.event_id)
				INNER JOIN event_date_time AS EDATE ON (EDATE.event_id=BOK.event_id)
				WHERE BOK.status='1' AND USR.status='1' AND EDATE.status='1' AND 
					  EDATE.date='$date' AND EDATE.time<='$eTime' AND EDATE.time>='$sTime'
			  	GROUP BY BOK.id,CUST.customer_id";

	  	$bookData = $this->db->query($sql)->result_array();

	  	foreach($bookData AS $bData){
			$userData = array('id'=>$bData['bookId'],
							  'title'=>$bData['event_name'],
							  'message'=>'Booking Remainder');
	  		$this->push_sent_cancel('2',$bData['fcm_token'],$userData);
	  	}
	}

    function push_sent_cancel($type='1', $fcm_token='', $fcm_data=array()) {
		$settings = getSettings();
		$key = $settings['app_id'];

		if(empty($key) || empty($fcm_token) || empty($fcm_data)){
			return;
		}

		switch ($type) {
			case '1':
				$data = "{ \"notification\": { \"title\": \"".$fcm_data['title']."\", \"text\": \"".$fcm_data['message']."\", \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"event_id\" : \"".$fcm_data['id']."\", \"trip_status\" : 0}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"".$fcm_token."\"}";
				break;
			case '2':
				$data = "{ \"notification\": { \"title\": \"".$fcm_data['title']."\", \"text\": \"".$fcm_data['message']."\", \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"booking_id\" : \"".$fcm_data['id']."\", \"trip_status\" : 0}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"".$fcm_token."\"}";
				break;
		}

		$ch = curl_init("https://fcm.googleapis.com/fcm/send");
		$header = array('Content-Type: application/json', 'Authorization: key='.$key);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

		$out = curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_exec($ch);
		curl_close($ch);
  	}
}
?>