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

class Provider extends CI_Controller {

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

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

	public function addProvider(){
		$template['page'] = 'Provider/providerForm';
        $template['menu'] = 'Organizer Management';
        $template['smenu'] = 'Add Organizer';
        $template['pTitle'] = "Add Organizer";
        $template['pDescription'] = "Create New Organizer";

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

	public function viewProviders(){
		$template['page'] = 'Provider/viewProvider';
        $template['menu'] = 'Organizer Management';
        $template['smenu'] = 'View Organizers';
        $template['pTitle'] = "View Organizers";
        $template['pDescription'] = "View and Manage Organizers";
        $template['page_head'] = "Organizer Management";

        $template['provider_data'] = $this->Provider_model->getProviderData('');

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

	public function getProviderData(){
		$resArr = array('status'=>0);
		if(!isset($_POST)||empty($_POST)||!isset($_POST['provider_id'])||empty($_POST['provider_id']) || 
		   !is_numeric($provider_id = decode_param($_POST['provider_id']))){
			echo json_encode($resArr);exit;
		}
		$view_all = (isset($_POST['view_all']) && $_POST['view_all'] == 1)?1:'0,1';
		$mechData = $this->Provider_model->getProviderData($provider_id,$view_all);

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

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

    function changeStatus(){
        if(!isset($_POST) || !isset($_POST['provider_id']) || empty($_POST['provider_id']) || 
           !isset($_POST['status']) || $_POST['status'] == ''){
            echo json_encode(array('status'=>'0'));exit;
        }
        $status = $_POST['status'];
        $provider_id = decode_param($_POST['provider_id']);
        $resp = $this->Provider_model->changeStatus($provider_id,$status);
        if($resp){
        	$this->load->model('Api_model');
			$providerData = $this->Provider_model->getProviderData($provider_id,'0,1');

			if(!empty($providerData)){
				$subject  = "Your Organizer Account is now activated";
				$email_id = $providerData->email;
	 			$template = getNotifTemplate();
				$message  = "<html>
								<body>
									Your Organizer Account for the username 
							 		<strong>".$providerData->username."</strong> is now activated. 
						 			Please use this link for access your account 
						 			<a href='".base_url()."'>".base_url()."</a><br>
								</body>
						     </html>";

	            if(isset($template['provider_activation_mail']) && 
	               !empty($template['provider_activation_mail'])){
	                $message = str_replace(array('{:user_name}','{:url}'),
	                					   array($providerData->username,base_url()),
	                                       $template['provider_activation_mail']);
	            }			
				$this->Api_model->send_mail($subject,$email_id,$message);
			}
            echo json_encode(array('status'=>'1'));exit;
        }
        echo json_encode(array('status'=>'0'));exit;
    }

	public function createProvider(){
		$err = 0;
		$errMsg = '';
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(!isset($_POST) || empty($_POST) || !isset($_FILES) || empty($_FILES)){
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Provider/addProvider'));
		}
		if($err == 0 && (!isset($_POST['display_name']) || empty($_POST['display_name']))){
			$err = 1;
			$errMsg = 'Provide a Display Name';
		}else if($err == 0 && (!isset($_POST['username']) || empty($_POST['username']))){
			$err = 1;
			$errMsg = 'Provide a User Name';
		}else if($err == 0 && (!isset($_POST['password']) || empty($_POST['password']) || 
								empty($_POST['password'] = md5($_POST['password'])))){
			$err = 1;
			$errMsg = 'Provide a Password';
		}else if($err == 0 && (!isset($_POST['name']) || empty($_POST['name']))){
			$err = 1;
			$errMsg = 'Provide a Name';
		}else if($err == 0 && (!isset($_POST['email']) || empty($_POST['email']))){
            $err = 1;
			$errMsg = 'Provide an Email ID';
        }else if($err == 0 && (!isset($_POST['phone']) || empty($_POST['phone']))){
            $err = 1;
			$errMsg = 'Provide a Phone Number';
        }
        
        if($err == 0){
	        $config = set_upload_service("assets/uploads/services");
	        $this->load->library('upload');
	        $config['file_name'] = time()."_".$_FILES['profile_image']['name'];
	        $this->upload->initialize($config);
	        if(!$this->upload->do_upload('profile_image')){
	        	$err = 1;
				$errMsg = $this->upload->display_errors();
	        }else{
	            $upload_data = $this->upload->data();
	            $_POST['profile_image'] = $config['upload_path']."/".$upload_data['file_name'];
	        }
	    }

		if($err == 1){
			$flashMsg['message'] = $errMsg;
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Provider/addProvider'));
		}

        $status = $this->Provider_model->addProvider($_POST);
        if($status == 1){
        	$this->load->model('Api_model');
			$subject  = "Your Organizer Account is now activated";
			$email_id = $_POST['email'];

 			$template = getNotifTemplate();
			$message  = "<html>
							<body>
								Your Organizer Account for the username 
						 		<strong>".$providerData->username."</strong> is now activated. Please use this link for access your account 
						 		<a href='".base_url()."'>".base_url()."</a><br>
							</body>
						 </html>";

            if(isset($template['provider_activation_mail']) && 
               !empty($template['provider_activation_mail'])){
                $message = str_replace(array('{:user_name}','{:url}'),
                					   array($email_id,base_url()),
                                       $template['provider_activation_mail']);
            }			
			$this->Api_model->send_mail($subject,$email_id,$message);

            $flashMsg =array('message'=>'Successfully Updated User Details..!','class'=>'success');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Provider/viewProviders'));
        } else if($status == 2){
            $flashMsg = array('message'=>'Email ID already exist..!','class'=>'error');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Provider/addProvider'));
        } else if($status == 3){
            $flashMsg = array('message'=>'Phone Number already exist..!','class'=>'error');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Provider/addProvider'));
        } else if($status == 4){
            $flashMsg = array('message'=>'User Name already exist..!','class'=>'error');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Provider/addProvider'));
        } else {
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Provider/addProvider'));
        }
	}

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

		$template['page'] = 'Provider/providerForm';
        $template['menu'] = 'Organizer Management';
        $template['smenu'] = 'Edit Organizer';
        $template['pTitle'] = "Edit Organizers";
        $template['pDescription'] = "Update Organizer Data";

        $template['provider_data'] = $this->Provider_model->getProviderData($provider_id,'0,1');
        $template['provider_id'] = encode_param($provider_id);
		$this->load->view('template',$template);
	}

	public function updateProvider($provider_id = ''){
		$err = 0;
		$errMsg = '';
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(!isset($_POST) || empty($_POST) || !isset($_FILES) || empty($_FILES)){
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Provider/addProvider'));
		}
		if($err == 0 && (!isset($_POST['display_name']) || empty($_POST['display_name']))){
			$err = 1;
			$errMsg = 'Provide a Display Name';
		}else if($err == 0 && (!isset($_POST['username']) || empty($_POST['username']))){
			$err = 1;
			$errMsg = 'Provide a User Name';
		}else if($err == 0 && (!isset($_POST['name']) || empty($_POST['name']))){
			$err = 1;
			$errMsg = 'Provide a Name';
		}else if($err == 0 && (!isset($_POST['email']) || empty($_POST['email']))){
            $err = 1;
			$errMsg = 'Provide an Email ID';
        }else if($err == 0 && (!isset($_POST['phone']) || empty($_POST['phone']))){
            $err = 1;
			$errMsg = 'Provide a Phone Number';
        }
    	
        if($err == 0){
	        $config = set_upload_service("assets/uploads/services");
	        $this->load->library('upload');
	        $config['file_name'] = time()."_".$_FILES['profile_image']['name'];
	        $this->upload->initialize($config);
	        if($this->upload->do_upload('profile_image')){
	            $upload_data = $this->upload->data();
	            $_POST['profile_image'] = $config['upload_path']."/".$upload_data['file_name'];
	        }
	    }

		if($err == 1){
			$flashMsg['message'] = $errMsg;
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Provider/editProviders/'.$provider_id));
		}
		
        $status = $this->Provider_model->updateProvider(decode_param($provider_id),$_POST);
        if($status == 1){
            $flashMsg =array('message'=>'Successfully Updated User Details..!','class'=>'success');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Provider/viewProviders'));
        } else if($status == 2){
            $flashMsg = array('message'=>'Email ID already exist..!','class'=>'error');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Provider/editProviders/'.$provider_id));
        } else if($status == 3){
            $flashMsg = array('message'=>'Phone Number already exist..!','class'=>'error');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Provider/editProviders/'.$provider_id));
        } else if($status == 4){
            $flashMsg = array('message'=>'User Name already exist..!','class'=>'error');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Provider/editProviders/'.$provider_id));
        } else {
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Provider/editProviders/'.$provider_id));
        }
	}

 	function getProviderPayDetails($provider_id = ''){
 		if(empty($provider_id)){
 			if($this->session->userdata('user_type') == 1){
	 			$provider_id = (isset($_POST['provider_id'])&&!empty($_POST['provider_id']))?$_POST['provider_id']:'';
	 		}else{
		 		$provider_id = $this->session->userdata('id');
	 		}
 		}

		$template['page'] = 'Provider/providerPayDetails';
        $template['page_desc'] = "Payment Details";
        $template['page_title'] = "Payment Management";
        
		$template['menu'] = "Payment Management";
		$template['sub_menu'] = "Payment Details";

 		$providerPayData = $this->Provider_model->getProviderPayData($provider_id);
 		$template['payedDetails'] = $providerPayData['payedDetails'];
 		$template['pendingDetails'] = $providerPayData['pendingDetails'];
 		
 		$template['user_type'] = $this->session->userdata('user_type');
 		$template['provider_id'] = encode_param($provider_id);
 		$template['provider_data'] = $this->Provider_model->getProviderData();
		$this->load->view('template',$template);
 	}
	
	function updateProviderPayDate(){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(!isset($_POST) || empty($_POST) || 
		   !isset($_POST['provider_id']) || empty($_POST['provider_id']) || 
		   !isset($_POST['last_payment_date']) || empty($_POST['last_payment_date'])){
			$this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Provider/editProviders/'.$provider_id));
		}
		$_POST['provider_id'] = (!is_numeric($_POST['provider_id']))?decode_param($_POST['provider_id']):$_POST['provider_id'];
		$_POST['last_payment_date'] = date('Y-m-d 00:00:00',strtotime($_POST['last_payment_date']));

        $status = $this->Provider_model->updatePaymentDate($_POST);

        if($status){
        	$flashMsg['class'] = 'success';
        	$flashMsg['message'] = 'Successfully Updated..!';
        }

        $this->session->set_flashdata('message', $flashMsg);
        redirect(base_url('Provider/getProviderPayDetails/'.$_POST['provider_id']));
	}

	function resetPassword($provider_id = ''){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(empty($provider_id) || !is_numeric($provider_id = decode_param($provider_id))){
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Provider/viewProviders'));
		}
		$unique_id = $this->Provider_model->resetPassword($provider_id);
		$providerData = $this->Provider_model->getProviderData($provider_id);

		if(empty($unique_id) || empty($providerData)){
			$this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Provider/viewProviders'));
		}

    	$this->load->model('Api_model');
		$subject   = "New Password for Organizer Account";
		$email_id  = $providerData->email;
		$template  = getNotifTemplate();
		$message   = "<html>
						<body>
							New password of your Organizer Account for the username 
					 		<strong>".$providerData->username."</strong> is <strong>".$unique_id."</strong><br>
						</body>
				     </html>";

        if(isset($template['provider_verify_mail']) && !empty($template['provider_verify_mail'])){
            $message = str_replace(array('{:user_name}','{:password}'),
            					   array($providerData->username,$resetLink),
                                   $template['provider_verify_mail']);
        }	
		$this->Api_model->send_mail($subject,$email_id,$message);

		$flashMsg = array('message'=>'Password Generated..!','class'=>'success');
		$this->session->set_flashdata('message', $flashMsg);
        redirect(base_url('Provider/viewProviders'));
	}


}
?>