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

class Customer extends CI_Controller {

 public function __construct() {
        parent::__construct();
        date_default_timezone_set("Asia/Kolkata");
        $this->load->model('Customer_model');
         $this->load->helper('generals_helper');
        if(!$this->session->userdata('logged_in')) {
            redirect(base_url());
        }

         
    }



	public function index(){
       
		$template['page'] = 'Customer/list';
        $template['menu'] = 'Customer Management';
        $template['smenu'] = 'View Customers';
        $template['pTitle'] = "View Customers";
        $template['pDescription'] = "View and Manage Customers";
        $template['page_head'] = "Customer Management";
        $template['datatable'] = 1;
        //$template['customer_data'] = $this->Customer_model->getCustomerData();

		$this->load->view('template',$template);
	}
public function create(){
        
        $template['page'] = 'Customer/create';
        $template['menu'] = 'Customer Management';
        $template['smenu'] = 'Add Customer';
        $template['pTitle'] = "Add Customer";
        $template['pDescription'] = "Create New Customer";

        $this->load->view('template',$template);
    }
	public function getCustomerData(){
		$resArr = array('status'=>0);
		if(!isset($_POST)||empty($_POST)||!isset($_POST['customer_id'])||empty($_POST['customer_id']) || 
		   !is_numeric($customer_id = $_POST['customer_id'])){
			echo json_encode($resArr);exit;
		}
		 $view_all = (isset($_POST['view_all']) && !empty($_POST['view_all']))?$_POST['view_all']:'';
        //$view_all = (isset($_POST['view_all']) && $_POST['view_all'] == 1)?1:0;
		$mechData = $this->Customer_model->getCustomerData($customer_id,$view_all);
      //echo json_encode($mechData);exit;
		if(empty($mechData)){
			echo json_encode($resArr);exit;
		}

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

	function changeStatus($customer_id = '',$status ='1'){
	
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'danger');
		if(empty($customer_id) || !is_numeric($customer_id = decode_param($customer_id))){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Customer'));
		}
		$status = $this->Customer_model->changeStatus($customer_id,$status);
		if(!$status){
			$this->session->set_flashdata('message',$flashMsg);
		}
		redirect(base_url('Customer'));
	}

	public function createCustomer(){


		$err = 0;
		$errMsg = '';
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'danger');
		if(!isset($_POST) || empty($_POST) || !isset($_FILES) || empty($_FILES)){
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Customer/create'));
		}
		if($err == 0 && (!isset($_POST['name']) || empty($_POST['name']))){
			$err = 1;
			$errMsg = 'Provide Customer Name';
		}else if($err == 0 && (!isset($_POST['email_id']) || empty($_POST['email_id']))){
			$err = 1;
			$errMsg = 'Provide a Customer Email';
		}else if($err == 0 && (!isset($_POST['phone_no']) || empty($_POST['phone_no']))){
			$err = 1;
			$errMsg = 'Provide Customer Phone';
	
        }else if($err == 0 && (!isset($_POST['password']) || empty($_POST['password']))){
            $err = 1;
			$errMsg = 'Provide a password';
        }
        
        if($err == 0){
	        $config = set_upload_service("assets/uploads/customer");
	        $this->load->library('upload');
	        $config['file_name'] = time()."_".$_FILES['profile_photo']['name'];
	        $this->upload->initialize($config);
	        if(!$this->upload->do_upload('profile_photo')){
	        	$err = 1;
				$errMsg = $this->upload->display_errors();
	        }else{
	            $upload_data = $this->upload->data();
	             $image = $upload_data['file_name'];
            $new_array = array('width'=>100, 'height'=>100);
           
	            $image_file = $config['upload_path']."/".$upload_data['file_name'];
	          
             $_POST['profile_photo'] = $image_file;
	        }
	    }

		if($err == 1){
			$flashMsg['message'] = $errMsg;
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Customer/create'));
		}
		$temp_password = rand(10000000, 99999999);
		$_POST['password'] = md5($temp_password);

        $status = $this->Customer_model->addCustomer($_POST);

        if($status['status'] == 1){
			
            $template = getNotifTemplate();
			$to =$_POST['email'];
                        $sender_email = "hello@access.sa";
                        $data['name']=$_POST['name'];
                        $data['email']=$_POST['email'];
                        $data['registration_mail']=$template['registration_mail'];
                        $data['password']=$temp_password;
                        $mail_head = "Your Access Account is now activated";
                    if(isset($template['registration_mail']) && !empty($template['registration_mail'])){

	                    
                 $mail_status = send_custom_email($sender_email,$mail_head,$to,'Customer Login', $this->load->view('template/mail_template/customer_login_edit', $data,TRUE),'');


                       }else{
       
                 $mail_status = send_custom_email($sender_email,$mail_head,$to,'Customer Login', $this->load->view('template/mail_template/customer_login', $data,TRUE),'');
             

                       }
                        
                    

            $flashMsg =array('message'=>'Please add custom vehicle details..!','class'=>'success','customer_id'=>$status['customer_id']);
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Vehicle_details/create/'.encode_param($status['customer_id'])));
        } else if($status == 2){
            $flashMsg = array('message'=>'Email ID already exist..!','class'=>'danger');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Customer/create'));
        } else if($status == 3){
            $flashMsg = array('message'=>'Phone Number already exist..!','class'=>'danger');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Customer/create'));
        } else if($status == 4){
            $flashMsg = array('message'=>'User Name already exist..!','class'=>'danger');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Customer/create'));
        } else {
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Customer/create'));
        }
	}
	public function editCustomers($customer_id){
       
		$id=decode_param($customer_id);
 
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'danger');
		if(empty($customer_id) || !is_numeric($customer_id = decode_param($customer_id))){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Customer'));
		}

		$template['page'] = 'Customer/create';
        $template['menu'] = 'Customer Management';
        $template['smenu'] = 'Edit Customer';
        $template['pTitle'] = "Edit Customers";
        $template['pDescription'] = "Update Customer Data";
         

        $template['customer_data'] = $this->Customer_model->getCustomerData($id);
        $template['customer_id'] =encode_param($id);

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

	public function updateCustomer($customer_id = ''){
		$id=decode_param($customer_id);
		$err = 0;
		$errMsg = '';
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'danger');
		if(!isset($_POST) || empty($_POST) || !isset($_FILES) || empty($_FILES)){
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Customer/create'));
		}
		
		if($err == 0 && (!isset($_POST['name']) || empty($_POST['name']))){
			$err = 1;
			$errMsg = 'Provide Customer Name';
		}else if($err == 0 && (!isset($_POST['email_id']) || empty($_POST['email_id']))){
			$err = 1;
			$errMsg = 'Provide a Customer Email';
		}else if($err == 0 && (!isset($_POST['phone_no']) || empty($_POST['phone_no']))){
			$err = 1;
			$errMsg = 'Provide Customer Phone';
	
        }else if($err == 0 && (!isset($_POST['password']) || empty($_POST['password']))){
            $err = 1;
            $errMsg = 'Provide a password';
        }
    	
        if($err == 0){
	        $config = set_upload_service("uploads/customer");
	        $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();
	             $image = $upload_data['file_name'];
            $new_array = array('width'=>100, 'height'=>100);
            $img_file = imageResize($image, $new_array, './uploads/customer/');
            unlink('./uploads/customer/'.$image);
            move_files('/uploads/customer/'.$img_file);
            $image_file = 'assets/uploads/customer/'.$img_file;
	           
                $_POST['profile_image'] = $image_file;
	        }
	    }

		if($err == 1){
			$flashMsg['message'] = $errMsg;
			$this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Customer/editCustomers/'.$customer_id));
		}
		
        $status = $this->Customer_model->updateCustomer($id,$_POST);
       
        if($status == 1){
            $flashMsg = array('message'=>'Update Vehicle Data!','class'=>'success');
            $this->session->set_flashdata('message', $flashMsg);
           redirect(base_url('Vehicle_details/edit/'.encode_param($id)));
        } else if($status == 2){
            $flashMsg = array('message'=>'Email ID already exist..!','class'=>'danger');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Customer/editCustomers/'.$customer_id));
        } else if($status == 3){
            $flashMsg = array('message'=>'Phone Number already exist..!','class'=>'danger');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Customer/editCustomers/'.$customer_id));
        } else if($status == 4){
            $flashMsg = array('message'=>'User Name already exist..!','class'=>'danger');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Customer/editCustomers/'.$customer_id));
        } 
        else {
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Customer/editCustomers/'.$customer_id));
        }
	}



public function check_email_availability() {
   			
		$email=$this->input->post('email');

        $result = $this->Customer_model->email_availability_check($email);
		echo json_encode($result);
		
		
	}


public function get_all_customer() {
	$data = $_GET;
//print_r($data);exit;
	$col = $data['order'][0]['column'];
	$col_type = $data['order'][0]['dir'];

	 $columns = array("customer.cust_id","customer.name","customer.email_id","customer.phone_no");
	
	
	$value['order_by'] = $columns[$col];
	$value['order_type'] = $col_type;
	$value['search'] = $data['search']['value'];
	$value['start'] = $data['start'];
	$value['length'] = $data['length'];
	$value['where'] = '';

	if(!empty($value['search'])) {
            $where = array();
            foreach($columns as $c) {
                $where_data[] = $c." like '%".$value['search']."%' ";
            }
            $where = implode(" OR ", $where_data);
            $where = "(".$where.")";
            $value['where'] = $where;
        }



	$prod_list = $this->Customer_model->get_all_customer($value);

	
   
    $all_list = $this->Customer_model->get_all_customer();

	$recordsTotal = count($all_list);

    $filtered = count($all_list);
    if($value['where']!='') {
        $value['length'] = '-1';
        $all_list = $this->Customer_model->get_all_customer($value);
        $filtered = count($all_list);
    }

	$data = array();
	foreach ($prod_list  as $r) {


$action = "<a class='btn btn-info btn-sm view_wish' onclick='getCustomerDetails(".$r->cust_id.")'><i class='fa fa-fw fa-eye'></i>View</a>";

                // $action .= "  <a class='btn btn-info btn-sm' href='".base_url()."Customer/editCustomers/".encode_param($r->cust_id)."'>
                //                              <i class='fa fa-pencil'></i>Edit
                //                          </a>";
                                  
                                      
                                               
                         $action .=   "  <a class='btn btn-sm btn-danger' 
                            href='".base_url()."Customer/changeStatus/".encode_param($r->cust_id).'/2' ."'
                            onClick='return doconfirm()'>
                          <i class='fa fa-fw fa-trash'></i>Delete
                        </a>";   
                        
                       
                                        
                         if($r->status == 1){ 
                      $action .=   " <a class='btn btn-sm btn-success' style='background-color:#ac2925' href='".base_url()."Customer/changeStatus/".encode_param($r->cust_id).'/0' ."'>
                                             <i class='fa fa-cog'></i> De-activate
                                           </a>";
                                         } else { 
              $action .=  " <a class='btn btn-sm btn-success' href='".base_url()."Customer/changeStatus/".encode_param($r->cust_id).'/1' ."'>
                       <i class='fa fa-cog'></i> Activate
                                </a>";
                        } 
                        


                array_push($data, array(
                    $r->cust_id,
                    $r->name,
                    $r->email_id,
                    $r->phone_no,
                    $r->area,
                    $action
                     ));
            }


	echo json_encode(array('recordsFiltered' => $filtered, 'recordsTotal' => $recordsTotal, 'data' => $data));
  
}


	
}
?>