<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Notification extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('Notification_model');
        $this->load->library('form_validation');
        $this->userDetails = $this->session->userdata('isUserLoggedIn');
    }

    public function index()
    {
        $q = urldecode($this->input->get('q', TRUE));
        $start = intval($this->input->get('start'));
        
        if ($q <> '') {
            $config['base_url'] = base_url() . 'notification/?q=' . urlencode($q);
            $config['first_url'] = base_url() . 'notification/?q=' . urlencode($q);
        } else {
            $config['base_url'] = base_url() . 'notification/';
            $config['first_url'] = base_url() . 'notification/';
        }

        $config['per_page'] = 10;
        $config['page_query_string'] = TRUE;
        $config['total_rows'] = $this->Notification_model->total_rows($q,$this->userDetails['Id']);
        $Notification = $this->Notification_model->get_limit_data($config['per_page'], $start, $q, $this->userDetails['Id']);

        $this->load->library('pagination');
        $this->pagination->initialize($config);

        $data = array(
            'notification_data' => $Notification,
            'q' => $q,
            'pagination' => $this->pagination->create_links(),
            'total_rows' => $config['total_rows'],
            'start' => $start,
        );

        $pageData = array(
            'header'=>array('pageTitle'=>'Notification'),
            'body'=>$data,
            'footer'=>array(),
        );
        loadView('notification/notification_list',$pageData);
    }

    public function create() 
    {
        $data = array(
            'button' => 'Create',
            'action' => site_url('notification/create_action'),
	        'id' => set_value('id'),
	        'fsTitle' => set_value('fsTitle'),
		    'fsMessage' => set_value('fsMessage'),
	        'fsViewMoreButtonTitle' => set_value('fsViewMoreButtonTitle'),
            'fsImage' => set_value('fsImage'),
	        'fsViewMoreButtonLink' => set_value('fsViewMoreButtonLink'),
		    'fiStatus' => set_value('fiStatus'),
		    'fdCreateDate' => set_value('fdCreateDate'),
		    'fdUpdateDate' => set_value('fdUpdateDate'),
		);

        $pageData = array(
            'header'=>array('pageTitle'=>'Notification create'),
            'body'=>$data,
            'footer'=>array(),
        );
        loadView('notification/notification_form',$pageData);
    }


    public function duplicate($notificationId){
    	$row = $this->Notification_model->get_by_id($notificationId);
    	// print_r($row); die;
    	$data = array(
            'button' => 'Create',
            'action' => site_url('notification/create_action'),
	        'id' => set_value('id'),
	        'fsTitle' => $row->fsTitle,
		    'fsMessage' => $row->fsMessage,
	        'fsViewMoreButtonTitle' => $row->fsMoreButtonTitle,
	        'fsViewMoreButtonLink' => $row->fsMoreButtonLink,
	        'fsImage' => $row->fsImage,
		    'fiStatus' => $row->fiStatus,
		    'fdCreateDate' => set_value('fdCreateDate'),
		    'fdUpdateDate' => set_value('fdUpdateDate'),
		);

        $pageData = array(
            'header'=>array('pageTitle'=>'Notification create'),
            'body'=>$data,
            'footer'=>array(),
        );
        loadView('notification/notification_form',$pageData);
    }
    
    public function create_action() 
    {
        $this->_rules();

        if ($this->form_validation->run() == FALSE) {
            $this->create();
        } else {
            $data = array(
                'fiHotelId' => $this->userDetails['Id'],
                'fsTitle' => $this->input->post('fsTitle',TRUE),
        		'fsMessage' => $this->input->post('fsMessage',TRUE),
                'fsMoreButtonTitle' => $this->input->post('fsViewMoreButtonTitle',TRUE),
                'fsMoreButtonLink' => $this->input->post('fsViewMoreButtonLink',TRUE),
        		'fdCreateDate' => date('Y-m-d H:i:s'),
        	); 

            $fsNotificationImage = isset($_REQUEST['fsOldImage'])?$_REQUEST['fsOldImage']:'';
            if(isset($_FILES["fsNotificationImage"]["name"]) && $_FILES["fsNotificationImage"]["name"]!=""){
                $ext = pathinfo($_FILES["fsNotificationImage"]["name"], PATHINFO_EXTENSION);
                $target_file = "assets/uploads/notification/" . time().'-'.rand(1111,9999).'.'.$ext;
                $fsNotificationImage = $target_file;
                move_uploaded_file($_FILES["fsNotificationImage"]["tmp_name"], $target_file);
            }
            $data['fsImage'] = $fsNotificationImage;

        /* Android 1 for normal broadcast message */
        $deviceLists = $this->db->select('fsToken')->from('token')->where('fiHotelId',$this->userDetails['Id'])->where('fsDeviceType','1')->get();
        $deviceLists = $deviceLists->result_array();

        $notificationImage = $data['fsImage']==""?"":base_url().$data['fsImage'];

        $width = $height = 0;
        if($data['fsImage']!=""){
            list($width, $height) = getimagesize(base_url().$data['fsImage']);
        }



        $fbIsVisibleLink = $data['fsMoreButtonTitle']!=""?true:false;
        if(count($deviceLists) > 0){
            $toeknLists = array();
            foreach($deviceLists as $singleToken){
                if(strlen($singleToken['fsToken']) < 50){
                    $toeknLists[] = $singleToken['fsToken'];
                }
            }
            $response = $this->sendOneSignalNotification(
                $toeknLists,
                $this->input->post('fsTitle',TRUE),
                $this->input->post('fsMessage',TRUE),
                false,
                array('fiNotifyId'=>1,'fdDateTime'=>date('jS M Y H:i A'),'fh'=>(float) $height,'fw'=>(float) $width,'fsImg'=>$notificationImage,'btnTxt'=>$data['fsMoreButtonTitle'],'btnLnk'=>$data['fsMoreButtonLink'],'fbLnkSts'=>$fbIsVisibleLink)
            );
        } 

        /* iOS */
        $deviceLists = $this->db->select('fsToken')->from('token')->where('fiHotelId',$this->userDetails['Id'])->where('fsDeviceType','2')->get();
        $deviceLists = $deviceLists->result_array();
        if(count($deviceLists) > 0){
            $toeknLists = array();
            foreach($deviceLists as $singleToken){
                if(strlen($singleToken['fsToken']) < 50){
                    $toeknLists[] = $singleToken['fsToken'];
                }
            }

    
            
            $response = $this->sendOneSignalNotification(

                $toeknLists,
                $this->input->post('fsTitle',TRUE),
                $this->input->post('fsMessage',TRUE),
                true,
                array('fiNotifyId'=>1,'fdDateTime'=>date('jS M Y H:i A'),'fh'=>(float) $height,'fw'=>(float) $width,'fsImg'=>$notificationImage,'btnTxt'=>$data['fsMoreButtonTitle'],'btnLnk'=>$data['fsMoreButtonLink'])

            );


        } 


        // 1 End
        $this->Notification_model->insert($data);
        $this->session->set_flashdata('message', 'Create Record Success');
        redirect(site_url('notification'));
        }
    }



    /* 3 for normal broadcast message */
    function sendOneSignalNotification($to,$title,$message,$isiOS,$other_data = array()){
        
        $device_ids = $to;
        'To : '.print_r($device_ids);
        $headings = array(
            "en" => $title
        );
        $content = array(
            "en" => $message
        );
        $data = array(
            "title"          => $title,
            "message"        => $message,
            // 'fsTitle'=> $title,
            // 'fsMessage'=> $message,
        );
        $data = array_merge($data,$other_data);
        $fields = array(
            'app_id' => ONE_SIGNAL_APP_ID,
            'include_player_ids' => $device_ids,
            'data' => $data,
            'contents' => $content,
            "headings"=> $headings
        );

        // $other_data['fsImg'] = 'https://res.cloudinary.com/practicaldev/image/fetch/s--loWQ8cSh--/c_imagga_scale,f_auto,fl_progressive,h_900,q_auto,w_1600/https://dev-to-uploads.s3.amazonaws.com/i/968e7goywahqew4obu4y.png';

        if($other_data['fsImg']!=""){
            $fields['content_available']=true;
            if($isiOS){
                $fields['large_icon']=$other_data['fsImg'];
                // $fields['media']=$other_data['fsImg'];
                $fields['ios_attachments']=array("id1"=>$other_data['fsImg']);
            }else{
                $fields['big_picture']=$other_data['fsImg'];
            }
        }

        // if($isiOS==true){
        //      print_r($to); die();
        // }

        $sendContent = json_encode($fields);


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
        curl_setopt($ch, CURLOPT_HTTPHEADER, 
                    array('Content-Type: application/json; 
                           charset=utf-8',
                           'Authorization: Basic '.ONE_SIGNAL_API_KEY // your api key
                    ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $sendContent);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        $response = curl_exec($ch);
        curl_close($ch);

        // if($isiOS==true){
        //      print_r($response);  die();
        // }

        return json_decode($response,true);
    } 


    function sendAndroidNotification($to,$title,$message,$isiOS,$other_data = array()){
        // echo json_encode($to); 
        $url=FCM_SERVER_URL;
        $key=FCM_SERVER_KEY;

        $titleMsg = array(
            'fsTitle'=>$title,
            'fsMessage'=>$message
        );

        $data = array( 
            'body'=>array_merge($titleMsg,$other_data),
            'sound'=>'default',
            'content_available'=>1
        );         
        $notification = array('title' =>$title , 'body'=>$message, 'text' => $message, 'sound' => 'default', 'badge' => '1');
        $fields = array('registration_ids' =>$to,'data' =>$data);
        if($isiOS){
            $fields['notification']=$notification;
        }
        $headers = array(
            'Authorization:key=' . $key,
            'Content-Type: application/json'
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);//new added
        $result = curl_exec($ch);
        // print_r($result); die;
        return json_decode($result,true);
    } 

    // 3 for normal broadcast message */
    public function deleteAll(){
    	$this->db->delete('notification',array('fiHotelId'=>$this->userDetails['Id']));
    	$this->session->set_flashdata('message', 'All Record Delete Success');
            redirect(site_url('notification'));
    }


    public function delete($id) 
    {
        $row = $this->Notification_model->get_by_id($id);

        if ($row) {
            $this->Notification_model->delete($id);
            $this->session->set_flashdata('message', 'Delete Record Success');
            redirect(site_url('notification'));
        } else {
            $this->session->set_flashdata('message', 'Record Not Found');
            redirect(site_url('notification'));
        }
    }

    public function _rules() 
    {

    $this->form_validation->set_rules('fsTitle', 'fstitle', 'trim|required');
	$this->form_validation->set_rules('fsMessage', 'fsMessage', 'trim|required');
	$this->form_validation->set_rules('id', 'id', 'trim');
	$this->form_validation->set_error_delimiters('<span class="text-danger">', '</span>');
    }

}

/* End of file category.php */
/* Location: ./application/controllers/category.php */
/* Please DO NOT modify this information : */
/* Generated by Harviacode Codeigniter CRUD Generator 2020-03-13 09:27:44 */
/* http://harviacode.com */