<?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/Kolkata");
        $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();

		$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(){
		$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']) || empty($_POST['event_name']))){
            $err = 1;
            $errMsg = 'Provide Event Name';
        } else if ($err == 0 && (!isset($_POST['event_discription']) || $_POST['event_discription']=='')){
            $err = 1;
            $errMsg = 'Provide Event Discription';
        } 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['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++){
                $cstmSeatLayout[] = array('color'=>$_POST['seat_color'][$i],
                                          'price'=>$_POST['seat_price'][$i],
                                          'capacity'=>$_POST['seat_capacity'][$i]);
            }
            $_POST['custom_seat_layout'] = json_encode($cstmSeatLayout);
        } else {
            $_POST['seat_pricing'] = json_encode(
                                            array('price'=>$_POST['price'],
                                                  'price_details'=>$_POST['price_details']
                                                  )
                                                );
        }

        $provider = ($this->session->userdata['user_type']==1)?'1':$this->session->userdata['id'];
        $eventData = array('venue_id'=>$_POST['venue_id'],
                           'event_name'=>$_POST['event_name'],
                           'category_id'=>$_POST['category_id'],
                           'provider_id'=>$provider,
                           'seat_pricing'=>$_POST['seat_pricing'],
                           'event_discription'=>$_POST['event_discription'],
                           'custom_seat_layout'=>$_POST['custom_seat_layout']);

        $event_id = $this->Event_model->createEvent($eventData);
        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);

            $evtMediaData = array();
            if(!empty($files = $_FILES)){
                $images = array();
                $this->load->library('upload',set_upload_service("assets/uploads/services"));
                for ($typ = 0; $typ < count($files); $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];

                    if($this->upload->do_upload('file')){
                        $imgData = $this->upload->data();
                        $evtMediaData[] = array(
                                            'event_id'=>$event_id,
                                            'media_type'=>'1',
                                            'media_url'=>"assets/uploads/services/".$imgData['file_name']);
                    } 
                }
                $status = $this->Event_model->createEventMedia($evtMediaData);
            }

            $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=''){
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');

        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'));
        }

        $err = 0;
        $errMsg = '';
        if($err == 0 && (!isset($_POST['event_name']) || empty($_POST['event_name']))){
            $err = 1;
            $errMsg = 'Provide Event Name';
        } else if ($err == 0 && (!isset($_POST['event_discription']) || $_POST['event_discription']=='')){
            $err = 1;
            $errMsg = 'Provide Event Discription';
        } 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['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++){
                $cstmSeatLayout[] = array('color'=>$_POST['seat_color'][$i],
                                          'price'=>$_POST['seat_price'][$i],
                                          'capacity'=>$_POST['seat_capacity'][$i]);
            }
            $_POST['custom_seat_layout'] = json_encode($cstmSeatLayout);
        } else {
            $_POST['seat_pricing'] = json_encode(
                                            array('price'=>$_POST['price'],
                                                  'price_details'=>$_POST['price_details']
                                                  )
                                                );
        }

        $provider = ($this->session->userdata['user_type']==1)?'1':$this->session->userdata['id'];
        $eventData = array('venue_id'=>$_POST['venue_id'],
                           'event_name'=>$_POST['event_name'],
                           'category_id'=>$_POST['category_id'],
                           'provider_id'=>$provider,
                           'seat_pricing'=>$_POST['seat_pricing'],
                           'event_discription'=>$_POST['event_discription'],
                           'custom_seat_layout'=>$_POST['custom_seat_layout']);

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

        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);

            $evtMediaData = array();
            if(isset($_FILES) && isset($_FILES['event_image']) && isset($_FILES['event_image']['name']) && 
               count($_FILES['event_image']['name']) > 1){
                $files = $_FILES;

                $images = array();
                $this->load->library('upload',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];

                    if($this->upload->do_upload('file')){
                        $imgData = $this->upload->data();
                        $evtMediaData[] = array(
                                            'event_id'=>$event_id,
                                            'media_type'=>'1',
                                            'media_url'=>"assets/uploads/services/".$imgData['file_name']);
                    } 
                }
            }

            $existingImages = (isset($_POST['existingImages']) && !empty($_POST['existingImages']))?
                              $_POST['existingImages']:'';
            $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 changeStatus($event_id = '',$status = '1'){
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(empty($event_id)){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Event/listEvents'));
        }
        $event_id = decode_param($event_id);
        $status = $this->Event_model->changeStatus($event_id,$status);
        if(!$status){
            $this->session->set_flashdata('message',$flashMsg);
        }
        redirect(base_url('Event/listEvents'));
    }

    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;
    }
}
?>