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

class Event extends CI_Controller {

	public function __construct() {
		parent::__construct();
        date_default_timezone_set("Asia/Riyadh");
        $this->load->model('Event_model');
		$this->load->model('Dashboard_model');
		
		if(!$this->session->userdata('logged_in')) {
			redirect(base_url('Login'));
		}
 	}
	function listEvents(){
		$template['page'] = 'Event/viewEventList';
        $template['menu'] = 'Event Management';
        $template['smenu'] = 'View Event List';
        $template['pTitle'] = "Event Management";
        $template['pDescription'] = "View Event List";
        $provider_id = ($this->session->userdata['user_type']==2)?$this->session->userdata['id']:'';
        $template['event_data'] = $this->Event_model->getEventData('','',$provider_id);
		$this->load->view('template',$template);
	}

	function addEvent(){
        $this->load->model('Venue_model');

        $template['venue_id'] = '';
        if(isset($_POST['venue_id']) && !empty($_POST['venue_id'])){
            $this->load->model('Tag_model');
            $this->load->model('Category_model');
            $template['tag_data'] = $this->Tag_model->getTagData('','1');
            $template['category_data'] = $this->Category_model->getCategoryData('','1');

            $template['venue_id'] = $_POST['venue_id'];
            $template['venueData'] = $this->Venue_model->getVenueData($template['venue_id']);
        }

        $template['venueList'] = $this->Venue_model->getVenueData('','1');

		$template['page'] = 'Event/eventAddForm';
        $template['menu'] = 'Event Management';
        $template['smenu'] = 'Add Event';
        $template['pTitle'] = "Add Event";
        $template['pDescription'] = "Create New Event";

		$this->load->view('template',$template);
	}

	function createEvent(){
        ini_set("memory_limit", "-1");
        set_time_limit(0);
        $language = getLanguages();
        
		$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('Event/addEvent'));
        }

		$err = 0;
        $errMsg = '';
        if($err == 0 && (!isset($_POST['event_name_EN']) || empty($_POST['event_name_EN']))){
            $err = 1;
            $errMsg = 'Provide Event Name (English)';
        } 
        else if ($err == 0 && (!isset($_POST['event_description_EN']) || $_POST['event_description_EN']=='')){
            $err = 1;
            $errMsg = 'Provide Event Description (English)';
        }  
        else if ($err == 0 && (!isset($_POST['event_start_date']) || $_POST['event_start_date'] == '')){
            $err = 1;
            $errMsg = 'Provide Event Start Date';
        } 
        else if ($err == 0 && (!isset($_POST['event_time']) || count($_POST['event_time']) <= 0)){
            $err = 1;
            $errMsg = 'Provide Event Timing';
        } 
        else if ($err == 0 && (!isset($_POST['category_id']) || $_POST['category_id'] == '')){
            $err = 1;
            $errMsg = 'Provide Event Category';
        } 
        else if ($err == 0 && (!isset($_POST['tags']) || count($_POST['tags']) <= 0)){
            $err = 1;
            $errMsg = 'Provide Proper Event Details';
        } 
        else if ($err == 0 && isset($_POST['fare_type']) && $_POST['fare_type'] == 1 && 
                  !isset($_POST['seat_color']) || empty($_POST['seat_color']) || 
                  !isset($_POST['seat_price']) || empty($_POST['seat_price']) || 
                  count($_POST['seat_price']) != count($_POST['seat_color'])){
            $err = 1;
            $errMsg = 'Provide Proper Layout details';
        }

        $_POST['has_payment'] = (isset($_POST['has_payment']) && $_POST['has_payment'] == 1)?'1':'0';

        $_POST['seat_pricing'] = $_POST['custom_seat_layout'] = '';
        if(isset($_POST['fare_type']) && $_POST['fare_type'] == 1){
            $cstmSeatLayout = array();
            for($i = 0 ; $i < count($_POST['seat_color']) ; $i++){
                if(!isset($_POST['weekend_price'][$i]) || empty($_POST['weekend_price'][$i])){
                    $_POST['weekend_price'][$i] = $_POST['seat_price'][$i];
                }
                $cstmSeatLayout[] = array('color'=>$_POST['seat_color'][$i],
                                          'price'=>$_POST['seat_price'][$i],
                                          'capacity'=>$_POST['seat_capacity'][$i],
                                          'weekend_price'=>$_POST['weekend_price'][$i]);
            }
            $_POST['custom_seat_layout'] = json_encode($cstmSeatLayout);
        } else if (isset($_POST['price']) && !empty($_POST['price']) && 
                   isset($_POST['capacity']) && !empty($_POST['capacity'])){
            $seatPriceArr = array('price'=>$_POST['price'],'capacity'=>$_POST['capacity']);
            foreach($language AS $lang) {
                if(isset($_POST['price_details_'.$lang]) && !empty($_POST['price_details_'.$lang])){
                    $details = $_POST['price_details_'.$lang];
                }
                $seatPriceArr['price_details_'.$lang] = $details;
            }
            $_POST['seat_pricing'] = json_encode($seatPriceArr);
        }

        $_POST['max_booking'] = (isset($_POST['max_booking']) && !empty($_POST['max_booking']))?
                                    $_POST['max_booking']:'14';

        $provider = ($this->session->userdata['user_type']==1)?'1':$this->session->userdata['id'];
        $eventData = array('venue_id'=>$_POST['venue_id'],
                           'category_id'=>$_POST['category_id'],
                           'provider_id'=>$provider,
                           'max_booking'=>$_POST['max_booking'],
                           'has_payment'=>$_POST['has_payment'],
                           'seat_pricing'=>$_POST['seat_pricing'],
                           'custom_seat_layout'=>$_POST['custom_seat_layout']);
        $languageArr = array();
        foreach($language AS $lang) {
            if((isset($_POST['event_name_'.$lang]) && !empty($_POST['event_name_'.$lang])) || 
               (isset($_POST['event_description_'.$lang]) && !empty($_POST['event_description_'.$lang]))){
                $languageArr[$lang]['event_name'] = $_POST['event_name_'.$lang];
                $languageArr[$lang]['event_desc'] = $_POST['event_description_'.$lang];
            }
        }

        $event_id = $this->Event_model->createEvent($eventData,$languageArr);
        if(!empty($event_id)){

            $insertEventDate = array();
            if(isset($_POST['schedule_type']) && $_POST['schedule_type'] == 0){
                $date = strtotime($_POST['event_start_date']);
                $date = date('Y-m-d',$date);
                foreach ($_POST['event_time'] AS $time) {
                    $insertEventDate[] = array('event_id'=>$event_id,'date'=>$date,'time'=>$time);
                }
            } else {
                $cdate = strtotime($_POST['event_start_date']);
                while ($cdate <= strtotime($_POST['event_end_date'])) {
                    $cdate = date('Y-m-d',$cdate);
                    foreach ($_POST['event_time'] AS $time) {
                        $insertEventDate[] = array('event_id'=>$event_id,'date'=>$cdate,'time'=>$time);
                    }
                    $cdate = strtotime($cdate . ' +1 day');
                }
            }
            $status = $this->Event_model->createEventDateTime($insertEventDate);

            $insertTag = array();
            foreach ($_POST['tags'] AS $tag) {
                $insertTag[] = array('event_id'=>$event_id,'tag_id'=>$tag);
            }
            $status = $this->Event_model->createTags($insertTag);
            
            if(isset($_FILES) && isset($_FILES['event_image']) && 
               isset($_FILES['event_image']['name']) && count($_FILES['event_image']['name'])>1){
                $resp = $this->eventImageUpload($event_id,$_FILES);

                $evtMediaData = (isset($resp['evtMediaData']))?$resp['evtMediaData']:array();
                $errorMediaFiles = (isset($resp['errorMediaFiles']))?$resp['errorMediaFiles']:array();
                $status = $this->Event_model->createEventMedia($evtMediaData);
            }

            // START - NEW EVENT NOTIFICATION MAIL \\
            if($this->session->userdata['user_type'] != 1){
                $settings = getSettings();
                $this->load->model('Api_model');

                $subject  = "TimeOut, New Event Created";
                $emailId  = $settings['admin_mail_id'];
                $message  =  "<html><body>
                               New Event Created, event name: <strong>".$_POST['event_name_en']."</strong>. Event URL : ".base_url()."eventdetail?event_id=$event_id
                              </body></html>";
                $this->Api_model->send_mail($subject,$emailId,$message);
            }
            // END - NEW EVENT NOTIFICATION MAIL \\

            $flashMsg['class'] = 'success';
            $flashMsg['message'] = 'Event Created';

            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Event/listEvents'));
        }
        $this->session->set_flashdata('message',$flashMsg);
        redirect(base_url('Event/addEvent'));
	}

	function editEvents($event_id=''){
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(empty($event_id) || empty(decode_param($event_id))){
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Event/listEvents'));
		}
		$template['page'] = 'Event/eventEditForm';
        $template['menu'] = 'Event Management';
        $template['smenu'] = 'Edit Event';
        $template['pTitle'] = "Edit Event";
        $template['pDescription'] = "Update Event Data";

        $template['event_id'] = $event_id;
        $template['event_data'] = $this->Event_model->getEventData(decode_param($event_id));

        $this->load->model('Tag_model');
        $this->load->model('Category_model');
        $template['tag_data'] = $this->Tag_model->getTagData('','1');
        $template['category_data'] = $this->Category_model->getCategoryData('','1');

		$this->load->view('template',$template);
	}

	function updateEvent($event_id=''){
        ini_set("memory_limit", "-1");
        set_time_limit(0);
        $language = getLanguages();
        
        if(empty($event_id) || empty($event_id = decode_param($event_id)) || 
          !isset($_POST) || empty($_POST)){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Event/listEvents'));
        }

        $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('Event/addEvent'));
        }

        $err = 0;
        $errMsg = '';
        if($err == 0 && (!isset($_POST['event_name_EN']) || empty($_POST['event_name_EN']))){
            $err = 1;
            $errMsg = 'Provide Event Name (English)';
        } 
        else if ($err == 0 && (!isset($_POST['event_description_EN']) || $_POST['event_description_EN']=='')){
            $err = 1;
            $errMsg = 'Provide Event Description (English)';
        }  
        else if ($err == 0 && (!isset($_POST['event_start_date']) || $_POST['event_start_date'] == '')){
            $err = 1;
            $errMsg = 'Provide Event Start Date';
        } 
        else if ($err == 0 && (!isset($_POST['event_time']) || count($_POST['event_time']) <= 0)){
            $err = 1;
            $errMsg = 'Provide Event Timing';
        } 
        else if ($err == 0 && (!isset($_POST['category_id']) || $_POST['category_id'] == '')){
            $err = 1;
            $errMsg = 'Provide Event Category';
        } 
        else if ($err == 0 && (!isset($_POST['tags']) || count($_POST['tags']) <= 0)){
            $err = 1;
            $errMsg = 'Provide Proper Event Details';
        } 
        else if ($err == 0 && isset($_POST['fare_type']) && $_POST['fare_type'] == 1 && 
                  !isset($_POST['seat_color']) || empty($_POST['seat_color']) || 
                  !isset($_POST['seat_price']) || empty($_POST['seat_price']) || 
                  count($_POST['seat_price']) != count($_POST['seat_color'])){
            $err = 1;
            $errMsg = 'Provide Proper Layout details';
        }

        $_POST['has_payment'] = (isset($_POST['has_payment']) && $_POST['has_payment'] == 1)?'1':'0';
        $_POST['seat_pricing'] = $_POST['custom_seat_layout'] = '';
        if(isset($_POST['fare_type']) && $_POST['fare_type'] == 1){
            $cstmSeatLayout = array();
            for($i = 0 ; $i < count($_POST['seat_color']) ; $i++){
                if(!isset($_POST['weekend_price'][$i]) || empty($_POST['weekend_price'][$i])){
                    $_POST['weekend_price'][$i] = $_POST['seat_price'][$i];
                }
                $cstmSeatLayout[] = array('color'=>$_POST['seat_color'][$i],
                                          'price'=>$_POST['seat_price'][$i],
                                          'capacity'=>$_POST['seat_capacity'][$i],
                                          'weekend_price'=>$_POST['weekend_price'][$i]);
            }
            $_POST['custom_seat_layout'] = json_encode($cstmSeatLayout);
        } else if(isset($_POST['price']) && !empty($_POST['price']) && 
                  isset($_POST['capacity']) && !empty($_POST['capacity'])){
            $seatPriceArr = array('price'=>$_POST['price'],'capacity'=>$_POST['capacity']);
            foreach($language AS $lang) {
                if(isset($_POST['price_details_'.$lang]) && !empty($_POST['price_details_'.$lang])){
                    $details = $_POST['price_details_'.$lang];
                }
                $seatPriceArr['price_details_'.$lang] = $details;
            }
            $_POST['seat_pricing'] = json_encode($seatPriceArr);
        }

        $_POST['max_booking'] = (isset($_POST['max_booking']) && !empty($_POST['max_booking']))?
                                    $_POST['max_booking']:'14';

        $provider = ($this->session->userdata['user_type']==1)?'1':$this->session->userdata['id'];
        $eventData = array('venue_id'=>$_POST['venue_id'],
                           'category_id'=>$_POST['category_id'],
                           'provider_id'=>$provider,
                           'max_booking'=>$_POST['max_booking'],
                           'has_payment'=>$_POST['has_payment'],
                           'seat_pricing'=>$_POST['seat_pricing'],
                           'custom_seat_layout'=>$_POST['custom_seat_layout']);
        $languageArr = array();
        foreach($language AS $lang) {
            if((isset($_POST['event_name_'.$lang]) && !empty($_POST['event_name_'.$lang])) || 
               (isset($_POST['event_description_'.$lang]) && !empty($_POST['event_description_'.$lang]))){
                $languageArr[$lang]['event_name'] = $_POST['event_name_'.$lang];
                $languageArr[$lang]['event_desc'] = $_POST['event_description_'.$lang];
            }
        }

        $status = $this->Event_model->updateEvent($event_id, $eventData, $languageArr);

        if($status){
            $insertEventDate = array();
            if(isset($_POST['schedule_type']) && $_POST['schedule_type'] == 0){
                $date = strtotime($_POST['event_start_date']);
                $date = date('Y-m-d',$date);
                foreach ($_POST['event_time'] AS $time) {
                    $insertEventDate[] = array('event_id'=>$event_id,'date'=>$date,'time'=>$time);
                }
            } else {
                $cdate = strtotime($_POST['event_start_date']);
                while ($cdate <= strtotime($_POST['event_end_date'])) {
                    $cdate = date('Y-m-d',$cdate);
                    foreach ($_POST['event_time'] AS $time) {
                        $insertEventDate[] = array('event_id'=>$event_id,'date'=>$cdate,'time'=>$time);
                    }
                    $cdate = strtotime($cdate . ' +1 day');
                }
            }
            $status = $this->Event_model->updateEventDateTime($event_id,$insertEventDate);

            $insertTag = array();
            foreach ($_POST['tags'] AS $tag) {
                $insertTag[] = array('event_id'=>$event_id,'tag_id'=>$tag);
            }
            $status = $this->Event_model->updateTags($event_id,$insertTag);

            $existingImages = (isset($_POST['existingImages']) && !empty($_POST['existingImages']))?
                              $_POST['existingImages']:'';

            $evtMediaData = array();
            $errorMediaFiles = array();
            $media_type = (!empty($existingImages))?1:0;
            if(isset($_FILES) && isset($_FILES['event_image']) && 
               isset($_FILES['event_image']['name']) && count($_FILES['event_image']['name'])>1){
                $resp = $this->eventImageUpload($event_id,$_FILES,$media_type);

                $evtMediaData = (isset($resp['evtMediaData']))?$resp['evtMediaData']:array();
                $errorMediaFiles = (isset($resp['errorMediaFiles']))?$resp['errorMediaFiles']:array();
            }
            $status = $this->Event_model->updateEventMedia($event_id,$evtMediaData,$existingImages);

            $flashMsg['class'] = 'success';
            $flashMsg['message'] = 'Event Created';

            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Event/listEvents'));
        }
        $this->session->set_flashdata('message',$flashMsg);
        redirect(base_url('Event/listEvents'));
	}

    function eventImageUpload($eId = '', $files = array(), $mTyp='0'){
        if(empty($eId) || empty($files)){
            return false;
        }

        $evtMediaData = array();
        $errorMediaFiles = array();
        $this->load->library('upload');
        $bPath = "assets/uploads/services/";
        $config = set_upload_service("assets/uploads/services");
        for($typ = 0; $typ < count($files['event_image']['name']); $typ++) { 
            $_FILES['file']['name'] = $files['event_image']['name'][$typ];
            $_FILES['file']['type'] = $files['event_image']['type'][$typ];
            $_FILES['file']['size'] = $files['event_image']['size'][$typ]; 
            $_FILES['file']['error'] = $files['event_image']['error'][$typ];
            $_FILES['file']['tmp_name'] = $files['event_image']['tmp_name'][$typ];

            $extn = substr($_FILES['file']['name'],strrpos($_FILES['file']['name'],'.')+1);
            $file = date('YmdHis').gettimeofday()['usec']."_EVT_IMG.".$extn;
            $config['file_name'] = $file;

            $this->upload->initialize($config);
            if($this->upload->do_upload('file')){
                $iDat = $this->upload->data();
                $path = $bPath.$iDat['file_name'];
                if($extn != 'gif'){
                    $size  = array('width'=>'720','height'=>'480');
                    $tFile = date('YmdHis').gettimeofday()['usec'].'_EVT_IMG_720x480.'.$extn;
                    $resp  = $this->imageResize($tFile,$size,$path);
                    if($resp['status'] == '1'){
                        $file = $tFile;
                        unlink($path);
                        $path = $bPath.$tFile;
                    }
                }
                $imgSafety = $this->googleVisionApi(base_url($file));
                if($imgSafety == 1){
                    $evtMediaData[] = array('event_id'=>$eId,'media_type'=>$mTyp,'media_url'=>$path);
                    $mTyp = '1';
                } 
                else if ($imgSafety == 2) {
                    $errorMediaFiles[] = $_FILES['file']['name'];
                }
            } else {
                $errorMediaFiles[] = $_FILES['file']['name'];
            }
        }
        return array('evtMediaData'=>$evtMediaData,'errorMediaFiles'=>$errorMediaFiles);
    }

    function changeStatus(){
        if(!isset($_POST) || !isset($_POST['event_id']) || empty($_POST['event_id']) || 
           !isset($_POST['status']) || $_POST['status'] == ''){
            echo json_encode(array('status'=>'0'));exit;
        }
        $status = $_POST['status'];
        $event_id = decode_param($_POST['event_id']);
        $resp = $this->Event_model->changeStatus($event_id,$status);
        if($resp){
            echo json_encode(array('status'=>'1'));exit;
        }
        echo json_encode(array('status'=>'0'));exit;
    }

    function getEventData(){
        $resArr = array('status'=>0);
        if(!isset($_POST) || empty($_POST) || !isset($_POST['event_id']) || empty($_POST['event_id']) || 
           empty($event_id = decode_param($_POST['event_id']))){
            echo json_encode($resArr);exit;
        }
        $this->load->model('Tag_model');
        
        $data['event'] = $this->Event_model->getEventData($event_id);
        $data['tag_data'] = $this->Tag_model->getTagData('','1');
        $viewPage = $this->load->view('Event/viewEventDetails',$data,true);

        echo $viewPage;exit;
    }

    function imageResize($newImage,$size,$path){
        $this->load->library('image_lib');
        $config['width']          = $size['width'];
        $config['height']         = $size['height'];
        $config['new_image']      = $newImage;
        $config['source_image']   = $path;
        $config['create_thumb']   = FALSE;
        $config['image_library']  = 'gd2';
        $config['maintain_ratio'] = TRUE;
        $this->image_lib->clear();
        $this->image_lib->initialize($config);
        $this->image_lib->resize();

        $res = array('status'=>'1');
        if(!$this->image_lib->resize()){
            $res['status'] = '0';
            $res['error'] = $this->image_lib->display_errors();
        }
        return $res;
    }
    
    function googleVisionApi($img='', $typ='SAFE_SEARCH_DETECTION'){
        if(empty($img)){
            return 0;
        }
        $settings = getSettings();
        $api = $settings['google_api_key'];
        $url = "https://vision.googleapis.com/v1/images:annotate?key=".$api;
        $req = "{'requests':[{'image':{'source':{'imageUri':'$img'}},'features':[{'type':'$typ'}]}]}";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POST,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$req);
        curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $resp = curl_exec($ch);
        curl_close ($ch);

        $safe = 1;
        if(!empty($resp) && !empty($resp = json_decode($resp,true)) && isset($resp['responses']) && 
           isset($resp['responses'][0]) && isset($resp['responses'][0]['safeSearchAnnotation'])){
            $resp = $resp['responses'][0]['safeSearchAnnotation'];
            
            if($resp['adult']=='Very Likely'||$resp['adult']=='Likely'||$resp['adult']=='Possible'){
                $safe = 2;
            }
            if($resp['spoof']=='Very Likely'||$resp['spoof']=='Likely'){
                $safe = 2;
            }
            if($resp['medical']=='Very Likely'||$resp['medical']=='Likely'){
                $safe = 2;
            }
            if($resp['violence']=='Very Likely'||$resp['violence']=='Likely'){
                $safe = 2;
            }
            if($resp['racy']=='Very Likely'||$resp['racy']=='Likely'||$resp['racy']=='Possible'){
                $safe = 2;
            }
        }
        return $safe;
    }
}
?>
