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

class Issue extends CI_Controller {

	public function __construct() {
		parent::__construct();
		date_default_timezone_set("Asia/Kolkata");
		$this->load->model('Issue_model');

		if(!$this->session->userdata('logged_in')) {
			redirect(base_url());
		}
	}

	public function addIssue(){
		$template['page'] = 'Issue/issueForm';
        $template['menu'] = 'Issue Management';
        $template['smenu'] = 'Add Issue';
        $template['pTitle'] = "Add Issue";
        $template['pDescription'] = "Create New Issue";

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

	public function viewIssues(){
		$template['page'] = 'Issue/viewIssues';
        $template['menu'] = 'Issue Management';
        $template['smenu'] = 'View Issues';
        $template['pTitle'] = "View Issues";
        $template['pDescription'] = "View and Manage Issues";

        $template['issue_data'] = $this->Issue_model->getIssues('',1);
		$this->load->view('template',$template);
	}

	function changeStatus($issue_id = '',$status = '1'){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(empty($issue_id) || !is_numeric($issue_id = decode_param($issue_id))){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Issue/viewIssues'));
		}
		$status = $this->Issue_model->changeStatus($issue_id,$status);
		if(!$status){
			$this->session->set_flashdata('message',$flashMsg);
		}
		redirect(base_url('Issue/viewIssues'));
	}

	public function createIssue(){
		$err = 0;
		$errMsg = 'Something went wrong, please try again..!';
    	$this->load->library('upload',set_upload_service("assets/uploads/services"));
		$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('Issue/addIssue'));
		}
		if($err == 0 && (!isset($_POST['issue']) || empty($_POST['issue']))){
			$err = 1;
			$errMsg = 'Provide Issue Short Discription';
		}
		else if($err == 0 && (!isset($_FILES['issue_image']) || empty($_FILES['issue_image']))){
			$err = 1;
			$errMsg = 'Provide Issue Icon';
		}
		else if($err == 0 && (empty($_POST['issue_category']) || count($_POST['issue_category']) <= 0)){
			$err = 1;
			$errMsg = 'Provide Issue Category Type';
		}
		else if($err==0&&(empty($_POST['default_description'])||count($_POST['default_description'])<=0)){
			$err = 1;
			$errMsg = 'Provide Issue Category Discription';
		}
		else if($err==0&&(empty($_POST['default_service_fee'])||count($_POST['default_service_fee'])<=0)){
			$err = 1;
			$errMsg = 'Provide Issue Category Service Fee';
		}
		else if($err==0&&(empty($_FILES['issue_cat_image'])||!isset($_FILES['issue_cat_image']['name'])||
						  count($_FILES['issue_cat_image']['name']) <= 0)){
			$err = 1;
			$errMsg = 'Provide Issue Category Default Icon';
		} 
		else if($err==0&&(count($_POST['issue_category']) != count($_POST['default_description']) || 
					      count($_POST['issue_category']) != count($_POST['default_service_fee']) || 
						  count($_POST['issue_category']) != count($_FILES['issue_cat_image']['name']))){
			$err = 1;
		} 
		$files = $_FILES;
		if($err == 0){
			$typ = 0;
			$insertSubTyp = array();

			for ($typ = 0; $typ < count($_POST['issue_category']); $typ++) { 
				if(!isset($_POST['issue_category'][$typ]) || 
				   !isset($_POST['default_description'][$typ]) || 
				   !isset($_POST['default_service_fee'][$typ]) ||  
				   !isset($_FILES['issue_cat_image']['name'][$typ])){
				   	$err = 1;
					break;
				}
				$_FILES['file']['name'] = $files['issue_cat_image']['name'][$typ];
				$_FILES['file']['type'] = $files['issue_cat_image']['type'][$typ];
				$_FILES['file']['size'] = $files['issue_cat_image']['size'][$typ]; 
				$_FILES['file']['error'] = $files['issue_cat_image']['error'][$typ];
				$_FILES['file']['tmp_name'] = $files['issue_cat_image']['tmp_name'][$typ];

				if(!$this->upload->do_upload('file')){
					$err = 1;
	                $errMsg = $this->upload->display_errors();
	                break;
				}
				$imgData = $this->upload->data();
				$image_name = "assets/uploads/services/".$imgData['file_name'];

				$insertSubTyp[] = array('issue_category' => $_POST['issue_category'][$typ],
									'issue_cat_image' => $image_name,'status'=>'1',
									'default_service_fee' => $_POST['default_service_fee'][$typ],
									'default_description' => $_POST['default_description'][$typ]);
			}
			unset($_POST['issue_category']);
			unset($_POST['default_service_fee']);
			unset($_POST['default_description']);

			if($this->upload->do_upload('issue_image')){
				$imgData = $this->upload->data();
				$_POST['issue_image'] = "assets/uploads/services/".$imgData['file_name'];
			} else {
				$err = 1;
                $errMsg = $this->upload->display_errors();
                break;
			}
		}
		if($err == 1){
			$flashMsg['message'] = $errMsg;
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Issue/addIssue'));
		}

        $status = $this->Issue_model->addIssue($_POST,$insertSubTyp);
        if($status == 1){
            $flashMsg =array('message'=>'Successfully Updated Issue Details..!','class'=>'success');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Issue/viewIssues'));
        } else {
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Issue/addIssue'));
        }
	}

	public function editIssue($issue_id = ''){
		$flashMsg=array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(empty($issue_id) || !is_numeric($issue_id = decode_param($issue_id))){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Issue/viewIssues'));
		}

		$template['page'] = 'Issue/issueForm';
        $template['menu'] = 'Issue Management';
        $template['smenu'] = 'Edit Issue';
        $template['pTitle'] = "Edit Issue";
        $template['pDescription'] = "Update Issue Data";

        $template['issue_id'] = encode_param($issue_id);
        $template['issue_data'] = $this->Issue_model->getIssueDetails($issue_id,1);
		if(empty($template['issue_data'])){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Issue/viewIssues'));
		}
		$this->load->view('template',$template);
	}

	public function updateIssue($issue_id = ''){
		$err = 0;
		$errMsg = 'Something went wrong, please try again..!';
    	$this->load->library('upload',set_upload_service("assets/uploads/services"));
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');

		if(empty($issue_id) || !is_numeric($issue_id = decode_param($issue_id))){
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Issue/viewIssues'));
		}
		if(!isset($_POST) || empty($_POST)){
			$err = 1;
		}
		if($err == 0 && (!isset($_POST['issue']) || empty($_POST['issue']))){
			$err = 1;
			$errMsg = 'Provide Issue Short Discription';
		}
		else if($err == 0 && (!isset($_POST['extSubTypes']) || empty($_POST['extSubTypes']))){
			$err = 1;
		} 

		$insertSubTyp = array();
		$updateSubTyp = array();
		$issue_data = array('issue'=>$_POST['issue']);
		if($err == 0){
			foreach ($_POST['extSubTypes'] AS $typ_id) {
				if(isset($_POST['issue_category_'.$typ_id]) && 
				   !empty($_POST['issue_category_'.$typ_id])){
					$issue_category = $_POST['issue_category_'.$typ_id];
					$updateSubTyp[$typ_id]['issue_category'] = $issue_category;
				}
				if(isset($_POST['default_description_'.$typ_id]) && 
				   !empty($_POST['default_description_'.$typ_id])){
					$default_description = $_POST['default_description_'.$typ_id];
					$updateSubTyp[$typ_id]['default_description'] = $default_description;
				}
				if(isset($_POST['default_service_fee_'.$typ_id]) && 
				   !empty($_POST['default_service_fee_'.$typ_id])){
					$default_service_fee = $_POST['default_service_fee_'.$typ_id];
					$updateSubTyp[$typ_id]['default_service_fee'] = $default_service_fee;
				}
				if(isset($_FILES['issue_cat_image_'.$typ_id]) && 
				   isset($_FILES['issue_cat_image_'.$typ_id]['name']) && 
				   !empty($_FILES['issue_cat_image_'.$typ_id]['name']) && 
				   $this->upload->do_upload('issue_cat_image_'.$typ_id)){
					$imgData = $this->upload->data();
					$issue_cat_image = "assets/uploads/services/".$imgData['file_name'];
					$updateSubTyp[$typ_id]['issue_cat_image'] = $issue_cat_image;
				}

			}

			if(isset($_POST['issue_category']) && count($_POST['issue_category']) > 0 && 
			   isset($_POST['default_description']) && count($_POST['default_description']) > 0 && 
			   isset($_POST['default_service_fee']) && count($_POST['default_service_fee']) > 0 && 
			   isset($_FILES['issue_cat_image']) && isset($_FILES['issue_cat_image']['name']) && 
			   count($_FILES['issue_cat_image']['name']) > 0 && 
			   count($_POST['issue_category']) == count($_POST['default_description']) && 
			   count($_POST['issue_category']) == count($_POST['default_service_fee']) && 
			   count($_POST['issue_category']) == count($_FILES['issue_cat_image']['name'])){
				
				$typ = 0;
				$files = $_FILES;

				for ($typ = 0; $typ < count($_POST['issue_category']); $typ++) {

					if(!isset($_POST['issue_category'][$typ]) || 
					   !isset($_POST['default_description'][$typ]) || 
					   !isset($_POST['default_service_fee'][$typ]) ||  
					   !isset($_FILES['issue_cat_image']) || 
					   !isset($_FILES['issue_cat_image']['name']) || 
					   !isset($_FILES['issue_cat_image']['name'][$typ])){
						break;
					}
					$_FILES['file']['name'] = $files['issue_cat_image']['name'][$typ];
					$_FILES['file']['type'] = $files['issue_cat_image']['type'][$typ];
					$_FILES['file']['size'] = $files['issue_cat_image']['size'][$typ]; 
					$_FILES['file']['error'] = $files['issue_cat_image']['error'][$typ];
					$_FILES['file']['tmp_name'] = $files['issue_cat_image']['tmp_name'][$typ];

					if(!$this->upload->do_upload('file')){
		                continue;
					}
					$imgData = $this->upload->data();
					$image_name = "assets/uploads/services/".$imgData['file_name'];

					$insertSubTyp[] = array('issue_category' => $_POST['issue_category'][$typ],
										'issue_cat_image' => $image_name,'status'=>'1',
										'default_service_fee' => $_POST['default_service_fee'][$typ],
										'default_description' => $_POST['default_description'][$typ],
										'issue_id'=>$issue_id);
				}
			}		
			if($this->upload->do_upload('issue_image')){
				$imgData = $this->upload->data();
				$issue_data['issue_image'] = "assets/uploads/services/".$imgData['file_name'];
			}	
		}
 
		if($err == 1){
			$flashMsg['message'] = $errMsg;
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Issue/editIssue/'.encode_param($issue_id)));
		}

        $status = $this->Issue_model->updateIssue($issue_id,$issue_data,$updateSubTyp,$insertSubTyp);
        if($status == 1){
            $flashMsg =array('message'=>'Successfully Updated Issue Details..!','class'=>'success');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Issue/viewIssues'));
        } else {
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Issue/editIssue/'.encode_param($issue_id)));
        }
	}

	public function issueMapping(){
		if($this->session->userdata('user_type') == 1){
			redirect(base_url('Issue/viewIssues'));
		}

		$template['page'] = 'Issue/issueMapping';
        $template['menu'] = 'Issue Management';
        $template['smenu'] = 'Issue Mapping';
        $template['pTitle'] = "Issue Mapping";
        $template['pDescription'] = "Creating Custom Issues";

        $mechanic_id = $this->session->userdata('id');
        $template['issue_data'] = $this->Issue_model->getUnMappedIssues($mechanic_id,1);
        $template['mechanic_id'] = encode_param($mechanic_id);
        if(empty($template['issue_data'])){
			$this->session->set_flashdata('message',array('message'=>'Currently you have mapped all the existing issue categories, add new category or manage mapped issues..!','class'=>'error'));
        	redirect(base_url('Issue/viewMappedIssues/'.$mechanic_id));
		}
		$this->load->view('template',$template);
	}

	public function createMechIssue(){
		$err = 0;
		$errMsg = '';
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(!isset($_POST) || empty($_POST) || !isset($_POST['mapping_type']) ||
		   !isset($_POST['issue_id']) || empty($_POST['issue_id']) || 
		   !isset($_POST['mechanic_id']) || empty($_POST['mechanic_id']) || 
		   !is_numeric($_POST['issue_id'] = decode_param($_POST['issue_id'])) || 
		   !is_numeric($_POST['mechanic_id'] = decode_param($_POST['mechanic_id'])) || 
		   ($_POST['mapping_type'] == 1 && 
   			  (!isset($_POST['issue_cat_ids']) || empty($_POST['issue_cat_ids'])))){
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Issue/issueMapping'));
		}
		$custom_issue = $this->genIssueMapInsertData($_POST['mapping_type'],$_POST);
		if(empty($custom_issue)){
			$this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Issue/issueMapping'));
		}

        $status = $this->Issue_model->addMechIssue($custom_issue);
        if($status == 1){
            $flashMsg =array('message'=>'Successfully Created..!','class'=>'success');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Issue/viewMappedIssues'));
        } else {
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Issue/issueMapping'));
        }
	}

 	function viewMappedIssues($mechanic_id = ''){
 		if(!empty($mechanic_id)){
 			$mechanic_id = (!is_numeric($mechanic_id))?decode_param($mechanic_id):$mechanic_id;
 		}
        $mechanic_data = '';
 		if($this->session->userdata('user_type') == 1){
 			$this->load->model('Mechanic_model');
			$mechanic_data = $this->Mechanic_model->getMechanic('',1);
	 		if(isset($_POST['mechanic_id']) && !empty($_POST['mechanic_id'])){
	 			$mechanic_id = $_POST['mechanic_id'];
	 			$mechanic_id = (!is_numeric($mechanic_id))?decode_param($mechanic_id):$mechanic_id;
	 		}
 		} else {
 			$mechanic_id = $this->session->userdata('id');
 		}

		$template['page'] = 'Issue/viewMappedIssues';
        $template['menu'] = 'Issue Management';
        $template['smenu'] = 'Manage Mapped Issues';
        $template['pTitle'] = "Manage Mapped Issues";
        $template['pDescription'] = "View and Manage Mapped Issues";
 		
 		$template['mechanic_id'] = $mechanic_id;
 		$template['mechanic_data'] = $mechanic_data;
 		$template['mechanicIssueData'] = $this->Issue_model->getMechanicIssues($mechanic_id,'',1);
		$this->load->view('template',$template);
 	}

 	function changeMappedIssueStatus($mechanic_id = '',$issue_id = '',$status = '1'){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(empty($issue_id) || !is_numeric($issue_id  = decode_param($issue_id)) || 
		   empty($mechanic_id) || !is_numeric($mechanic_id  = decode_param($mechanic_id))){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Issue/viewMappedIssues/'.encode_param($mechanic_id)));
		}
		$status = $this->Issue_model->changeMappedIssueStatus($mechanic_id,$issue_id,$status);
		if(!$status){
			$this->session->set_flashdata('message',$flashMsg);
		}
		redirect(base_url('Issue/viewMappedIssues/'.encode_param($mechanic_id)));
 	}


	public function editMechanicIssues($mechanic_id = '',$issue_id = ''){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(empty($issue_id) || !is_numeric($issue_id = decode_param($issue_id)) || 
		   empty($mechanic_id) || !is_numeric($mechanic_id = decode_param($mechanic_id))){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Issue/viewMappedIssues'));
		}

		$template['page'] = 'Issue/issueMapping';
        $template['menu'] = 'Issue Management';
        $template['smenu'] = 'Edit Mechanic Issue';
        $template['pTitle'] = "Edit Mechanic Issue Management";
        $template['pDescription'] = "Update Custom Mechanic Issue Data";

        $template['issue_id'] = encode_param($issue_id);
        $template['mechanic_id'] = encode_param($mechanic_id);
        $template['issue_data'] = $this->Issue_model->getIssues('',1);
 		$template['mechanicIssueData'] = $this->Issue_model->getMechanicIssues($mechanic_id,$issue_id,1);

		if(empty($template['mechanicIssueData']) || !isset($template['mechanicIssueData'][$issue_id])){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Issue/viewMappedIssues/'.encode_param($mechanic_id)));
		}
		$template['mechanicIssueData'] = $template['mechanicIssueData'][$issue_id];
		$this->load->view('template',$template);
	}

	public function updateMechIssue($mechanic_id = '',$issue_id = ''){
		$err = 0;
		$errMsg = '';
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		$editPage =base_url('Issue/editMechanicIssues/'.encode_param($mechanic_id).'/'.encode_param($issue_id));
		if(!isset($_POST) || empty($_POST) || !isset($_POST['mapping_type']) ||
		   !isset($_POST['issue_id']) || empty($_POST['issue_id']) || 
		   !isset($_POST['mechanic_id']) || empty($_POST['mechanic_id']) || 
		   !is_numeric($_POST['issue_id'] = decode_param($_POST['issue_id'])) || 
		   !is_numeric($_POST['mechanic_id'] = decode_param($_POST['mechanic_id'])) || 
		   ($_POST['mapping_type']==1&&(!isset($_POST['issue_cat_ids'])||empty($_POST['issue_cat_ids'])))){
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Issue/viewMappedIssues'));
		}
		$custom_issue = $this->genIssueMapInsertData($_POST['mapping_type'],$_POST);
		if(empty($custom_issue)){
			$this->session->set_flashdata('message', $flashMsg);
            redirect(base_url($editPage));
		}

        $status = $this->Issue_model->updateMechIssue($_POST['mechanic_id'],$_POST['issue_id'],$custom_issue);
        if($status == 1){
            $flashMsg =array('message'=>'Successfully Created..!','class'=>'success');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Issue/viewMappedIssues/'.encode_param($mechanic_id)));
        } else {
            $this->session->set_flashdata('message', $flashMsg);
            redirect($editPage);
        }
	}
	

	function getIssueDetails(){
		$resArr = array('status'=>0);
		if(!isset($_POST)||empty($_POST)||!isset($_POST['issue_id'])||empty($_POST['issue_id']) || 
		   !is_numeric($issue_id = decode_param($_POST['issue_id']))){
			echo json_encode($resArr);exit;
		}
		$issue_data = $this->Issue_model->getIssueDetails($issue_id);

		if(empty($issue_data)){
			echo json_encode($resArr);exit;
		}

		$resArr['status'] = 1;
		$resArr['data'] = $issue_data;
		echo json_encode($resArr);exit;
	}

	function genIssueMapInsertData($mapping_type = '', $mapping_data = ''){
		if(empty($mapping_data) || $mapping_type == ''){
			return 0;
		}

		$custData = array();
		if($mapping_type == 1){
			foreach($mapping_data['issue_cat_ids'] AS $type_ids) {
				if(isset($mapping_data['default_service_fee_'.$type_ids]) && 
				   !empty($mapping_data['default_service_fee_'.$type_ids]) && 
				   isset($mapping_data['default_description_'.$type_ids]) && 
				   !empty($mapping_data['default_description_'.$type_ids])){

					$custData[] = array('issue_id'=>$mapping_data['issue_id'],
										'mechanic_id'=>$mapping_data['mechanic_id'],
						                'issue_cat_id'=>$type_ids,
										'custom_description'=>$mapping_data['default_description_'.$type_ids],
										'custom_service_fee'=>$mapping_data['default_service_fee_'.$type_ids]);
				}
			}
		} else {
			$custData[] = array('issue_id'=>$mapping_data['issue_id'],
								    'mechanic_id'=>$mapping_data['mechanic_id']);
		}

		return $custData;
	}
}
?>