<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Vehicles extends CI_Controller
{
  public $page_data = array();

  function __construct()
  {
    parent::__construct();
    $this->initial();
  }

  public function initial()
  {
    ini_set('max_execution_time', 5000);
    ini_set("memory_limit", "-1");

    $this->load->model('User_model', 'User');
    $this->load->model('Work_model', 'Work');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Vehicle_model', 'Vehicle');
    $this->load->model('Vehicle_work_slips_model', 'Vehicle_work_slips');
    $this->load->model('Labour_model', 'Labour');
    $this->load->model('Bills_model', 'Bills');
    $this->load->model('Stock_model', 'Stock');
    $this->load->model('Labour_model', 'Labour');
    $this->load->model('Employees_model', 'Employee');
    $this->load->model('Supplier_model', 'Supplier');
    $this->load->library('phpqrcode/qrlib');
    $this->load->library('Bills_management','bills_management');

    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin","admin","supervisor","general_manager","auditor","accounts_manager","purchase_manager","procurement_engineer","project_manager","operation_manager");
    if($this->User->is_logged_in($allowed_user_roles)==false){
      redirect(base_url(), 'refresh');
    }
    //        File Directory
    $this->page_data['directory'] = "vehicles";

    $user_accounts_where = "ur.role_name='supervisor' or ur.role_name='general_manager'";
    $this->page_data['user_accounts'] = $this->Account->select_account_heads("",$user_accounts_where,"user")->result();
    if($this->config->item('Labour_group_member_payment')==0){
      $this->db->where('(l.labour_type=0 or (l.labour_type=1 and group_position=1))');
    }
    $this->page_data['labours_2'] = $this->Labour->select_labours()->result();
    $this->page_data['vehicle_suppliers'] = $this->Supplier->select_supplier("*", array("supplier_type" => 'vehicle'))->result();
  }

  public function index()
  {
    $this->view();
  }

  public function view()
  {
    $this->page_data['page_name'] = 'vehicles_view';
    $this->load->view('Index', $this->page_data);
  }
  public function drivers()
  {
    if($this->config->item('app_module_vehicle_management')==1){
      $columns = 'v.*,ah.acc_head_name,vc.consignee_name';
    }else{
      $columns = 'v.*,vc.consignee_name';
    }
    $this->page_data['owned_vehicles'] = $this->Vehicle->select_vehicle($columns,array('v.vehicle_type'=>'own'))->result();
    $this->page_data['page_name'] = 'drivers';
    $this->load->view('Index', $this->page_data);
  }
  public function print_qrcode($id=""){
    if($id!="") {
      $this->page_data['vehicle_data'] = $this->Vehicle->select_vehicle("v.*", array("v.id" => $id));
      if($this->page_data['vehicle_data']->num_rows()==1){
        $this->page_data['vehicle_data'] = $this->page_data['vehicle_data']->row();
        $SERVERFILEPATH = FCPATH.'/uploads/vehicles/';
        $text = "vehicle_id=".$this->page_data['vehicle_data']->id;
        $text1= $this->page_data['vehicle_data']->id;

        $folder = $SERVERFILEPATH;
        $file_name1 = $text1."-Qrcode.png";
        $file_name = $folder.$file_name1;
        QRcode::png($text,$file_name,'L', 10, 2);

        $this->page_data['qr_code_image'] = $file_name1;

        $this->page_data['page_name'] = 'vehicle_qr_code';
        $this->load->view('Index',$this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }
  public function fuel_report()
  {
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['work_types'] = $this->Work->select_work_types()->result();
    $this->page_data['vehicles'] = $this->Vehicle->select_vehicle()->result();
    $this->page_data['driver_employees'] = $this->Employee->select_employee("e.*",array('e.department'=>1))->result();
    if($this->config->item('app_module_vehicle_management')==1){
      $columns = 'v.*,ah.acc_head_name,vc.consignee_name';
    }else{
      $columns = 'v.*,vc.consignee_name';
    }
    $this->page_data['owned_vehicles'] = $this->Vehicle->select_vehicle($columns,array('v.vehicle_type'=>'own'))->result();
    $this->page_data['page_name'] = 'fuel_report';
    $this->load->view('Index', $this->page_data);
  }
  public function bata_report()
  {
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['work_types'] = $this->Work->select_work_types()->result();
    $this->page_data['vehicles'] = $this->Vehicle->select_vehicle()->result();
    $this->page_data['driver_employees'] = $this->Employee->select_employee("e.*",array('e.department'=>1))->result();
    if($this->config->item('app_module_vehicle_management')==1){
      $columns = 'v.*,ah.acc_head_name,vc.consignee_name';
    }else{
      $columns = 'v.*,vc.consignee_name';
    }
    $this->page_data['owned_vehicles'] = $this->Vehicle->select_vehicle($columns,array('v.vehicle_type'=>'own'))->result();
    $this->page_data['page_name'] = 'bata_report';
    $this->load->view('Index', $this->page_data);
  }
  public function material_consumption()
  {
    $this->page_data['materials'] = $this->Material->select_material()->result();
    $this->page_data['material_categories'] = $this->Material->select_category("")->result();
    $this->page_data['stock_locations_warehouse'] = $this->Stock->select_stock_locations("", array('sl.work_id' => '0'))->result();
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['work_types'] = $this->Work->select_work_types()->result();
    $this->page_data['vehicles'] = $this->Vehicle->select_vehicle()->result();
    $this->page_data['driver_employees'] = $this->Employee->select_employee("e.*",array('e.department'=>1))->result();
    if($this->config->item('app_module_vehicle_management')==1){
      $columns = 'v.*,ah.acc_head_name,vc.consignee_name';
    }else{
      $columns = 'v.*,vc.consignee_name';
    }
    $this->page_data['owned_vehicles'] = $this->Vehicle->select_vehicle($columns,array('v.vehicle_type'=>'own'))->result();
    $this->page_data['page_name'] = 'vehicle_material_consumption';
    $this->load->view('Index', $this->page_data);
  }
  public function profit_loss_report()
  {
    $this->page_data['driver_employees'] = $this->Employee->select_employee("e.*",array('e.department'=>1))->result();
    if($this->config->item('app_module_vehicle_management')==1){
      $columns = 'v.*,ah.acc_head_name,vc.consignee_name';
    }else{
      $columns = 'v.*,vc.consignee_name';
    }
    $this->page_data['owned_vehicles'] = $this->Vehicle->select_vehicle($columns,array('v.vehicle_type'=>'own'))->result();
    $this->page_data['page_name'] = 'profit_loss_report';
    $this->load->view('Index', $this->page_data);
  }
  public function consignees($page='',$id='')
  {
    if($this->config->item('app_module_vehicle_management')==1){
      $columns = 'v.*,ah.acc_head_name,vc.consignee_name';
    }else{
      $columns = 'v.*,vc.consignee_name';
    }
    $this->page_data['owned_vehicles'] = $this->Vehicle->select_vehicle($columns,array('v.vehicle_type'=>'own'))->result();
    if($page='profile' && $id!=''){
      $this->page_data['consignee_data'] = $this->Vehicle->select_consignee('*',array("consignee_id"=>$id));
      if($this->page_data['consignee_data']->num_rows()==1){
        $this->page_data['consignee_data'] = $this->page_data['consignee_data']->row();
        $this->page_data['page_name'] = 'consignee_profile';
      }else {
        show_404();
      }
    }else{
      $this->page_data['page_name'] = 'consignees';
    }
    $this->load->view('Index', $this->page_data);
  }
  public function renewal_payments()
  {
    if($this->config->item('app_module_vehicle_management')==1){
      $columns = 'v.*,ah.acc_head_name,vc.consignee_name';
    }else{
      $columns = 'v.*,vc.consignee_name';
    }
    $this->page_data['owned_vehicles'] = $this->Vehicle->select_vehicle($columns,array('v.vehicle_type'=>'own'))->result();
    $this->page_data['page_name'] = 'renewal_payments';
    $this->load->view('Index', $this->page_data);
  }
  public function allocations()
  {
    $this->page_data['vehicle_categories'] = $this->Vehicle->select_vehicle("distinct(v.vehicle_category)")->result();
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations()->result();
    $this->page_data['driver_employees'] = $this->Employee->select_employee("e.*",array('e.department'=>1))->result();

    if($this->config->item('app_module_vehicle_management')==1){
      $columns = 'v.*,ah.acc_head_name,vc.consignee_name';
    }else{
      $columns = 'v.*,vc.consignee_name';
    }
    $this->page_data['owned_vehicles'] = $this->Vehicle->select_vehicle($columns,array('v.vehicle_type'=>'own'))->result();
    $this->page_data['page_name'] = 'vehicle_allocations';
    $this->load->view('Index', $this->page_data);
  }
  public function expenses()
  {
    if($this->config->item('app_module_vehicle_management')==1){
      $columns = 'v.*,ah.acc_head_name,vc.consignee_name';
    }else{
      $columns = 'v.*,vc.consignee_name';
    }
    $this->page_data['owned_vehicles'] = $this->Vehicle->select_vehicle($columns,array('v.vehicle_type'=>'own'))->result();
    $this->page_data['page_name'] = 'vehicle_expenses';
    $this->load->view('Index', $this->page_data);
  }
  public function add()
  {
    if($this->config->item('app_module_vehicle_management')==1){
      $this->page_data['page_name'] = 'vehicles_add';
    }else{
      $this->page_data['page_name'] = 'vehicles_view';
    }
    $this->load->view('Index', $this->page_data);
  }

  public function profile($id='')
  {
    $this->page_data['driver_employees'] = $this->Employee->select_employee("e.*",array('e.department'=>1))->result();
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations()->result();
    $this->page_data['vehicle_document_types'] = $this->Vehicle->select_vehicle_document_types()->result();
    if($id!=''){
      if($this->config->item('app_module_vehicle_management')==1){
        $columns = 'v.*,ah.acc_head_name,lp.loan_provider_name,vc.consignee_name';
      }else{
        $columns = 'v.*,vc.consignee_name';
      }
      $this->page_data['owned_vehicles'] = $this->Vehicle->select_vehicle($columns,array('v.vehicle_type'=>'own','v.id'=>$id))->result();

      $vehicle_data = $this->Vehicle->select_vehicle($columns,array('v.id'=>$id));
      if($vehicle_data->num_rows()==1){
        $this->page_data['vehicle_data'] = $vehicle_data->row();

        $this->page_data['vehicles'] = $this->Vehicle->select_vehicle()->result();
        $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
        $this->page_data['work_types'] = $this->Work->select_work_types()->result();
        $this->page_data['labours_2'] = $this->Labour->select_labours()->result();
        $this->page_data['labour_groups'] = $this->Labour->select_labours("",array("labour_type"=>1,"labour_group !="=>0,"group_position"=>1))->result();
        $accounts_where = "ur.role_name='supervisor' or ur.role_name='general_manager'";
        $this->page_data['user_accounts'] = $this->Account->select_account_heads("",$accounts_where,"user")->result();

        $this->page_data['page_name'] = 'vehicle_profile';
        $this->load->view('Index', $this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }

  public function edit($id='')
  {
    if($id!=''){
      $vehicle_data = $this->Vehicle->select_vehicle('',array('v.id'=>$id));
      if($vehicle_data->num_rows()==1){
        $this->page_data['vehicle_data'] = $vehicle_data->row();

        $this->page_data['page_name'] = 'vehicles_edit';
        $this->load->view('Index', $this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }

  public function select_vehicle(){

    $json_data=array();
    $j=0;
    $sl_no=1;
    $data=array();
    if(isset($_POST['vehicle_type']) && $_POST['vehicle_type']!='' && $_POST['vehicle_type']!='all'){
      $data['v.vehicle_type'] = $_POST['vehicle_type'];
    }
    if(isset($_POST['consignee']) && $_POST['consignee']!='' && $_POST['consignee']!='all'){
      $data['v.consignee'] = $_POST['consignee'];
    }
    $select_colum='v.*,u.*,v.created_date AS v_created_date,v.created_by AS v_created_by,vc.consignee_name,vc.consignee_place';
    if($this->session->userdata('user_role')!='admin'){
      // $data['v.created_by'] = $this->session->userdata('user_id');
    }
    $result = $this->Vehicle->select_vehicle($select_colum,$data);
    $result_array=$result->result();

    $json_data['draw']=4;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();
    $btn_edit=$btn_delete='';
    foreach($result_array as $row):
      if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager'){
        $btn_edit='<a style="margin-left: 5px;margin-right: 5px" id="vehicles_edit_btn" href="#vehicles_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air vehicle_work_slip_edit_btn">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="vehicles_delete_btn" href="#vehicles_delete_modal" data-toggle="modal"  class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air ">
        <i class="la la-trash"></i>
        </a>';
      }

      if($page_name='vehicles_view'){
        $array[$j][]=$row->id;
        $array[$j][]=$j+1;
        $array[$j][]='<a href="'.base_url().'vehicles/profile/'.$row->id.'">'.$row->vehicle_name.'</a>';
        $array[$j][]=$row->vehicle_no;
        $array[$j][]='<a href="'.base_url().'vehicles/consignees/profile/'.$row->consignee.'">'.$row->consignee_name.'<br/>'.$row->consignee_place.'</a>';
        $array[$j][]='<a href="'.base_url().'vehicles/profile/'.$row->id.'">'.$row->vehicle_name." : ".$row->vehicle_no.'</a>';
        $array[$j][]=$row->vehicle_type;
        $array[$j][]='<a href="'.base_url().'vehicles/consignees/profile/'.$row->consignee.'">'.$row->consignee_name.'<br/>'.$row->consignee_place.'</a>';
        $array[$j][]=$row->basic_charge;
        $array[$j][]=$row->work_duration_type;
        $array[$j][]=$row->loading_capacity_cft;
        $array[$j][]=$row->loading_capacity_ton;
        $array[$j][]=$row->vehicle_op_balance;
        if ($this->config->item('UI_hide_created_date_field')==0){
          $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : '.date('d-m-Y',strtotime($row->v_created_date))."</li><li>Created By : ".$row->user_alias."</li>";
        }else{
          $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->user_alias.'</li>';
        }
        $array[$j][]=$btn_edit.$btn_delete;
        $array[$j][]=$row->consignee;
      }else{
        $array[$j][]=$row->id;
        $array[$j][]=$row->vehicle_name;
        $array[$j][]=$row->vehicle_no;
        $array[$j][]=$row->basic_charge;
        $array[$j][]=$row->consignee_name;
      }

      $j++;
    endforeach;

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function select_vehicle_owned(){

    $json_data=array();
    $j=0;
    $sl_no=1;
    $data=array();
    if(isset($_POST['vehicle_type']) && $_POST['vehicle_type']!='' && $_POST['vehicle_type']!='all'){
      $data['v.vehicle_type'] = $_POST['vehicle_type'];
    }
    if($page_name='vehicles_view'){
      $select_colum='v.*,u.*,ah.acc_head_name,v.created_date AS v_created_date,v.created_by AS v_created_by,,vc.consignee_name,vc.consignee_place,lp.loan_provider_name';
    }
    else{
      $select_colum='';
    }
    if($this->session->userdata('user_role')!='admin'){
      // $data['v.created_by'] = $this->session->userdata('user_id');
    }
    $result = $this->Vehicle->select_vehicle($select_colum,$data);
    $result_array=$result->result();

    $json_data['draw']=4;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();
    $btn_edit=$btn_delete=$btn_qr_code='';
    foreach($result_array as $row):
      if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager'){
        $btn_edit='<a style="margin-left: 5px;margin-right: 5px" href="'.base_url().'vehicles/edit/'.$row->id.'" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air vehicle_work_slip_edit_btn">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="vehicles_delete_btn" href="#vehicles_delete_modal" data-toggle="modal"  class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air ">
        <i class="la la-trash"></i>
        </a>';
        $btn_qr_code='<a style="margin-left: 5px;margin-right: 5px" id="btn_qr_code" href="javascript:;" class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
        <i class="la la-qrcode"></i>
        </a>';
      }

      if($row->vehicle_status==1){
        $vehicle_status = '<span style="margin-top: 5px" class="m-badge m-badge--success m-badge--wide"><i class="fa fa-check-circle"></i> Active</span>';
      }else{
        $vehicle_status = '<span style="margin-top: 5px" class="m-badge m-badge--danger m-badge--wide"><i class="fa fa-times-circle"></i> On Repair</span>';
      }

      if($row->emi_status==2){
        $emi_status = '<span style="margin-top: 5px" class="m-badge m-badge--success m-badge--wide"><i class="fa fa-check-circle"></i> Finished</span>';
      }elseif($row->emi_status==1){
        $emi_status = '<span style="margin-top: 5px" class="m-badge m-badge--info m-badge--wide"><i class="fa fa-check-circle"></i> Ongoing</span>';
      }else{
        $emi_status = '<span style="margin-top: 5px" class="m-badge m-badge--danger m-badge--wide"><i class="fa fa-times-circle"></i> NO EMI</span>';
      }

      $array[$j][]=$row->id;
      $array[$j][]=$j+1;
      $array[$j][]='<a href="'.base_url().'vehicles/profile/'.$row->id.'">'.$row->vehicle_no.'</a>';
      $array[$j][]=$row->manufacturer;
      $array[$j][]=$row->vehicle_category;
      $array[$j][]=$row->model;
      $array[$j][]=$row->vehicle_type_cat;
      $array[$j][]='<a href="'.base_url().'vehicles/consignees/profile/'.$row->consignee.'">'.$row->consignee_name.'</a>';
      $array[$j][]=$row->basic_charge;
      $array[$j][]=ucfirst($row->work_duration_type);
      $array[$j][]=$emi_status;
      $array[$j][]=($row->emi_status!=0)?$row->emi_amount:'';
      $array[$j][]=($row->emi_status!=0)?$row->emi_date:'';
      $array[$j][]=($row->next_emi_renewal_date!='0000-00-00')?date('d-m-Y',strtotime($row->next_emi_renewal_date)):'';
      $array[$j][]=($row->tax_renewal_date!='0000-00-00')?date('d-m-Y',strtotime($row->tax_renewal_date)):'';
      $array[$j][]=($row->insurance_renewal_date!='0000-00-00')?date('d-m-Y',strtotime($row->insurance_renewal_date)):'';
      $array[$j][]=($row->permit_renewal_date!='0000-00-00')?date('d-m-Y',strtotime($row->permit_renewal_date)):'';
      $array[$j][]=($row->fitness_renewal_date!='0000-00-00')?date('d-m-Y',strtotime($row->fitness_renewal_date)):'';
      $array[$j][]=($row->break_renewal_date!='0000-00-00')?date('d-m-Y',strtotime($row->break_renewal_date)):'';
      $array[$j][]=($row->pollution_renewal_date!='0000-00-00')?date('d-m-Y',strtotime($row->pollution_renewal_date)):'';
      $array[$j][]=($row->gps_renewal_date!='0000-00-00')?date('d-m-Y',strtotime($row->gps_renewal_date)):'';
      $array[$j][]=($row->speed_governor_renewal_date!='0000-00-00')?date('d-m-Y',strtotime($row->speed_governor_renewal_date)):'';
      $array[$j][]=($row->welfare_renewal_date!='0000-00-00')?date('d-m-Y',strtotime($row->welfare_renewal_date)):'';
      $array[$j][]=$row->loading_capacity_cft;
      $array[$j][]=$row->loading_capacity_ton;
      $array[$j][]=$row->engine_no;
      $array[$j][]=$row->chasis_no;
      $array[$j][]=$row->dealer;
      $array[$j][]=($row->date_of_delivery!='0000-00-00')?date('d-m-Y',strtotime($row->date_of_delivery)):'';
      $array[$j][]=$row->total_amount;
      $array[$j][]=$row->loan_no;
      $array[$j][]=$row->loan_provider_name;
      $array[$j][]=$row->installments;
      $array[$j][]=($row->purchase_month!='0000-00-00')?date('M Y',strtotime($row->purchase_month)):'';
      $array[$j][]=($row->closing_month!='0000-00-00')?date('M Y',strtotime($row->closing_month)):'';
      $array[$j][]=$row->acc_head_name;
      $array[$j][]=$row->installments_left;
      $array[$j][]=$row->current_payable_amount;
      $array[$j][]=$vehicle_status;
      $array[$j][]=$row->vehicle_op_balance;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : '.date('d-m-Y',strtotime($row->v_created_date))."</li><li>Created By : ".$row->user_alias."</li>";
      }else{
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->user_alias.'</li>';
      }
      $array[$j][]=$btn_qr_code.$btn_edit.$btn_delete;

      $j++;
    endforeach;

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function select_vehicles_list(){
    $data = array();
    if(isset($_POST['id']) && $_POST['id']!=""){
      $data['v.id'] = $_POST['id'];
    }
    if(isset($_POST['category']) && $_POST['category']!="" && $_POST['category']!="all"){
      $data['v.vehicle_category'] = $_POST['category'];
    }
    if(isset($_POST['vehicle_type']) && $_POST['vehicle_type']!='' && $_POST['vehicle_type']!='all'){
      $data['v.vehicle_type'] = $_POST['vehicle_type'];
    }
    $result = $this->Vehicle->select_vehicle("",$data);
    if($result->num_rows()>0) {
      echo json_encode(array("count" => $result->num_rows(),"data" => $result->result_array()));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }

  public function create($type=''){
    $data['vehicle_no'] = $vehicle_where['vehicle_no'] = strtoupper($this->security->xss_clean($this->input->post('vehicle_number')));
    $data['consignee'] = $this->security->xss_clean($this->input->post('consignee'));
    $data['vehicle_type'] = $this->security->xss_clean($this->input->post('vehicle_type'));
    $data['basic_charge'] = $this->security->xss_clean($this->input->post('basic_charge'));
    $data['work_duration_type'] = $this->security->xss_clean($this->input->post('work_duration_type'));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');
    $data['loading_capacity_cft'] = $this->security->xss_clean($this->input->post('loading_capacity_cft'));
    $data['loading_capacity_ton'] = $this->security->xss_clean($this->input->post('loading_capacity_ton'));
    $data['vehicle_op_balance'] = $this->security->xss_clean($this->input->post('op_balance'));
    if($type=='own'){
      $data['vehicle_type_cat'] = $this->security->xss_clean($this->input->post('vehicle_type_cat'));
      $data['vehicle_category'] = strtoupper($this->security->xss_clean($this->input->post('category')));
      $data['model'] = strtoupper($this->security->xss_clean($this->input->post('model')));
      $data['manufacturer'] = strtoupper($this->security->xss_clean($this->input->post('manufacturer')));
      $data['dealer'] = $this->security->xss_clean($this->input->post('dealer'));
      $data['engine_no'] = $this->security->xss_clean($this->input->post('engine_no'));
      $data['chasis_no'] = $this->security->xss_clean($this->input->post('chasis_no'));
      if($this->input->post('delivery_date')!=''){
        $data['date_of_delivery'] = date('Y-m-d',strtotime($this->input->post('delivery_date')));
      }
      $data['vehicle_name'] = strtoupper($data['manufacturer']." ".$data['vehicle_category']." ".$data['model']);
      $data['vehicle_status'] = $this->security->xss_clean($this->input->post('vehicle_status'));
      if($this->input->post('have_emi')=='on'){
        $data['financier'] = $this->security->xss_clean($this->input->post('financier'));
        $data['total_amount'] = $this->security->xss_clean($this->input->post('total_loan_amount'));
        $data['emi_amount'] = $this->security->xss_clean($this->input->post('emi_amount'));
        $data['loan_no'] = $this->security->xss_clean($this->input->post('loan_no'));
        $data['installments'] = $this->security->xss_clean($this->input->post('installments'));
        $data['installments_left'] = $this->security->xss_clean($this->input->post('installments_left'));
        $data['current_payable_amount'] = $this->security->xss_clean($this->input->post('emi_current_payable_amount'));
        if($this->input->post('purchase_month')!=''){
          $data['purchase_month'] = date('Y-m-d',strtotime("01-".$this->input->post('purchase_month')));
        }
        if($this->input->post('close_month')!=''){
          $data['closing_month'] = date('Y-m-d',strtotime("01-".$this->input->post('close_month')));
        }
        $data['emi_date'] = $this->security->xss_clean($this->input->post('emi_date'));
        if($this->input->post('emi_next_month')!=''){
          $data['next_emi_renewal_date'] = date('Y-m-d',strtotime(sprintf("%02d", $data['emi_date'])."-".$this->input->post('emi_next_month')));
        }
        $data['emi_bank_account'] = $this->security->xss_clean($this->input->post('emi_bank_account'));
        $data['emi_status'] = $this->security->xss_clean($this->input->post('emi_status'));
      }else{
        $data['emi_status'] = 0;
      }
      if($this->input->post('have_insurance')=='on'){
        $data['insurer'] = $this->security->xss_clean($this->input->post('insurer'));
        $data['insurance_renewal_date'] = date('Y-m-d',strtotime($this->input->post('insurance_date')));
      }
      if($this->input->post('have_tax')=='on'){
        $data['tax_renewal_date'] = date('Y-m-d',strtotime($this->input->post('tax_date')));
      }
      if($this->input->post('have_break')=='on'){
        $data['break_renewal_date'] = date('Y-m-d',strtotime($this->input->post('break_date')));
      }
      if($this->input->post('have_permit')=='on'){
        $data['permit_renewal_date'] = date('Y-m-d',strtotime($this->input->post('permit_date')));
      }
      if($this->input->post('have_fitness')=='on'){
        $data['fitness_renewal_date'] = date('Y-m-d',strtotime($this->input->post('fitness_date')));
      }
      if($this->input->post('have_pollution')=='on'){
        $data['pollution_renewal_date'] = date('Y-m-d',strtotime($this->input->post('pollution_date')));
      }
      if($this->input->post('have_gps')=='on'){
        $data['gps_renewal_date'] = date('Y-m-d',strtotime($this->input->post('gps_date')));
      }
      if($this->input->post('have_speed_governor')=='on'){
        $data['speed_governor_renewal_date'] = date('Y-m-d',strtotime($this->input->post('speed_governor_date')));
      }
      if($this->input->post('have_welfare')=='on'){
        $data['welfare_renewal_date'] = date('Y-m-d',strtotime($this->input->post('welfare_date')));
      }
    }else{
      $data['vehicle_name'] = strtoupper($this->security->xss_clean($this->input->post('vehicle_name')));
    }
    $count = $this->Vehicle->select_vehicle("",$vehicle_where)->num_rows();

    if($count==0) {
      $result2 = $this->Vehicle->create_vehicle($data);
      $flash_data['status'] = $result2['status'];
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Vehicle Added Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';

      } else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else{
      $flash_data['status'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. Vehicle with Same Number Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));

  }
  public function update($type='')
  {
    $data['id'] = $vehicle_where['id !='] = $this->security->xss_clean($this->input->post('vehicle_id'));
    $data['vehicle_no'] = $vehicle_where['vehicle_no'] = $this->security->xss_clean($this->input->post('vehicle_number'));
    $data['consignee'] = $this->security->xss_clean($this->input->post('consignee'));
    $data['basic_charge'] = $this->security->xss_clean($this->input->post('basic_charge'));
    $data['work_duration_type'] = $this->security->xss_clean($this->input->post('work_duration_type_edit'));
    $data['loading_capacity_cft'] = $this->security->xss_clean($this->input->post('loading_capacity_cft'));
    $data['loading_capacity_ton'] = $this->security->xss_clean($this->input->post('loading_capacity_ton'));
    $data['vehicle_op_balance'] = $this->security->xss_clean($this->input->post('op_balance'));
    if($type=='own'){
      $data['vehicle_type'] = 'own';
      $data['vehicle_type_cat'] = $this->security->xss_clean($this->input->post('vehicle_type_cat'));
      $data['vehicle_category'] = strtoupper($this->security->xss_clean($this->input->post('category')));
      $data['model'] = strtoupper($this->security->xss_clean($this->input->post('model')));
      $data['manufacturer'] = strtoupper($this->security->xss_clean($this->input->post('manufacturer')));
      $data['dealer'] = $this->security->xss_clean($this->input->post('dealer'));
      $data['engine_no'] = $this->security->xss_clean($this->input->post('engine_no'));
      $data['chasis_no'] = $this->security->xss_clean($this->input->post('chasis_no'));
      if($this->input->post('delivery_date')!=''){
        $data['date_of_delivery'] = date('Y-m-d',strtotime($this->input->post('delivery_date')));
      }else{
        $data['date_of_delivery'] = '0000-00-00';
      }
      $data['vehicle_name'] = strtoupper($data['manufacturer']." ".$data['vehicle_category']." ".$data['model']);
      $data['vehicle_status'] = $this->security->xss_clean($this->input->post('vehicle_status'));
      if($this->input->post('have_emi')=='on'){
        $data['financier'] = $this->security->xss_clean($this->input->post('financier'));
        $data['total_amount'] = $this->security->xss_clean($this->input->post('total_loan_amount'));
        $data['emi_amount'] = $this->security->xss_clean($this->input->post('emi_amount'));
        $data['loan_no'] = $this->security->xss_clean($this->input->post('loan_no'));
        $data['installments'] = $this->security->xss_clean($this->input->post('installments'));
        $data['installments_left'] = $this->security->xss_clean($this->input->post('installments_left'));
        $data['current_payable_amount'] = $this->security->xss_clean($this->input->post('emi_current_payable_amount'));
        if($this->input->post('purchase_month')!=''){
          $data['purchase_month'] = date('Y-m-d',strtotime("01-".$this->input->post('purchase_month')));
        }else{
          $data['purchase_month'] = '0000-00-00';
        }
        if($this->input->post('close_month')!=''){
          $data['closing_month'] = date('Y-m-d',strtotime("01-".$this->input->post('close_month')));
        }else{
          $data['closing_month'] = '0000-00-00';
        }
        $data['emi_date'] = $this->security->xss_clean($this->input->post('emi_date'));
        if($this->input->post('emi_next_month')!=''){
          $data['next_emi_renewal_date'] = date('Y-m-d',strtotime(sprintf("%02d", $data['emi_date'])."-".$this->input->post('emi_next_month')));
        }
        $data['emi_bank_account'] = $this->security->xss_clean($this->input->post('emi_bank_account'));
        $data['emi_status'] = $this->security->xss_clean($this->input->post('emi_status'));
      }else{
        $data['financier'] = $data['loan_no'] = '';
        $data['total_amount'] = $data['emi_amount'] = $data['installments'] = $data['emi_date'] = $data['emi_bank_account'] = 0;
        $data['purchase_month'] = $data['closing_month'] = '0000-00-00';
        $data['emi_status'] = 2;
      }
      if($this->input->post('have_insurance')=='on'){
        $data['insurer'] = $this->security->xss_clean($this->input->post('insurer'));
        $data['insurance_renewal_date'] = date('Y-m-d',strtotime($this->input->post('insurance_date')));
      }else{
        $data['insurer'] = '';
        $data['insurance_renewal_date'] = '0000-00-00';
      }
      if($this->input->post('have_tax')=='on'){
        $data['tax_renewal_date'] = date('Y-m-d',strtotime($this->input->post('tax_date')));
      }else{
        $data['tax_renewal_date'] = '0000-00-00';
      }
      if($this->input->post('have_break')=='on'){
        $data['break_renewal_date'] = date('Y-m-d',strtotime($this->input->post('break_date')));
      }else{
        $data['break_renewal_date'] = '0000-00-00';
      }
      if($this->input->post('have_permit')=='on'){
        $data['permit_renewal_date'] = date('Y-m-d',strtotime($this->input->post('permit_date')));
      }else{
        $data['permit_renewal_date'] = '0000-00-00';
      }
      if($this->input->post('have_fitness')=='on'){
        $data['fitness_renewal_date'] = date('Y-m-d',strtotime($this->input->post('fitness_date')));
      }else{
        $data['fitness_renewal_date'] = '0000-00-00';
      }
      if($this->input->post('have_pollution')=='on'){
        $data['pollution_renewal_date'] = date('Y-m-d',strtotime($this->input->post('pollution_date')));
      }else{
        $data['pollution_renewal_date'] = '0000-00-00';
      }
      if($this->input->post('have_gps')=='on'){
        $data['gps_renewal_date'] = date('Y-m-d',strtotime($this->input->post('gps_date')));
      }else{
        $data['gps_renewal_date'] = '0000-00-00';
      }
      if($this->input->post('have_speed_governor')=='on'){
        $data['speed_governor_renewal_date'] = date('Y-m-d',strtotime($this->input->post('speed_governor_date')));
      }else{
        $data['speed_governor_renewal_date'] = '0000-00-00';
      }
      if($this->input->post('have_welfare')=='on'){
        $data['welfare_renewal_date'] = date('Y-m-d',strtotime($this->input->post('welfare_date')));
      }else{
        $data['welfare_renewal_date'] = '0000-00-00';
      }
    }else{
      $data['vehicle_type'] = $this->security->xss_clean($this->input->post('vehicle_type_edit'));
      $data['vehicle_name'] = strtoupper($this->security->xss_clean($this->input->post('vehicle_name')));
    }
    $count = $this->Vehicle->select_vehicle("",$vehicle_where)->num_rows();
    if($count==0){
      $result = $this->Vehicle->update_vehicle($data);
      $flash_data['status'] = $result;
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Vehicle Details Updated Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';

      } else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else{
      $flash_data['status'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. Vehicle with Same Number Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function delete()
  {
    //  Delete Received Amount
    $redirect_url= $this->security->xss_clean($this->input->post('redirect_url'));
    $data2['id'] = $this->security->xss_clean($this->input->post('vehicle_id'));
    $data2['delete_status']=1;
    $result2 = $this->Vehicle->update_vehicle($data2);

    $flash_data['status'] = $result2;
    if ($result2 == 1) {
      $flash_data['flashdata_type'] = 'success';
      $flash_data['flashdata_msg'] = 'Vehicle Deleted Succesfully';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }

  public function select_summary($return_type=''){
    $json_data=$json_data2=array();
    $j=$sl_no=0;
    $data=array();
    $id = $_POST['id'];
    $vehicle_data = $this->Vehicle->select_vehicle('',array("v.id"=>$_POST['id']));
    if($vehicle_data->num_rows()==1){

      $json_data['work_slips_payable'] = $this->Vehicle_work_slips->select_vehicle_work_slips("COALESCE(SUM(vws.total_payable_amount),0) as total_amount",array('v.id'=>$id),"","","","","")->row()->total_amount;
      $json_data['total_work_slip_paid'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",array("v.id" => $id,"ats.tr_type" => 'vehicle_work_slip_transaction',"ats.reference_type" => 'vehicle_work_slip'),'vehicle_work_slip')->row()->total_amount;
      $json_data['op_balance_payable'] = $vehicle_data->row()->vehicle_op_balance;
      $op_balance_transaction_where['v.id'] = $id;
      $op_balance_transaction_where['ats.reference_type'] = 'vehicle';
      $op_balance_transaction_where['ats.tr_type'] = "vehicle_opbalance_transaction";
      $json_data['op_balance_paid'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total",$op_balance_transaction_where,'vehicle_payment')->row()->total;
      $json_data['total_balance'] = $json_data['work_slips_payable']+$json_data['op_balance_payable']-$json_data['total_work_slip_paid']-$json_data['op_balance_paid'];

      foreach ($json_data as $key => $value) {
        $json_data[$key] = $this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($value,$this->config->item('Currency_currency_shortname'));
      }
      $json_data['work_slips_count'] = $this->Vehicle_work_slips->select_vehicle_work_slips("v.id",array('v.id'=>$id),"","","","","")->num_rows();
      if($return_type=='count') {
        echo json_encode($json_data);  // send data as json format
      }else {

      }
    }
  }
  public function select_renewal_type(){
    $json_data=array();

    if(isset($_POST['vehicle_id']) && $_POST['vehicle_id']!=''){
      $vehicle_data = $this->Vehicle->select_vehicle('',array("v.id"=>$_POST['vehicle_id']));
      if($vehicle_data->num_rows()==1){
        $json_data['count'] = 1;
        $vehicle_data = $vehicle_data->row();
        $json_data['data'] = array();
        if($vehicle_data->emi_status==1){
          $json_data['data'][] = 'emi';
        }
        if($vehicle_data->insurance_renewal_date!='0000-00-00'){
          $json_data['data'][] = 'insurance';
        }
        if($vehicle_data->tax_renewal_date!='0000-00-00'){
          $json_data['data'][] = 'tax';
        }
        if($vehicle_data->break_renewal_date!='0000-00-00'){
          $json_data['data'][] = 'break';
        }
        if($vehicle_data->permit_renewal_date!='0000-00-00'){
          $json_data['data'][] = 'permit';
        }
        if($vehicle_data->fitness_renewal_date!='0000-00-00'){
          $json_data['data'][] = 'fitness';
        }
        if($vehicle_data->pollution_renewal_date!='0000-00-00'){
          $json_data['data'][] = 'pollution';
        }
        if($vehicle_data->gps_renewal_date!='0000-00-00'){
          $json_data['data'][] = 'gps';
        }
        if($vehicle_data->speed_governor_renewal_date!='0000-00-00'){
          $json_data['data'][] = 'speed_governor';
        }
        if($vehicle_data->welfare_renewal_date!='0000-00-00'){
          $json_data['data'][] = 'welfare';
        }
      }else{
        $json_data['count'] = 0;
      }
    }else{
      $json_data['count'] = 0;
    }

    echo json_encode($json_data);  // send data as json format
  }

  public function select_details(){
    $json_data=array();

    if(isset($_POST['vehicle_id']) && $_POST['vehicle_id']!=''){
      $vehicle_data = $this->Vehicle->select_vehicle('',array("v.id"=>$_POST['vehicle_id']));
      if($vehicle_data->num_rows()==1){
        $json_data['count'] = 1;
        $vehicle_data = $vehicle_data->row();
        $vehicle_id = $vehicle_data->id;
        // $this->db->where("FIND_IN_SET($vehicle_id, e.assigned_vehicles)");
        $this->db->where("e.department=1");
        $vehicle_data->assigned_drivers = $this->Employee->select_employee("e.*")->result_array();
        $json_data['data'] = $vehicle_data;
      }else{
        $json_data['count'] = 0;
      }
    }else{
      $json_data['count'] = 0;
    }

    echo json_encode($json_data);  // send data as json format
  }

  public function select_renewal_details(){
    $json_data=array();

    if(isset($_POST['vehicle_id']) && $_POST['vehicle_id']!='' && isset($_POST['renewal_type']) && $_POST['renewal_type']!=''){
      $vehicle_data = $this->Vehicle->select_vehicle('',array("v.id"=>$_POST['vehicle_id']));
      if($vehicle_data->num_rows()==1){
        $json_data['count'] = 1;
        $vehicle_data = $vehicle_data->row();
        if($_POST['renewal_type']=='emi'){
          $json_data['data']['renewal_date'] = date('d-m-Y',strtotime($vehicle_data->next_emi_renewal_date));
          $json_data['data']['renewal_amount'] = $vehicle_data->emi_amount;
        }elseif($_POST['renewal_type']=='insurance'){
          $json_data['data']['renewal_date'] = date('d-m-Y',strtotime($vehicle_data->insurance_renewal_date));
          $json_data['data']['renewal_amount'] = '';
        }elseif($_POST['renewal_type']=='tax'){
          $json_data['data']['renewal_date'] = date('d-m-Y',strtotime($vehicle_data->tax_renewal_date));
          $json_data['data']['renewal_amount'] = '';
        }elseif($_POST['renewal_type']=='break'){
          $json_data['data']['renewal_date'] = date('d-m-Y',strtotime($vehicle_data->break_renewal_date));
          $json_data['data']['renewal_amount'] = '';
        }elseif($_POST['renewal_type']=='permit'){
          $json_data['data']['renewal_date'] = date('d-m-Y',strtotime($vehicle_data->permit_renewal_date));
          $json_data['data']['renewal_amount'] = '';
        }elseif($_POST['renewal_type']=='fitness'){
          $json_data['data']['renewal_date'] = date('d-m-Y',strtotime($vehicle_data->fitness_renewal_date));
          $json_data['data']['renewal_amount'] = '';
        }elseif($_POST['renewal_type']=='pollution'){
          $json_data['data']['renewal_date'] = date('d-m-Y',strtotime($vehicle_data->pollution_renewal_date));
          $json_data['data']['renewal_amount'] = '';
        }elseif($_POST['renewal_type']=='gps'){
          $json_data['data']['renewal_date'] = date('d-m-Y',strtotime($vehicle_data->gps_renewal_date));
          $json_data['data']['renewal_amount'] = '';
        }elseif($_POST['renewal_type']=='speed_governor'){
          $json_data['data']['renewal_date'] = date('d-m-Y',strtotime($vehicle_data->speed_governor_renewal_date));
          $json_data['data']['renewal_amount'] = '';
        }elseif($_POST['renewal_type']=='welfare'){
          $json_data['data']['renewal_date'] = date('d-m-Y',strtotime($vehicle_data->welfare_renewal_date));
          $json_data['data']['renewal_amount'] = '';
        }
      }else{
        $json_data['count'] = 0;
      }
    }else{
      $json_data['count'] = 0;
    }

    echo json_encode($json_data);  // send data as json format
  }

  // public function create_driver(){
  //   $data['driver_name'] = $driver_where['driver_name'] = $this->security->xss_clean($this->input->post('driver_name'));
  //   $data['driver_place'] = $this->security->xss_clean($this->input->post('place'));
  //   $data['driver_mobile'] = $this->security->xss_clean($this->input->post('mobile'));
  //   $data['assigned_vehicles'] = implode(',',$this->input->post('assigned_vehicles'));
  //   $data['created_date'] = date('Y-m-d H:i:s');
  //   $data['created_by'] = $this->session->userdata('user_id');
  //   $count = $this->Vehicle->select_driver("",$driver_where)->num_rows();
  //
  //   if($count==0) {
  //     $result = $this->Vehicle->create_driver($data);
  //     $flash_data['status'] = $result['status'];
  //     if ($flash_data['status'] == 1) {
  //       $flash_data['flashdata_msg'] = 'Driver Added Successfully!.';
  //       $flash_data['flashdata_type'] = 'success';
  //       $flash_data['alert_type'] = 'success';
  //       $flash_data['flashdata_title'] = 'Success !';
  //     } else {
  //       $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
  //       $flash_data['flashdata_type'] = 'error';
  //       $flash_data['alert_type'] = 'danger';
  //       $flash_data['flashdata_title'] = 'Error !!';
  //     }
  //   }else{
  //     $flash_data['status'] = 2;
  //     $flash_data['flashdata_msg'] = 'Sorry.. Driver with Same Number Already Exist!';
  //     $flash_data['flashdata_type'] = 'warning';
  //     $flash_data['alert_type'] = 'warning';
  //     $flash_data['flashdata_title'] = 'Duplication !!';
  //   }
  //   $flash_data['message'] = $flash_data['flashdata_msg'];
  //   echo(json_encode($flash_data));
  // }
  // public function update_driver(){
  //   $data['driver_id'] = $driver_where['driver_id !='] = $this->security->xss_clean($this->input->post('driver_id'));
  //   $data['driver_name'] = $driver_where['driver_name'] = $this->security->xss_clean($this->input->post('driver_name'));
  //   $data['driver_place'] = $this->security->xss_clean($this->input->post('place'));
  //   $data['driver_mobile'] = $this->security->xss_clean($this->input->post('mobile'));
  //   $data['assigned_vehicles'] = implode(',',$this->input->post('assigned_vehicles'));
  //   $count = $this->Vehicle->select_driver("",$driver_where)->num_rows();
  //
  //   if($count==0) {
  //     $result = $this->Vehicle->update_driver($data);
  //     $flash_data['status'] = $result;
  //     if ($flash_data['status'] == 1) {
  //       $flash_data['flashdata_msg'] = 'Driver Details Updated Successfully!.';
  //       $flash_data['flashdata_type'] = 'success';
  //       $flash_data['alert_type'] = 'success';
  //       $flash_data['flashdata_title'] = 'Success !';
  //     } else {
  //       $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
  //       $flash_data['flashdata_type'] = 'error';
  //       $flash_data['alert_type'] = 'danger';
  //       $flash_data['flashdata_title'] = 'Error !!';
  //     }
  //   }else{
  //     $flash_data['status'] = 2;
  //     $flash_data['flashdata_msg'] = 'Sorry.. Driver with Same Number Already Exist!';
  //     $flash_data['flashdata_type'] = 'warning';
  //     $flash_data['alert_type'] = 'warning';
  //     $flash_data['flashdata_title'] = 'Duplication !!';
  //   }
  //   $flash_data['message'] = $flash_data['flashdata_msg'];
  //   echo(json_encode($flash_data));
  // }
  // public function delete_driver(){
  //   $data['driver_id'] = $this->security->xss_clean($this->input->post('driver_id'));
  //   $data['delete_status'] = 1;
  //   $result = $this->Vehicle->update_driver($data);
  //   $flash_data['status'] = $result;
  //   if ($flash_data['status'] == 1) {
  //     $flash_data['flashdata_msg'] = 'Driver Deleted Successfully!.';
  //     $flash_data['flashdata_type'] = 'success';
  //     $flash_data['alert_type'] = 'success';
  //     $flash_data['flashdata_title'] = 'Success !';
  //   } else {
  //     $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
  //     $flash_data['flashdata_type'] = 'error';
  //     $flash_data['alert_type'] = 'danger';
  //     $flash_data['flashdata_title'] = 'Error !!';
  //   }
  //
  //   $flash_data['message'] = $flash_data['flashdata_msg'];
  //   echo(json_encode($flash_data));
  // }
  // public function select_drivers(){
  //
  //   $json_data=array();
  //   $j=0;
  //   $sl_no=1;
  //   $data=array();
  //
  //   $result = $this->Vehicle->select_driver('*',$data);
  //   $result_array=$result->result();
  //
  //   $json_data['draw']=4;
  //   $json_data['recordsTotal']=$result->num_rows();
  //   $json_data['recordsFiltered']=$result->num_rows();
  //   $array=array();
  //   $btn_edit=$btn_delete='';
  //   foreach($result_array as $row):
  //     if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager'){
  //       $btn_edit='<a style="margin-left: 5px;margin-right: 5px" id="driver_edit_btn" href="#driver_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air vehicle_work_slip_edit_btn">
  //       <i class="la la-edit"></i>
  //       </a>';
  //       $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="driver_delete_btn" href="#driver_delete_modal" data-toggle="modal"  class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air ">
  //       <i class="la la-trash"></i>
  //       </a>';
  //     }
  //
  //     $assigned_vehicle_names = '';
  //     $assigned_vehicles = explode(',',$row->assigned_vehicle_names);
  //     foreach ($assigned_vehicles as $key => $value) {
  //       $value = explode(';',$value);
  //       $assigned_vehicle_names.='<a style="margin-top:5px" href="'.base_url().'vehicles/profile/'.$value[2].'" class="btn btn-outline-primary m-btn btn-sm m-btn--custom m-btn--outline-2x" >'.$value[0].' ['.$value[1].']</a><br/>';
  //     }
  //
  //     $array[$j][]=$row->driver_id;
  //     $array[$j][]=$j+1;
  //     $array[$j][]=$row->driver_name;
  //     $array[$j][]=$row->driver_place;
  //     $array[$j][]=$row->driver_mobile;
  //     $array[$j][]=$assigned_vehicle_names;
  //     $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : '.date('d-m-Y',strtotime($row->created_date))."</li><li>Created By : ".$row->user_alias."</li>";
  //     $array[$j][]=$btn_edit.$btn_delete;
  //     $array[$j][]=$row->assigned_vehicles;
  //
  //     $j++;
  //   endforeach;
  //
  //   $json_data['data']=$array;
  //   echo json_encode($json_data);  // send data as json format
  // }

  public function create_consignee(){
    $data['consignee_name'] = $consignee_where['consignee_name'] = $this->security->xss_clean($this->input->post('consignee_name'));
    $data['consignee_place'] = $this->security->xss_clean($this->input->post('place'));
    $data['consignee_mobile'] = $this->security->xss_clean($this->input->post('mobile'));
    $count = $this->Vehicle->select_consignee("",$consignee_where)->num_rows();
    if($count==0) {
      $result = $this->Vehicle->create_consignee($data);
      $flash_data['status'] = $result['status'];
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Consignee Added Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      } else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else{
      $flash_data['status'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. Consignee with Same Number Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function update_consignee(){
    $data['consignee_id'] = $consignee_where['consignee_id !='] = $this->security->xss_clean($this->input->post('consignee_id'));
    $data['consignee_name'] = $consignee_where['consignee_name'] = $this->security->xss_clean($this->input->post('consignee_name'));
    $data['consignee_place'] = $this->security->xss_clean($this->input->post('place'));
    $data['consignee_mobile'] = $this->security->xss_clean($this->input->post('mobile'));
    $count = $this->Vehicle->select_consignee("",$consignee_where)->num_rows();

    if($count==0) {
      $result = $this->Vehicle->update_consignee($data);
      $flash_data['status'] = $result;
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Consignee Details Updated Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      } else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else{
      $flash_data['status'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. Consignee with Same Number Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function delete_consignee(){
    $data['consignee_id'] = $this->security->xss_clean($this->input->post('consignee_id'));
    $data['delete_status'] = 1;
    $result = $this->Vehicle->update_consignee($data);
    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Consignee Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }

    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function select_consignees(){

    $json_data=array();
    $j=0;
    $sl_no=1;
    $data=array();

    $result = $this->Vehicle->select_consignee('*',$data);
    $result_array=$result->result();

    $json_data['draw']=4;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();
    $btn_edit=$btn_delete='';
    foreach($result_array as $row):
      if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager'){
        $btn_edit='<a style="margin-left: 5px;margin-right: 5px" id="consignee_edit_btn" href="#consignee_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air vehicle_work_slip_edit_btn">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="consignee_delete_btn" href="#consignee_delete_modal" data-toggle="modal"  class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air ">
        <i class="la la-trash"></i>
        </a>';
      }

      $vehicle_count = $this->Vehicle->select_vehicle("",array("v.consignee"=>$row->consignee_id))->num_rows();

      $array[$j][]=$row->consignee_id;
      $array[$j][]=$j+1;
      $array[$j][]='<a href="'.base_url().'vehicles/consignees/profile/'.$row->consignee_id.'">'.$row->consignee_name.'</a>';
      $array[$j][]=$row->consignee_place;
      $array[$j][]=$row->consignee_mobile;
      $array[$j][]=$vehicle_count;
      $array[$j][]=$btn_edit.$btn_delete;

      $j++;
    endforeach;

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function select_consignees_list(){
    $data = array();
    if(isset($_POST['id']) && $_POST['id']!=""){
      $data['consignee_id'] = $_POST['id'];
    }
    $result = $this->Vehicle->select_consignee("",$data);
    if($result->num_rows()>0) {
      echo json_encode(array("count" => $result->num_rows(),"data" => $result->result_array()));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }
  public function select_consignee_summary($return_type=''){
    $json_data=$json_data2=array();
    $j=$sl_no=0;
    $data=array();
    $id = $_POST['consignee_id'];
    $vehicle_where['v.consignee'] = $_POST['consignee_id'];
    // Op balance
    $json_data['total_op_balance'] = $this->Vehicle->select_vehicle("COALESCE(SUM(v.vehicle_op_balance),0) as total",$vehicle_where)->row()->total;
    $transaction_where['v.consignee'] = $vehicle_where['v.consignee'];
    $transaction_where['ats.reference_type'] = 'vehicle';
    $transaction_where['ats.tr_type'] = "vehicle_opbalance_transaction";
    $json_data['total_op_balance_paid'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total",$transaction_where,'vehicle_payment')->row()->total;

    $json_data['total_vehicles'] = $this->Vehicle->select_vehicle("",array("v.consignee"=>$id))->num_rows();
    $json_data['total_work_slip_paid'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",array("v.consignee" => $id,"ats.tr_type" => 'vehicle_work_slip_transaction',"ats.reference_type" => 'vehicle_work_slip'),'vehicle_work_slip')->row()->total_amount;
    $json_data['total_work_slip_payable'] = $this->Vehicle_work_slips->select_vehicle_work_slips("COALESCE(SUM(vws.total_payable_amount),0) as total_amount", array("v.consignee" => $id))->row()->total_amount;
    $json_data['total_payable'] = $json_data['total_op_balance']+$json_data['total_work_slip_payable'];
    $json_data['total_paid'] = $json_data['total_work_slip_paid']+$json_data['total_op_balance_paid'];
    $json_data['total_balance'] = $json_data['total_payable']-$json_data['total_paid'];
    foreach ($json_data as $key => $value) {
      $json_data[$key] = $this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($value,$this->config->item('Currency_currency_shortname'));
    }
    if($return_type=='count') {
      echo json_encode($json_data);  // send data as json format
    }else {

    }
  }
  public function pending_payment_list(){
    $json_data['bill_data'] = $json_data['vehicle_op_balance'] = array();
    $work_slip_where['vws.balance >'] = 0;
    $vehicle_where['v.vehicle_op_balance >'] = 0;
    if(isset($_POST['consignee_id']) && $_POST['consignee_id']!=""){
      $work_slip_where['v.consignee'] = $_POST['consignee_id'];
      $vehicle_where['v.consignee'] = $_POST['consignee_id'];
    }
    // Op balance
    $vehicles = $this->Vehicle->select_vehicle("v.*,vc.consignee_name",$vehicle_where)->result();
    foreach ($vehicles as $key => $value) {
      // Check OP Balance Payments
      $transaction_where['ats.reference_id'] = $value->id;
      $transaction_where['ats.reference_type'] = 'vehicle';
      $transaction_where['ats.tr_type'] = "vehicle_opbalance_transaction";
      $op_balance_transaction = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total",$transaction_where,'vehicle_payment')->row()->total;
      if($op_balance_transaction < $value->vehicle_op_balance){
        $value->op_balance_paid = $op_balance_transaction;
        $value->op_balance_balance = $value->vehicle_op_balance-$op_balance_transaction;
        $value->created_date = date('d-m-Y',strtotime($value->created_date));
        $json_data['vehicle_op_balance'][] = $value;
      }
    }

    //bill data
    $json_data['bill_data'] = $this->Vehicle_work_slips->select_vehicle_work_slips("u.*,v.*,wc.*,vws.*,e.employee_name,vws.basic_charge AS vws_basic_charge,vws.basic_charge_2 AS vws_basic_charge_2,vws.basic_charge_3 AS vws_basic_charge_3,vws.remarks AS vws_remarks,vws.balance AS vws_balance,vc.consignee_name", $work_slip_where)->result();

    echo json_encode($json_data);
  }

  public function create_vehicle_payment(){

    $transaction_data['tr_date'] = $transaction_data2['tr_date'] = $transaction_data3['tr_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('paid_date'))));
    $transaction_data['tr_debit_acc'] = $transaction_data2['tr_debit_acc'] = $transaction_data3['tr_debit_acc'] = $this->security->xss_clean($this->input->post('debit_acc'));
    $transaction_data['tr_mode'] = $transaction_data2['tr_mode'] = $transaction_data3['tr_mode'] = $this->security->xss_clean($this->input->post('payment_mode'));
    $transaction_data['tr_reference_no'] = $transaction_data2['tr_reference_no'] = $transaction_data3['tr_reference_no'] = $this->security->xss_clean($this->input->post('reference_no'));
    $transaction_data['created_date'] = $transaction_data2['created_date'] = $transaction_data3['created_date'] = date('Y-m-d H:i:s');
    $transaction_data['created_by'] = $transaction_data2['created_by'] = $transaction_data3['created_by'] = $this->session->userdata('user_id');
    if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
      $transaction_data['tr_entry_approval_status'] = $transaction_data2['tr_entry_approval_status'] = $transaction_data3['tr_entry_approval_status'] = 0;
    }

    $last_tr_group = $this->Account->select_account_transaction("max(ats.tr_group_id) as tr_group_id",'','','','','','all','all');
    if($last_tr_group->num_rows()==1){
      $transaction_data['tr_group_id'] = ($last_tr_group->row()->tr_group_id)+1;
    }else{
      $transaction_data['tr_group_id'] = 1;
    }

    //bill payments
    $transaction_data['reference_type'] = "vehicle_work_slip";
    $transaction_data['tr_type'] = "vehicle_work_slip_transaction";
    $transaction_data['tr_description'] = ucwords(str_replace('_',' ',$transaction_data['tr_type']));

    $bill_count = $this->input->post("bill_count");
    if($bill_count > 0){
      for ($i=0; $i < $bill_count ; $i++)
      {
        $transaction_data['reference_id'] = $this->input->post("bill_id_".$i);
        $transaction_data['tr_amount'] = $this->input->post("amount_".$i);
        if($transaction_data['tr_amount']>0){
          $transaction_data['tr_credit_acc'] = 12;//Vehicle
          $transaction_result1 =  $this->Account->create_account_transaction($transaction_data);
          $flash_data1['status'] = $transaction_result1['status']; //bill payment
          $this->bills_management->calculate_vehicle_work_slip_total($transaction_data['reference_id']);
        }
      }
    }

    // OP Balance Payments
    $transaction_data['reference_type'] = "vehicle";
    $transaction_data['tr_type'] = "vehicle_opbalance_transaction";
    $transaction_data['tr_description'] = ucwords(str_replace('_',' ',$transaction_data['tr_type']));

    $opbalance_count = $this->input->post("op_balance_count");
    if($opbalance_count > 0){
      for ($i=0; $i < $opbalance_count ; $i++)
      {
        $transaction_data['reference_id'] = $this->input->post("vehicle_id_".$i);
        $transaction_data['tr_amount'] = $this->input->post("op_balance_amount_".$i);
        if($transaction_data['tr_amount']>0){
          $transaction_data['tr_credit_acc'] = 12;//Vehicle
          $transaction_result1 =  $this->Account->create_account_transaction($transaction_data);
          $flash_data1['status'] = $transaction_result1['status'];
        }
      }
    }

    if ((isset($flash_data1) && $flash_data1['status'] == 1 ))  {
      $flash_data['status'] = 1;
      $flash_data['flashdata_msg'] = 'Vehicle Payments Created Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);

  }

  public function create_renewal_payment()
  {
    $transaction_data['reference_id'] = $this->security->xss_clean($this->input->post('vehicle_id'));
    $vehicle_details = $this->Vehicle->select_vehicle('',array("v.id"=>$this->input->post('vehicle_id')))->row();
    $transaction_data['tr_other_data'] = $this->security->xss_clean($this->input->post('renewal_type')).";".$this->security->xss_clean($this->input->post('renewal_date'));
    $transaction_data['reference_type'] = "vehicle";
    $transaction_data['tr_type'] = "vehicle_renewal_transaction";
    $transaction_data['tr_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('paid_date'))));
    $transaction_data['tr_debit_acc'] = $this->security->xss_clean($this->input->post('debit_acc'));
    $transaction_data['tr_credit_acc'] = 12;//vehicle work slip
    $transaction_data['tr_description'] = "Vehicle Renewal Transaction";
    $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('paid_amount'));
    $transaction_data['tr_mode'] = $this->security->xss_clean($this->input->post('payment_mode'));
    $transaction_data['tr_reference_no'] = $this->security->xss_clean($this->input->post('reference_no'));
    if($this->input->post('reference_date')!=''){
      $transaction_data['tr_reference_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('reference_date'))));
    }
    $transaction_data['tr_remarks'] = $this->security->xss_clean($this->input->post('tr_remarks'));
    $transaction_data['created_date'] = date('Y-m-d H:i:s');
    $transaction_data['created_by'] = $this->session->userdata('user_id');
    $result =  $this->Account->create_account_transaction($transaction_data);
    $flash_data['status'] = $result['status'];
    if ($result['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Vehicle Renewal Payment Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
      // Update Next Renewal Date
      if($this->input->post('renewal_type')!='emi' && $this->input->post('next_renewal_date')!=''){
        $vehicle_update_data['id'] = $this->security->xss_clean($this->input->post('vehicle_id'));
        if($this->input->post('renewal_type')=='insurance'){
          $vehicle_update_data['insurance_renewal_date'] =  date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('next_renewal_date'))));
        }elseif($this->input->post('renewal_type')=='tax'){
          $vehicle_update_data['tax_renewal_date'] =  date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('next_renewal_date'))));
        }elseif($this->input->post('renewal_type')=='break'){
          $vehicle_update_data['break_renewal_date'] =  date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('next_renewal_date'))));
        }elseif($this->input->post('renewal_type')=='permit'){
          $vehicle_update_data['permit_renewal_date'] =  date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('next_renewal_date'))));
        }elseif($this->input->post('renewal_type')=='fitness'){
          $vehicle_update_data['fitness_renewal_date'] =  date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('next_renewal_date'))));
        }elseif($this->input->post('renewal_type')=='pollution'){
          $vehicle_update_data['pollution_renewal_date'] =  date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('next_renewal_date'))));
        }elseif($this->input->post('renewal_type')=='gps'){
          $vehicle_update_data['gps_renewal_date'] =  date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('next_renewal_date'))));
        }elseif($this->input->post('renewal_type')=='speed_governor'){
          $vehicle_update_data['speed_governor_renewal_date'] =  date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('next_renewal_date'))));
        }elseif($this->input->post('renewal_type')=='welfare'){
          $vehicle_update_data['welfare_renewal_date'] =  date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('next_renewal_date'))));
        }
        $result2 = $this->Vehicle->update_vehicle($vehicle_update_data);
      }elseif($this->input->post('renewal_type')=='emi'){
        $emi_renewal_month = $vehicle_details->next_emi_renewal_date;
        $next_month = date("Y-m-d", strtotime($emi_renewal_month." +1 month"));
        $vehicle_update_data['id'] = $this->security->xss_clean($this->input->post('vehicle_id'));
        $vehicle_update_data['next_emi_renewal_date'] = date("Y-m", strtotime($next_month))."-".$vehicle_details->emi_date;
        $result2 = $this->Vehicle->update_vehicle($vehicle_update_data);
      }
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }

  public function select_renewal_transactions($reference_type='',$list_type='',$param3=""){

    $select_columns= "";
    $json_data=array();
    $j=$sl_no=$total_bill_amount=$total_paid_amount=$total_balance_amount=0;
    $data=array();
    if(isset($_POST['date']) && $_POST['date']!=''){
      $date=array();
      $date=explode('-',$_POST['date']);
      $start_date=date('Y-m-d', strtotime($date[0]));
      $end_date=date('Y-m-d', strtotime($date[1]));
      $data["STR_TO_DATE(ats.tr_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(ats.tr_date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['ats.created_by'] = $_POST['user_id'];
    }

    if($this->config->item('user_data_access_view_all')!=1 && $reference_type=='user_payment_receipt' && $reference_type=='user_payment_return'){
      $data['ats.created_by'] = $this->session->userdata('user_id');
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!='' && $_POST['start_date']!='all'){
      $data['ats.tr_date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!='' && $_POST['end_date']!='all'){
      $data['ats.tr_date <='] = date('Y-m-d', strtotime($_POST['end_date']));
    }

    if(isset($_POST['vehicle_id']) && $_POST['vehicle_id']!='' && $_POST['vehicle_id']!='all'){
      $data['v.id'] = $_POST['vehicle_id'];
    }
    $select_columns = "v.*";

    $reference_type = 'vehicle_renewal';
    $data['ats.reference_type'] = 'vehicle';
    $data['ats.tr_type'] = $reference_type."_transaction";

    $result = $this->Account->select_account_transaction("ats.*,ah1.acc_head_name as debit_account,ah2.acc_head_name as credit_account,u1.user_alias as created_user,vc.consignee_name,".$select_columns,$data,$reference_type);
    $result_array=$result->result();
    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();


    foreach($result_array as $row):
      $sl_no++;
      $btn_edit = $btn_delete = '';
      $transaction_id_column = 1;
      $tr_display_type='';

      if($reference_type=='vehicle_renewal'){
        $bill_type = 'vehicle_renewal';
        $bill_id = $row->id;
        $bill_id_link = $row->tr_other_data;
        $bill_no = '';
        $consignee = $row->consignee_name;
        $project = '<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name ." : ".$row->vehicle_no.'</a>';
        $form_type="vehicle_renewal";
        $transaction_type=$reference_type."_transaction";
      }

      if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='madmin' || $this->session->userdata('user_role')=='general_manager' || ($this->session->userdata('user_role')=='supervisor' && $this->session->userdata('user_id')==$row->created_by)) {
        // Editing Disabled for Purchase Bill Payment Copied From Purchase Order
        $transaction_edit = 1;
        if($this->session->userdata('user_role')=='accounts_manager'){
          $transaction_edit = 0;
        }
        if($transaction_edit==1){
          $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" data-bill-type="'.$bill_type.'" data-bill-id="'.$bill_id.'" data-tr-display-type="'.$tr_display_type.'" id="btn_edit_bill_payment" href="#bill_payment_edit_modal" data-id-column="'.$transaction_id_column.'"  data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-edit"></i>
          </a>';
          $btn_delete = '<a style="margin-left: 5px;margin-right: 5px" data-form-type="'.$form_type.'" data-tr-type="'.$transaction_type.'"  data-id-column="'.$transaction_id_column.'" id="btn_delete_transaction"  href="#transaction_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-trash"></i>
          </a>';
        }
        if($row->reference_type=='supplier'){
          $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="advance_payment_edit_btn" href="#advance_payment_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-edit"></i>
          </a>';
          $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="btn_delete_advance_transaction"  href="#advance_transaction_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-trash"></i>
          </a>';
        }
      }

      $renewal_type = $renewal_date = '';
      if($row->tr_other_data!=''){
        $tr_other_data = explode(';',$row->tr_other_data);
        $renewal_type = $tr_other_data[0];
        $renewal_date = $tr_other_data[1];
      }


      $array[$j][]=$sl_no;
      $array[$j][]=$row->transaction_id;
      $array[$j][]=date('d-m-Y',strtotime($row->tr_date));
      $array[$j][]='<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name ." : ".$row->vehicle_no.'</a>';
      $array[$j][]=$row->consignee_name;
      $array[$j][]=ucwords($renewal_type);
      $array[$j][]=$renewal_date;
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]=number_format($row->tr_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=$row->debit_account;
      $array[$j][]=$row->tr_mode;
      $array[$j][]=$row->tr_reference_no;
      if($row->tr_reference_date!='0000-00-00'){
        $array[$j][]=date('d-m-Y',strtotime($row->tr_reference_date));
      }else{
        $array[$j][]='';
      }
      $array[$j][]=$row->tr_remarks;
      $array[$j][]=$row->created_user;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][]=date('d-m-Y',strtotime($row->created_date));
      }else{
        $array[$j][]='';
      }
      $array[$j][]=$btn_edit.$btn_delete;
      $array[$j][]=$row->tr_debit_acc;

      $total_paid_amount+=$row->tr_amount;

      $j++;
    endforeach;
    if($result->num_rows()>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_paid_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="";
      $array[$j][]='';
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";


    }

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }

  public function select_pending_renewal(){

    $json_data=array();
    $j=0;
    $sl_no=1;
    $data=array();
    if(isset($_POST['vehicle_type']) && $_POST['vehicle_type']!='' && $_POST['vehicle_type']!='all'){
      $data['v.vehicle_type'] = $_POST['vehicle_type'];
    }
    if(isset($_POST['vehicle_id']) && $_POST['vehicle_id']!='' && $_POST['vehicle_id']!='all'){
      $data['v.id'] = $_POST['vehicle_id'];
    }
    $select_colum='v.*,u.*,v.created_date AS v_created_date,v.created_by AS v_created_by';
    if($this->session->userdata('user_role')!='admin'){
      // $data['v.created_by'] = $this->session->userdata('user_id');
    }
    $result = $this->Vehicle->select_vehicle($select_colum,$data);
    $result_array=$result->result();

    $json_data['draw']=4;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();
    $slno=0;

    foreach($result_array as $row):
      $today = new DateTime(date('Y-m-d'));
      if($this->session->userdata('user_role')!='auditor' || $this->session->userdata('user_data_permission')['adding']==1) {
        $btn_add_payment = '<a style="margin-left: 5px;margin-right: 5px" id="btn_add_renewal_payment" href="#vehicle_renewal_add_modal"   data-toggle="modal" class="btn btn-info m-btn m-btn--icon btn-sm  m-btn--pill m-btn--air">
        <i class="la la-plus-circle"></i> Add Payment
        </a>';
      }

      if($row->emi_status==1 && $row->next_emi_renewal_date!='0000-00-00' && $row->next_emi_renewal_date<=date('Y-m-d',strtotime("+".$this->config->item('Vehicle_emi_reminder_days_before')." days"))){
        $emi_renewal_date = new DateTime($row->next_emi_renewal_date);
        $emi_date_diff_days = $today->diff($emi_renewal_date)->format("%r%a");
        if($emi_date_diff_days<=0){
          $status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Due</span>";
        }else{
          $status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Pending</span>";
        }

        $slno++;
        $array[$j][]=$slno;
        $array[$j][]='<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name ." : ".$row->vehicle_no.'</a>';
        $array[$j][]='EMI';
        $array[$j][]=date('d-m-Y',strtotime($row->next_emi_renewal_date));
        $array[$j][]=$status;
        $array[$j][]=$btn_add_payment;
        $array[$j][]=$row->id;
        $array[$j][]='emi';
        $j++;
      }

      if($row->insurance_renewal_date!='0000-00-00' && $row->insurance_renewal_date<=date('Y-m-d',strtotime("+".$this->config->item('Vehicle_insurance_reminder_days_before')." days"))){
        $insurance_renewal_date = new DateTime($row->insurance_renewal_date);
        $insurance_date_diff_days = $today->diff($insurance_renewal_date)->format("%r%a");
        if($insurance_date_diff_days<=0){
          $status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Due</span>";
        }else{
          $status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Pending</span>";
        }

        $slno++;
        $array[$j][]=$slno;
        $array[$j][]='<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name ." : ".$row->vehicle_no.'</a>';
        $array[$j][]='Insurance';
        $array[$j][]=date('d-m-Y',strtotime($row->insurance_renewal_date));
        $array[$j][]=$status;
        $array[$j][]=$btn_add_payment;
        $array[$j][]=$row->id;
        $array[$j][]='insurance';
        $j++;
      }

      if($row->tax_renewal_date!='0000-00-00' && $row->tax_renewal_date<=date('Y-m-d',strtotime("+".$this->config->item('Vehicle_tax_reminder_days_before')." days"))){
        $tax_renewal_date = new DateTime($row->tax_renewal_date);
        $tax_date_diff_days = $today->diff($tax_renewal_date)->format("%r%a");
        if($tax_date_diff_days<=0){
          $status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Due</span>";
        }else{
          $status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Pending</span>";
        }

        $slno++;
        $array[$j][]=$slno;
        $array[$j][]='<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name ." : ".$row->vehicle_no.'</a>';
        $array[$j][]='Tax';
        $array[$j][]=date('d-m-Y',strtotime($row->tax_renewal_date));
        $array[$j][]=$status;
        $array[$j][]=$btn_add_payment;
        $array[$j][]=$row->id;
        $array[$j][]='tax';
        $j++;
      }

      if($row->break_renewal_date!='0000-00-00' && $row->break_renewal_date<=date('Y-m-d',strtotime("+".$this->config->item('Vehicle_break_reminder_days_before')." days"))){
        $break_renewal_date = new DateTime($row->break_renewal_date);
        $break_date_diff_days = $today->diff($break_renewal_date)->format("%r%a");
        if($break_date_diff_days<=0){
          $status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Due</span>";
        }else{
          $status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Pending</span>";
        }

        $slno++;
        $array[$j][]=$slno;
        $array[$j][]='<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name ." : ".$row->vehicle_no.'</a>';
        $array[$j][]='Break';
        $array[$j][]=date('d-m-Y',strtotime($row->break_renewal_date));
        $array[$j][]=$status;
        $array[$j][]=$btn_add_payment;
        $array[$j][]=$row->id;
        $array[$j][]='break';
        $j++;
      }

      if($row->permit_renewal_date!='0000-00-00' && $row->permit_renewal_date<=date('Y-m-d',strtotime("+".$this->config->item('Vehicle_permit_reminder_days_before')." days"))){
        $permit_renewal_date = new DateTime($row->permit_renewal_date);
        $permit_date_diff_days = $today->diff($permit_renewal_date)->format("%r%a");
        if($permit_date_diff_days<=0){
          $status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Due</span>";
        }else{
          $status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Pending</span>";
        }

        $slno++;
        $array[$j][]=$slno;
        $array[$j][]='<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name ." : ".$row->vehicle_no.'</a>';
        $array[$j][]='Permit';
        $array[$j][]=date('d-m-Y',strtotime($row->permit_renewal_date));
        $array[$j][]=$status;
        $array[$j][]=$btn_add_payment;
        $array[$j][]=$row->id;
        $array[$j][]='permit';
        $j++;
      }

      if($row->fitness_renewal_date!='0000-00-00' && $row->fitness_renewal_date<=date('Y-m-d',strtotime("+".$this->config->item('Vehicle_fitness_reminder_days_before')." days"))){
        $fitness_renewal_date = new DateTime($row->fitness_renewal_date);
        $fitness_date_diff_days = $today->diff($fitness_renewal_date)->format("%r%a");
        if($fitness_date_diff_days<=0){
          $status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Due</span>";
        }else{
          $status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Pending</span>";
        }

        $slno++;
        $array[$j][]=$slno;
        $array[$j][]='<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name ." : ".$row->vehicle_no.'</a>';
        $array[$j][]='Fitness';
        $array[$j][]=date('d-m-Y',strtotime($row->fitness_renewal_date));
        $array[$j][]=$status;
        $array[$j][]=$btn_add_payment;
        $array[$j][]=$row->id;
        $array[$j][]='fitness';
        $j++;
      }

      if($row->pollution_renewal_date!='0000-00-00' && $row->pollution_renewal_date<=date('Y-m-d',strtotime("+".$this->config->item('Vehicle_pollution_reminder_days_before')." days"))){
        $pollution_renewal_date = new DateTime($row->pollution_renewal_date);
        $pollution_date_diff_days = $today->diff($pollution_renewal_date)->format("%r%a");
        if($pollution_date_diff_days<=0){
          $status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Due</span>";
        }else{
          $status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Pending</span>";
        }

        $slno++;
        $array[$j][]=$slno;
        $array[$j][]='<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name ." : ".$row->vehicle_no.'</a>';
        $array[$j][]='Pollution';
        $array[$j][]=date('d-m-Y',strtotime($row->pollution_renewal_date));
        $array[$j][]=$status;
        $array[$j][]=$btn_add_payment;
        $array[$j][]=$row->id;
        $array[$j][]='pollution';
        $j++;
      }

      if($row->gps_renewal_date!='0000-00-00' && $row->gps_renewal_date<=date('Y-m-d',strtotime("+".$this->config->item('Vehicle_gps_reminder_days_before')." days"))){
        $gps_renewal_date = new DateTime($row->gps_renewal_date);
        $gps_date_diff_days = $today->diff($gps_renewal_date)->format("%r%a");
        if($gps_date_diff_days<=0){
          $status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Due</span>";
        }else{
          $status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Pending</span>";
        }

        $slno++;
        $array[$j][]=$slno;
        $array[$j][]='<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name ." : ".$row->vehicle_no.'</a>';
        $array[$j][]='GPS';
        $array[$j][]=date('d-m-Y',strtotime($row->gps_renewal_date));
        $array[$j][]=$status;
        $array[$j][]=$btn_add_payment;
        $array[$j][]=$row->id;
        $array[$j][]='gps';
        $j++;
      }

      if($row->speed_governor_renewal_date!='0000-00-00' && $row->speed_governor_renewal_date<=date('Y-m-d',strtotime("+".$this->config->item('Vehicle_speed_governor_reminder_days_before')." days"))){
        $speed_governor_renewal_date = new DateTime($row->speed_governor_renewal_date);
        $speed_governor_date_diff_days = $today->diff($speed_governor_renewal_date)->format("%r%a");
        if($speed_governor_date_diff_days<=0){
          $status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Due</span>";
        }else{
          $status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Pending</span>";
        }

        $slno++;
        $array[$j][]=$slno;
        $array[$j][]='<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name ." : ".$row->vehicle_no.'</a>';
        $array[$j][]='Speed Governor';
        $array[$j][]=date('d-m-Y',strtotime($row->speed_governor_renewal_date));
        $array[$j][]=$status;
        $array[$j][]=$btn_add_payment;
        $array[$j][]=$row->id;
        $array[$j][]='speed_governor';
        $j++;
      }

      if($row->welfare_renewal_date!='0000-00-00' && $row->welfare_renewal_date<=date('Y-m-d',strtotime("+".$this->config->item('Vehicle_welfare_reminder_days_before')." days"))){
        $welfare_renewal_date = new DateTime($row->welfare_renewal_date);
        $welfare_date_diff_days = $today->diff($welfare_renewal_date)->format("%r%a");
        if($welfare_date_diff_days<=0){
          $status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Due</span>";
        }else{
          $status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Pending</span>";
        }

        $slno++;
        $array[$j][]=$slno;
        $array[$j][]='<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name ." : ".$row->vehicle_no.'</a>';
        $array[$j][]='Welfare';
        $array[$j][]=date('d-m-Y',strtotime($row->welfare_renewal_date));
        $array[$j][]=$status;
        $array[$j][]=$btn_add_payment;
        $array[$j][]=$row->id;
        $array[$j][]='welfare';
        $j++;
      }

    endforeach;

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }

  public function create_allocation(){
    $data['vehicle_id'] = $allocation_where['vehicle_id'] = $this->security->xss_clean($this->input->post('vehicle_id'));
    $data['date'] = $allocation_where['date'] = date('Y-m-d',strtotime($this->input->post('date')));
    $data['allocation_type'] = $this->security->xss_clean($this->input->post('allocation_status'));
    if($data['allocation_type']==1){
      $data['location_id'] = $this->security->xss_clean($this->input->post('location'));
      $data['driver_id'] = $this->security->xss_clean($this->input->post('driver'));
    }
    $data['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');
    $count = $this->Vehicle->select_vehicle_allocations("",$allocation_where)->num_rows();

    if($count==0) {
      $result = $this->Vehicle->create_vehicle_allocation($data);
      $flash_data['status'] = $result['status'];
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Vehicle Allocated Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      } else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else{
      $flash_data['status'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. Vehicle Already Allocated on Selected Date!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function update_allocation(){
    $data['allocation_id'] = $allocation_where['allocation_id !='] = $this->security->xss_clean($this->input->post('allocation_id'));
    $data['allocation_type'] = $this->security->xss_clean($this->input->post('allocation_status'));
    if($data['allocation_type']==1){
      $data['location_id'] = $this->security->xss_clean($this->input->post('location'));
      $data['driver_id'] = $this->security->xss_clean($this->input->post('driver'));
    }else{
      $data['location_id'] =   $data['driver_id'] = 0;
    }
    $data['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $result = $this->Vehicle->update_vehicle_allocation($data);
    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Vehicle Allocation Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function delete_allocation(){
    $data['allocation_id'] = $this->security->xss_clean($this->input->post('allocation_id'));
    $data['delete_status'] = 1;
    $result = $this->Vehicle->update_vehicle_allocation($data);
    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Vehicle Allocation Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function select_vehicle_allocations(){

    $json_data=array();
    $j=0;
    $sl_no=1;
    $data=array();
    if(isset($_POST['vehicle_type']) && $_POST['vehicle_type']!='' && $_POST['vehicle_type']!='all'){
      $data['v.vehicle_type'] = $_POST['vehicle_type'];
    }
    if(isset($_POST['vehicle_category']) && $_POST['vehicle_category']!='' && $_POST['vehicle_category']!='all'){
      $data['v.vehicle_category'] = $_POST['vehicle_category'];
    }
    if(isset($_POST['vehicle_id']) && $_POST['vehicle_id']!='' && $_POST['vehicle_id']!='all'){
      $data['v.id'] = $_POST['vehicle_id'];
    }
    $allocation_type_filter = 'all';
    if(isset($_POST['allocation_type']) && $_POST['allocation_type']!='' && $_POST['allocation_type']!='all'){
      $allocation_type_filter = $_POST['allocation_type'];
    }
    $select_colum='v.*,u.*,v.created_date AS v_created_date,v.created_by AS v_created_by';
    if($this->session->userdata('user_role')!='admin'){
      // $data['v.created_by'] = $this->session->userdata('user_id');
    }
    $result = $this->Vehicle->select_vehicle($select_colum,$data);
    $result_array=$result->result();

    $json_data['draw']=4;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();
    foreach($result_array as $row):

      if(isset($_POST['date']) && $_POST['date']!=''){
        $date=array();
        $date=explode('-',$_POST['date']);
        $start_date=date('Y-m-d', strtotime($date[0]));
        $end_date=date('Y-m-d', strtotime($date[1]));
        // of period 1 day
        $interval = new DateInterval('P1D');
        $realEnd = new DateTime($end_date);
        $realEnd->add($interval);
        $date_period = new DatePeriod(new DateTime($start_date), $interval, $realEnd);
        foreach ($date_period as $key => $value) {
          $date = date('Y-m-d',strtotime($value->format('Y-m-d')));

          // Check Allocation
          $allocation_data = $this->Vehicle->select_vehicle_allocations('va.*,v.vehicle_no,v.vehicle_name,sl.location_name,e.employee_name',array("va.vehicle_id"=>$row->id,"va.date"=>$date));
          $btn_add = $btn_edit = $btn_delete ='';
          $allocated = 0;
          if($allocation_data->num_rows()==1){
            $allocated = 1;
            $allocation_data = $allocation_data->row();
            if($allocation_data->allocation_type==0){
              $status="<span class='m-badge m-badge--info m-badge--wide'><i class='fa fa-times-circle'></i> Idle</span>";
            }elseif($allocation_data->allocation_type==1){
              $status="<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check-circle'></i> Allocated</span>";
            }else{
              $status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-cogs'></i> Maintenance/Service</span>";
            }
            $remarks = $allocation_data->remarks;
            $location_name = $allocation_data->location_name;
            $driver_name = $allocation_data->employee_name;
            $allocation_type = $allocation_data->allocation_type;
            $location_id = $allocation_data->location_id;
            $driver_id = $allocation_data->driver_id;
            $allocation_id = $allocation_data->allocation_id;
            if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager'){
              $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="vehicle_allocation_edit_btn" href="#vehicle_allocation_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
              <i class="la la-edit"></i>
              </a>';
              $btn_delete = '<a style="margin-left: 5px;margin-right: 5px" id="vehicle_allocation_delete_btn" href="#vehicle_allocation_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
              <i class="la la-trash"></i>
              </a>';
            }
          }else{
            $status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Not Allocated</span>";
            $location_name = $driver_name = $remarks = $location_id = $driver_id = $allocation_id = '';
            if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager'){
              $btn_add = '<a style="margin-left: 5px;margin-right: 5px" id="allocation_add_btn" href="#vehicle_allocation_add_modal" data-toggle="modal" class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
              <i class="la la-plus-circle"></i>
              </a>';
            }
            $allocation_type = "Not";
          }
          if($allocation_type_filter=='all' || $allocation_type_filter==$allocation_type){

            $array[$j][]=$j+1;
            $array[$j][]=date('d-m-Y',strtotime($value->format('Y-m-d')));
            $array[$j][]='<a href="'.base_url().'vehicles/profile/'.$row->id.'">'.$row->vehicle_no.' ['.$row->vehicle_category.']</a>';
            $array[$j][]=$status;
            $array[$j][]=$location_name;
            $array[$j][]=$driver_name;
            $array[$j][]=$remarks;
            $array[$j][]=$btn_add.$btn_edit.$btn_delete;
            $array[$j][]=$row->id;
            $array[$j][]=$allocation_type;
            $array[$j][]=$location_id;
            $array[$j][]=$driver_id;
            $array[$j][]=$allocation_id;

            $j++;
          }
        }
      }

    endforeach;

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }

  public function select_vehicle_expenses($page_data_type=''){

    $json_data=array();
    $j=$sl_no=$total_bill_amount=$total_paid_amount=$total_balance_amount=$total_tax_amount=0;
    $data=array();
    if(isset($_POST['date']) && $_POST['date']!=''){
      $date=array();
      $date=explode('-',$_POST['date']);
      $start_date=date('Y-m-d', strtotime($date[0]));
      $end_date=date('Y-m-d', strtotime($date[1]));
      $data["STR_TO_DATE(b.bill_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(b.bill_date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['bill_supplier_id']) && $_POST['bill_supplier_id']!='' && $_POST['bill_supplier_id']!='all'){
      $data['b.bill_supplier_id'] = $_POST['bill_supplier_id'];
    }
    if(isset($_POST['expense_head']) && $_POST['expense_head']!='' && $_POST['expense_head']!='all'){
      $data['b.bill_credit_ac'] = $_POST['expense_head'];
    }
    if(isset($_POST['vehicle_id']) && $_POST['vehicle_id']!='' && $_POST['vehicle_id']!='all'){
      $data['b.vehicle_id'] = $_POST['vehicle_id'];
    }
    if(isset($_POST['expense_type']) && $_POST['expense_type']!='' && $_POST['expense_type']!='all'){
      $data['b.bill_expense_type'] = $_POST['expense_type'];
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['b.work_id'] = $_POST['work'];
    }
    if(isset($_POST['stage_id']) && $_POST['stage_id']!='' && $_POST['stage_id']!='all'){
      $data['b.project_stage_id'] = $_POST['stage_id'];
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['b.created_by'] = $_POST['user_id'];
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!='' && $_POST['start_date']!='all'){
      $data['b.bill_date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!='' && $_POST['end_date']!='all'){
      $data['b.bill_date <='] = date('Y-m-d', strtotime($_POST['end_date']));
    }
    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    }
    if($this->config->item('user_data_access_view_all')!=1){
      $data['b.created_by'] = $this->session->userdata('user_id');
    }
    $entry_approval = 1;
    if($this->config->item('User_enable_data_entry_approval')==1){//webapp users approval
      $entry_approval = 'all';
    }
    if($page_data_type=='approval_entries'){
      $entry_approval = 'all';
      $data['u.user_role >'] =2;
      if(isset($_POST['approval_status']) && $_POST['approval_status']!='' && $_POST['approval_status']!='all'){
        $entry_approval = $_POST['approval_status'];
      }
    }

    $data['b.bill_type'] = 'vehicle';
    $result	= $this->Bills->select_bills("b.*,s.supplier_name,ah1.acc_head_name as expense_head_name,u.user_alias,wc.work_name,v.id,v.vehicle_no,v.vehicle_name,vc.consignee_name as vehicle_consignee_name",$data,'','','',$entry_approval);
    $result_array=$result->result();

    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();

    foreach($result_array as $row):
      $sl_no++;
      $id=$row->work_id;
      $bill_id_column= 24;//Column Where Bill ID Exist
      $btn_edit = $btn_delete = $btn_add_payment = '';
      if(($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_id')==$row->created_by) && ($this->config->item('User_enable_data_entry_approval')!=1 || $row->entry_approval_status!=1 || $this->session->userdata('user_role')=='admin')) {
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="vehicle_expense_edit_btn" href="#vehicle_expense_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete = '<a style="margin-left: 5px;margin-right: 5px" data-bill-type="vehicle_bill" data-bill-id-column="'.$bill_id_column.'" id="btn_delete_bill"  href="#bill_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-trash"></i>
        </a>';
      }
      if($this->session->userdata('user_role')!='auditor' || $this->session->userdata('user_data_permission')['adding']==1){
        if($row->bill_payment_status!=1){
          $btn_add_payment = '<a style="margin-left: 5px;margin-right: 5px" data-bill-type="vehicle_bill" data-bill-id-column="'.$bill_id_column.'" id="btn_add_bill_payment" href="#bill_payment_add_modal" data-toggle="modal" class="btn btn-focus m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-plus-circle"></i>
          </a>';
        }
      }

      if($row->bill_payment_status==1){
        $bill_payment_status="<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Paid</span>";
      }elseif($row->bill_payment_status==2){
        $bill_payment_status="<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Partially Paid</span>";
      }else{
        $bill_payment_status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Not Paid</span>";
      }
      $bill_attachment = $bill_attachment_url = $bill_attachment_btn = "";
      if($row->bill_attachment!=''){
        $bill_attachment = $row->bill_attachment;
        $bill_attachment_url =  base_url()."uploads/bills/".$bill_attachment;
        $bill_attachment_btn = '<a target="_blank" href="'.$bill_attachment_url.'">View Attachment</a>';
      }

      $btn_approve = $entry_approval_status = '';
      if(($this->session->userdata('user_role')=='admin' || ($this->session->userdata('user_role')=='accounts_manager' && $row->created_user_role_id>2 && (($this->config->item('User_enable_data_entry_approval_2_level')==0 && $row->created_user_role_id != 16) || $this->config->item('User_enable_data_entry_approval_2_level')==1))) && $page_data_type=='approval_entries' && $this->config->item('Mobile_App_enable_data_entry_approval')==1){
        $btn_approve = '<a style="margin-left: 5px;margin-right: 5px" data-type="expense_bill" data-approval-status="'.$row->entry_approval_status.'" data-id="'.$row->bill_id.'" id="btn_data_entry_approval" href="#data_entry_approve_modal" data-toggle="modal" class="btn btn-sm btn-warning m-btn m-btn--icon  m-btn--pill m-btn--air">
        <i class="la la-check-circle"></i> / <i class="la la-times-circle"></i>
        </a>';
      }
      if(($page_data_type=='approval_entries' && $this->config->item('Mobile_App_enable_data_entry_approval')==1) || $this->config->item('User_enable_data_entry_approval')==1){
        if($row->entry_approval_status==1){
          $entry_approval_status="<br/><span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Approved</span>";
        }elseif($row->entry_approval_status==2){
          $entry_approval_status="<br/><span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> Rejected</span>";
        }else{
          $entry_approval_status="<br/><span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> Pending</span>";
        }
      }

      $array[$j][]=$sl_no;
      $array[$j][]='<a id="m_quick_sidebar_toggle" data-type="bill_profile" data-bill-type="vehicle_bill" data-id="'.$row->bill_id.'" href="javascript:;">#'.$row->bill_id.'</a>';
      $array[$j][]=date('d-m-Y',strtotime($row->bill_date));
      $array[$j][]='<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name ." : ".$row->vehicle_no.'</a>';
      $array[$j][]=$row->bill_expense_type;
      $array[$j][]=$row->expense_head_name;
      $array[$j][]=$row->supplier_name;
      $array[$j][]=$row->bill_no;
      $array[$j][]=$row->bill_consignee_name;
      $array[$j][]=$row->bill_tax_percent;
      $array[$j][]=number_format($row->bill_tax_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=number_format($row->bill_payable_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=number_format($row->bill_total_paid,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=number_format($row->bill_balance_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=$bill_payment_status;
      $array[$j][]=$row->bill_description;
      $array[$j][]=$row->bill_remarks;
      $array[$j][]=$bill_attachment_btn;
      $array[$j][]='<a href="'.base_url().'work/profile/'.$id.'">'.$row->work_name.'</a>';
      $array[$j][]=$row->user_alias.$entry_approval_status;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][]=date('d-m-Y',strtotime($row->created_date));
      }else{
        $array[$j][]='';
      }
      $array[$j][]=$btn_add_payment.$btn_edit.$btn_delete.$btn_approve;
      $array[$j][]=$row->bill_credit_ac;
      $array[$j][]=$row->id;
      $array[$j][]=$row->bill_id;
      $array[$j][]=$bill_attachment;
      $array[$j][]=$row->bill_tax_percent;
      $array[$j][]=$row->bill_tax_amount;
      $array[$j][]=$row->bill_supplier_id;
      $array[$j][]=$row->entry_approval_status;

      $total_tax_amount+=$row->bill_tax_amount;
      $total_bill_amount+=$row->bill_payable_amount;
      $total_paid_amount+=$row->bill_total_paid;
      $total_balance_amount+=$row->bill_balance_amount;
      $j++;
    endforeach;
    if($result->num_rows()>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]='';
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_tax_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_bill_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_paid_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_balance_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
      $array[$j][]="";
    }

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }

  public function create_document(){
    $data['vehicle_id'] = $this->security->xss_clean($this->input->post('vehicle_id'));
    $data['document_type'] = $this->security->xss_clean($this->input->post('document_type'));
    $data['file'] = $this->security->xss_clean($this->input->post('file'));
    $data['file_type'] = 'google_drive';
    $data['file_remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');
    $result = $this->Vehicle->create_vehicle_document($data);
    $flash_data['status'] = $result['status'];
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Vehicle Document Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function update_document(){
    $data['document_id'] = $this->security->xss_clean($this->input->post('document_id'));
    $data['document_type'] = $this->security->xss_clean($this->input->post('document_type'));
    $data['file'] = $this->security->xss_clean($this->input->post('file'));
    $data['file_type'] = 'google_drive';
    $data['file_remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $result = $this->Vehicle->update_vehicle_document($data);
    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Vehicle Document Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function delete_document(){
    $data['document_id'] = $this->security->xss_clean($this->input->post('document_id'));
    $data['delete_status'] = 1;
    $result = $this->Vehicle->update_vehicle_document($data);
    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Vehicle Document Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo(json_encode($flash_data));
  }
  public function select_vehicle_documents(){

    $json_data=array();
    $j=0;
    $sl_no=1;
    $data=array();
    if(isset($_POST['vehicle_type']) && $_POST['vehicle_type']!='' && $_POST['vehicle_type']!='all'){
      $data['v.vehicle_type'] = $_POST['vehicle_type'];
    }
    if(isset($_POST['vehicle_id']) && $_POST['vehicle_id']!='' && $_POST['vehicle_id']!='all'){
      $data['v.id'] = $_POST['vehicle_id'];
    }
    $select_colum='vd.*,u.user_alias,v.vehicle_name,v.vehicle_no';
    if($this->session->userdata('user_role')!='admin'){
      // $data['v.created_by'] = $this->session->userdata('user_id');
    }
    $result = $this->Vehicle->select_vehicle_documents($select_colum,$data);
    $result_array=$result->result();

    $json_data['draw']=4;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();
    foreach($result_array as $row):

      $btn_add = $btn_edit = $btn_delete ='';
      if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager'){
        $btn_edit='<a style="margin-left: 5px;margin-right: 5px" id="vehicle_document_edit_btn" href="#vehicle_document_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air vehicle_work_slip_edit_btn">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="vehicle_document_delete_btn" href="#vehicle_document_delete_modal" data-toggle="modal"  class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air ">
        <i class="la la-trash"></i>
        </a>';
      }

      $array[$j][]=$j+1;
      $array[$j][]='<a href="'.base_url().'vehicles/profile/'.$row->vehicle_id.'">'.$row->vehicle_name.' ['.$row->vehicle_no.']</a>';
      $array[$j][]=$row->document_type;
      $array[$j][]='<a target="_blank" href="'.$row->file.'">'.$row->file.'</a>';
      $array[$j][]=$row->file_remarks;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : '.date('d-m-Y',strtotime($row->created_date))."</li><li>Created By : ".$row->user_alias."</li>";
      }else{
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->user_alias.'</li>';
      }
      $array[$j][]=$btn_add.$btn_edit.$btn_delete;
      $array[$j][]=$row->vehicle_id;
      $array[$j][]=$row->file_type;
      $array[$j][]=$row->file;
      $array[$j][]=$row->document_id;

      $j++;

    endforeach;

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function select_vehicle_profit_loss_report($page_data_type=''){

    $json_data=$array=array();
    $j=$sl_no=0;

    $gt_material_consumption = $gt_total_expense = $gt_driver_salary = $gt_staff_salary = $gt_spare_parts_bill_amount = $gt_service_bill_amount = $gt_workshop_amount = $gt_fuel_amount = $gt_company_income = $gt_outside_income = $gt_emi_amount = $gt_insurance_amount = $gt_tax_amount = $gt_fitness_amount = $gt_break_amount = $gt_permit_amount = $gt_pollution_amount = $gt_gps_amount =  $gt_welfare_amount = $gt_speed_governor_amount = 0;

    $data=$work_slip_where=array();
    if(isset($_POST['vehicle_id']) && $_POST['vehicle_id']!='' && $_POST['vehicle_id']!='all'){
      $data['v.vehicle_id'] = $_POST['vehicle_id'];
    }
    if(isset($_POST['date']) && $_POST['date']!=''){
      $date=array();
      $date=explode('-',$_POST['date']);
      $start_date=date('Y-m-d', strtotime($date[0]));
      $end_date=date('Y-m-d', strtotime($date[1]));
      $work_slip_where["STR_TO_DATE(vws.worked_date,'%Y-%m-%d') <="]= $end_date;
      $work_slip_where["STR_TO_DATE(vws.worked_date,'%Y-%m-%d') >="]= $start_date;
      $work_slip_expense_where["STR_TO_DATE(vws.worked_date,'%Y-%m-%d') <="]= $end_date;
      $work_slip_expense_where["STR_TO_DATE(vws.worked_date,'%Y-%m-%d') >="]= $start_date;
      $bill_where["STR_TO_DATE(b.bill_date,'%Y-%m-%d') <="]= $end_date;
      $bill_where["STR_TO_DATE(b.bill_date,'%Y-%m-%d') >="]= $start_date;
    }

    $data['vehicle_type'] = 'own';
    $result	= $this->Vehicle->select_vehicle("v.*",$data);

    foreach($result->result() as $row):
      $sl_no++;

      $work_slip_where['vws.vehicle_id'] = $row->id;
      $work_slip_where['vws.work_slip_type'] = 'inside_work';
      $gt_company_income += $total_company_income = $this->Vehicle_work_slips->select_vehicle_work_slips("COALESCE(SUM(vws.total_payable_amount),0) as total", $work_slip_where)->row()->total;
      $work_slip_where['vws.work_slip_type'] = 'outside_work';
      $gt_outside_income += $total_outside_income = $this->Vehicle_work_slips->select_vehicle_work_slips("COALESCE(SUM(vws.total_payable_amount),0) as total", $work_slip_where)->row()->total;

      $renewal_transaction_where['v.id'] = $row->id;
      $reference_type = 'vehicle_renewal';
      $renewal_transaction_where['ats.reference_type'] = 'vehicle';
      $renewal_transaction_where['ats.tr_type'] = $reference_type."_transaction";

      $this->db->where("ats.tr_other_data like '%emi%'");
      $gt_emi_amount += $emi_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total",$renewal_transaction_where,$reference_type)->row()->total;

      $this->db->where("ats.tr_other_data like '%insurance%'");
      $gt_insurance_amount += $insurance_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total",$renewal_transaction_where,$reference_type)->row()->total;

      $this->db->where("ats.tr_other_data like '%tax%'");
      $gt_tax_amount += $tax_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total",$renewal_transaction_where,$reference_type)->row()->total;

      $this->db->where("ats.tr_other_data like '%fitness%'");
      $gt_fitness_amount += $fitness_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total",$renewal_transaction_where,$reference_type)->row()->total;

      $this->db->where("ats.tr_other_data like '%break%'");
      $gt_break_amount += $break_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total",$renewal_transaction_where,$reference_type)->row()->total;

      $this->db->where("ats.tr_other_data like '%permit%'");
      $gt_permit_amount += $permit_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total",$renewal_transaction_where,$reference_type)->row()->total;

      $this->db->where("ats.tr_other_data like '%pollution%'");
      $gt_pollution_amount += $pollution_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total",$renewal_transaction_where,$reference_type)->row()->total;

      $this->db->where("ats.tr_other_data like '%gps%'");
      $gt_gps_amount += $gps_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total",$renewal_transaction_where,$reference_type)->row()->total;

      $this->db->where("ats.tr_other_data like '%welfare%'");
      $gt_welfare_amount += $welfare_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total",$renewal_transaction_where,$reference_type)->row()->total;

      $this->db->where("ats.tr_other_data like '%speed_governor%'");
      $gt_speed_governor_amount += $speed_governor_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total",$renewal_transaction_where,$reference_type)->row()->total;

      $work_slip_expense_where['vws.vehicle_id'] = $row->id;
      $work_slip_expense_where['expense_head'] = 'Fuel';
      $gt_fuel_amount += $fuel_amount	= $this->Vehicle_work_slips->select_vehicle_work_slip_expense("COALESCE(SUM(vwse.total_amount),0) as total",$work_slip_expense_where,"","","","","")->row()->total;

      $work_slip_expense_where['expense_head'] = 'Workshop';
      $gt_workshop_amount += $workshop_amount = $this->Vehicle_work_slips->select_vehicle_work_slip_expense("COALESCE(SUM(vwse.total_amount),0) as total",$work_slip_expense_where,"","","","","")->row()->total;

      $bill_where['b.bill_type'] = 'vehicle';
      $bill_where['b.vehicle_id'] = $row->id;
      $bill_where['b.bill_expense_type'] = 'Workshop';
      $gt_workshop_amount += $workshop_bill_amount	= $this->Bills->select_bills("COALESCE(SUM(b.bill_payable_amount),0) as total",$bill_where)->row()->total;

      $bill_where['b.bill_expense_type'] = 'Service';
      $gt_service_bill_amount += $service_bill_amount	= $this->Bills->select_bills("COALESCE(SUM(b.bill_payable_amount),0) as total",$bill_where)->row()->total;

      $bill_where['b.bill_expense_type'] = 'Spare_Parts';
      $gt_spare_parts_bill_amount += $spare_parts_bill_amount = $this->Bills->select_bills("COALESCE(SUM(b.bill_payable_amount),0) as total",$bill_where)->row()->total;

      $stock_consumption_where['sc.vehicle_id'] = $row->id;
      $gt_material_consumption += $material_consumption = $this->Stock->select_stock_consumption("COALESCE(SUM(sc.consumption_qty*sr.unit_price),0) as total", $stock_consumption_where)->row()->total;

      $gt_staff_salary += $staff_salary = 0;
      $gt_driver_salary += $driver_salary = 0;
      $gt_total_expense += $total_expense = ($emi_amount+$insurance_amount+$tax_amount+$break_amount+$permit_amount+$fitness_amount+$pollution_amount+$gps_amount+$speed_governor_amount+$welfare_amount+$fuel_amount+$workshop_amount+$workshop_bill_amount+$service_bill_amount+$spare_parts_bill_amount+$staff_salary+$driver_salary+$material_consumption);

      $array[$j][]=$sl_no;
      $array[$j][]='<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">'.$row->vehicle_name." : ".$row->vehicle_no. '</a>';
      $array[$j][]=$row->vehicle_category;
      $array[$j][]=$total_company_income;
      $array[$j][]=$total_outside_income;
      $array[$j][]=$total_company_income+$total_outside_income;
      $array[$j][]=$emi_amount;
      $array[$j][]=$insurance_amount;
      $array[$j][]=$tax_amount;
      $array[$j][]=$break_amount;
      $array[$j][]=$permit_amount;
      $array[$j][]=$fitness_amount;
      $array[$j][]=$pollution_amount;
      $array[$j][]=$gps_amount;
      $array[$j][]=$speed_governor_amount;
      $array[$j][]=$welfare_amount;
      $array[$j][]=$fuel_amount;
      $array[$j][]=$workshop_amount+$workshop_bill_amount;
      $array[$j][]=$service_bill_amount;
      $array[$j][]=$spare_parts_bill_amount;
      $array[$j][]=$staff_salary;
      $array[$j][]=$driver_salary;
      $array[$j][]=$material_consumption;
      $array[$j][]=$total_expense;

      $j++;
    endforeach;

    if($result->num_rows()>0){
      $array[$j][]='';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]='';
      $array[$j][]="<strong>".$gt_company_income."</strong>";
      $array[$j][]="<strong>".$gt_outside_income."</strong>";
      $array[$j][]="<strong>".($gt_outside_income+$gt_company_income)."</strong>";
      $array[$j][]="<strong>".$gt_emi_amount."</strong>";
      $array[$j][]="<strong>".$gt_insurance_amount."</strong>";
      $array[$j][]="<strong>".$gt_tax_amount."</strong>";
      $array[$j][]="<strong>".$gt_break_amount."</strong>";
      $array[$j][]="<strong>".$gt_permit_amount."</strong>";
      $array[$j][]="<strong>".$gt_fitness_amount."</strong>";
      $array[$j][]="<strong>".$gt_pollution_amount."</strong>";
      $array[$j][]="<strong>".$gt_gps_amount."</strong>";
      $array[$j][]="<strong>".$gt_speed_governor_amount."</strong>";
      $array[$j][]="<strong>".$gt_welfare_amount."</strong>";
      $array[$j][]="<strong>".$gt_fuel_amount."</strong>";
      $array[$j][]="<strong>".$gt_workshop_amount."</strong>";
      $array[$j][]="<strong>".$gt_service_bill_amount."</strong>";
      $array[$j][]="<strong>".$gt_spare_parts_bill_amount."</strong>";
      $array[$j][]="<strong>".$gt_staff_salary."</strong>";
      $array[$j][]="<strong>".$gt_driver_salary."</strong>";
      $array[$j][]="<strong>".$gt_material_consumption."</strong>";
      $array[$j][]="<strong>".$gt_total_expense."</strong>";



    }

    $json_data['data']=$array;
    $json_data['draw']=5;
    $json_data['recordsTotal']=sizeof($array);
    $json_data['recordsFiltered']=sizeof($array);
    echo json_encode($json_data);  // send data as json format
  }
}
?>
