<?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->model('Vehicle_model');
		
		if(!$this->session->userdata('logged_in')) {
			redirect(base_url('Login'));
		}

        if($this->session->userdata['user_type'] != 1){
            redirect(base_url());
        }
 	}

    public function addCustomerUser(){
        $template['page'] = 'Customer/add-customer-user';

        $template['pTitle'] = "Add New Customer";
        $template['pDescription'] = "Create New Customer";

        $template['menu'] = "Customer Management";
        $template['smenu'] = "Add Customer";
        $template['veh_data']['make'] = $this->Vehicle_model->getVehBrand('',1);
        $template['veh_data']['model'] = $this->Vehicle_model->getVehModel('',1);
        $this->load->view('template',$template);
    }
    
    public function listCustomerUsers(){
        $template['page'] = 'Customer/list-customer-users';

        $template['pTitle'] = "View Customers";
        $template['pDescription'] = "View and Manage Customers"; 

        $template['menu'] = "Customer Management";
        $template['smenu'] = "View Customers";

        $template['customerData'] = $this->Customer_model->getCustomer();
        $this->load->view('template',$template);
    }

    public function createCustomer(){
        $err = 0;
        $errMsg = '';
        $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('Customer/addCustomerUser'));
        }
        if($err == 0 && (!isset($_POST['first_name']) || empty($_POST['first_name']))){
            $err = 1;
            $errMsg = 'Provide a First Name';
        }
        else if($err == 0 && (!isset($_POST['last_name']) || empty($_POST['last_name']))){
            $err = 1;
            $errMsg = 'Provide a Last Name';
        }
        else if($err == 0 && (!isset($_POST['phone']) || empty($_POST['phone']))){
            $err = 1;
            $errMsg = 'Provide a Phone Number';
        }
        else if($err == 0 && (!isset($_POST['email']) || empty($_POST['email']))){
            $err = 1;
            $errMsg = 'Provide an Email ID';
        }
        else if($err == 0 && (!isset($_POST['date_of_birth']) || empty($_POST['date_of_birth']))){
            $err = 1;
            $errMsg = 'Provide Date Of Birth';
        }
        else if($err == 0 && (!isset($_POST['address']) || empty($_POST['address']))){
            $err = 1;
            $errMsg = 'Provide an Address';
        }
        else if($err == 0 && (!isset($_FILES['profile_image']) || empty($_FILES['profile_image']))){
            $err = 1;
            $errMsg = 'Provide Profile Picture';
        }
        $_POST['profile_image'] = '';
        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('Customer/addCustomerUser'));
        }
        $saved_vehicles = (!empty($_POST['saved_vehicles']))?implode(',',$_POST['saved_vehicles']):'';
        unset($_POST['saved_vehicles']);

        $status = $this->Customer_model->createCustomer($_POST,$saved_vehicles);
        if($status == 1){
            $flashMsg['class'] = 'success';
            $flashMsg['message'] = 'User Created';

            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Customer/listCustomerUsers'));
        }else if($status == 2){
            $flashMsg['message'] = 'Email ID already in use.';
        }else if($status == 3){
            $flashMsg['message'] = 'Phone Number already in use.';
        }
        $this->session->set_flashdata('message',$flashMsg);
        redirect(base_url('Customer/addCustomerUser'));
    }

    public function calculateAge($birthDate = ''){
        if(empty($birthDate))
            return;

        $birthDate = explode("/", $birthDate);
        $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
                ? ((date("Y") - $birthDate[2]) - 1)
                : (date("Y") - $birthDate[2]));
        return $age;
    }

    public function getCustomerData(){
        $return_arr = array('status'=>'0');
        if(!isset($_POST)||empty($_POST)||!isset($_POST['customer_id'])||empty($_POST['customer_id'])){
            echo json_encode($return_arr);exit;
        }
        $customer_id = decode_param($_POST['customer_id']);
        $customer_data = $this->Customer_model->getCustomer(array('customer_id'=>$customer_id));
        if(!empty($customer_data)){
            $return_arr['status'] = 1;
            $return_arr['customer_data'] = $customer_data;
        }
        echo json_encode($return_arr);exit;
    }

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

    function editCustomer($customer_id = ''){
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(empty($customer_id)){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Customer/listCustomerUsers'));
        }

        $template['page'] = 'Customer/add-customer-user';

        $template['menu'] = "Customer Management";
        $template['smenu'] = "Edit Customer";

        $template['pDescription'] = "Edit Customer Details";
        $template['pTitle'] = "Edit Customer";
        $template['customer_id'] = $customer_id;
        
        $template['veh_data']['make'] = $this->Vehicle_model->getVehBrand('',1);
        $template['veh_data']['model'] = $this->Vehicle_model->getVehModel('',1);
        $customer_id = decode_param($customer_id);
        $template['customer_data']=$this->Customer_model->getCustomer(array('customer_id'=>$customer_id));

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

    function updateCustomer($customer_id = ''){
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(empty($customer_id)){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Customer/listCustomerUsers'));
        }
        $customerIdDec = decode_param($customer_id);

        $err = 0;
        $errMsg = '';
        if(!isset($_POST) || empty($_POST)){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Customer/addCustomerUser'));
        }
        if($err == 0 && (!isset($_POST['first_name']) || empty($_POST['first_name']))){
            $err = 1;
            $errMsg = 'Provide a First Name';
        }
        else if($err == 0 && (!isset($_POST['last_name']) || empty($_POST['last_name']))){
            $err = 1;
            $errMsg = 'Provide a Last Name';
        }
        else if($err == 0 && (!isset($_POST['phone']) || empty($_POST['phone']))){
            $err = 1;
            $errMsg = 'Provide a Phone Number';
        }
        else if($err == 0 && (!isset($_POST['email']) || empty($_POST['email']))){
            $err = 1;
            $errMsg = 'Provide an Email ID';
        }
        else if($err == 0 && (!isset($_POST['date_of_birth']) || empty($_POST['date_of_birth']))){
            $err = 1;
            $errMsg = 'Provide Date Of Birth';
        }
        else if($err == 0 && (!isset($_POST['address']) || empty($_POST['address']))){
            $err = 1;
            $errMsg = 'Provide an Address';
        }

        if($err == 1){
            $flashMsg['message'] = $errMsg;
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Customer/editCustomer/'.$customer_id));
        }
        $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'];
        }
        $saved_vehicles = (!empty($_POST['saved_vehicles']))?implode(',',$_POST['saved_vehicles']):'';
        unset($_POST['saved_vehicles']);

        $status = $this->Customer_model->updateCustomer($customerIdDec,$_POST,$saved_vehicles);
        if($status == 1){
            $flashMsg['class'] = 'success';
            $flashMsg['message'] = 'User Details Updated';

            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Customer/listCustomerUsers'));
        }else if($status == 2){
            $flashMsg['message'] = 'Email ID already in use.';
        }else if($status == 3){
            $flashMsg['message'] = 'Phone Number already in use.';
        }
        $this->session->set_flashdata('message',$flashMsg);
        redirect(base_url('Customer/editCustomer/'.$customer_id));
    }

    public function exportCustomerData(){
        $custData = $this->Customer_model->getCustomer();

        if(empty($custData)){
            return;
        }
        $header = array('ID','Name','Phone','Email','Address','Date Of Birth','Status','Cars');

        $file = 'custData_'.time().'.csv';
        $fpoint = fopen('php://memory', 'w');
        fputcsv($fpoint, $header, ',');

        foreach($custData AS $customer){
            $carData = $this->Customer_model->getCustomer(array('customer_id'=>$customer->customer_id));

            $cars = '';
            $data = array();
            if(!empty($carData->vehicle_data)){
                foreach($carData->vehicle_data AS $car){
                    $cars = $car->car_name.',';
                    $cars = trim($cars,',');
                }
            }
            $data[] = $customer->customer_id;
            $data[] = $customer->first_name.' '.$customer->last_name;
            $data[] = $customer->phone;
            $data[] = $customer->email;
            $data[] = $customer->address;
            $data[] = $customer->date_of_birth;
            $data[] = ($customer->status == 1)?'Active':'De-active';
            $data[] = $cars;

            fputcsv($fpoint, $data, ',');
        }
        fseek($fpoint, 0);
        header('Content-Type: application/csv');
        header('Content-Disposition: attachement; filename="' . $file . '";');
        fpassthru($fpoint);
    }
}
?>