<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Customers 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('Client_model', 'Client');
    $this->load->model('Supplier_model', 'Supplier');
    $this->load->model('Purchase_bill_model', 'Purchases');
    $this->load->model('Purchase_order_model', 'Purchase_order');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Customers_model', 'Customers');
    $this->load->model('Services_model','Services');

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

  }

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

  public function view()
  {
    $this->page_data['tax_state_codes'] = $this->Settings->select_tax_state_codes("*")->result();
    $this->page_data['page_name'] = 'customers_view';
    $this->load->view('Index', $this->page_data);
  }
  public function profile($id='')
  {
    $this->page_data['services'] = $this->Services->select_services("",array('active_status'=>1))->result();
    $this->page_data['services_all'] = $this->Services->select_services("*")->result();

    if($id!="") {
      $this->page_data['customer_data'] = $this->Customers->select_customer("*", array("customer_id" => $id));
      if($this->page_data['customer_data']->num_rows()==1){
        $this->page_data['customer_data'] = $this->page_data['customer_data']->row();
        $this->page_data['page_name'] = 'customer_profile';
        $this->load->view('Index', $this->page_data);
      }else{
        show_404();
      }
    }
    else{
      show_404();
    }
  }

  public function create()
  {
    $data['customer_phone']=$customer_where['customer_phone']=$this->security->xss_clean($this->input->post('mobile_number'));
    $count = $this->Customers->select_customer("",$customer_where)->num_rows();
    if($count == 0) {
      $data['customer_name'] = $this->security->xss_clean($this->input->post('customer_name'));
      $data['contact_person'] = $this->security->xss_clean($this->input->post('contact_person'));
      $data['customer_location'] = $this->security->xss_clean($this->input->post('address'));
      $data['customer_email'] = $this->security->xss_clean($this->input->post('email'));
      if($this->input->post('taxno')){
        $data['customer_tax_no'] = $this->security->xss_clean($this->input->post('taxno'));
      }
      if($this->input->post('state_id')){
        $data['customer_tax_state'] = $this->security->xss_clean($this->input->post('state_id'));
      }
      if($this->input->post('sale_price_category')){
        $data['sale_price_category'] = $this->security->xss_clean($this->input->post('sale_price_category'));
      }
      $data['created_date'] = date('Y-m-d H:i:s');
      $data['created_by'] = $this->session->userdata('user_id');
      if ($this->session->userdata('branch_id') != 0) {
        $data['branch_id'] = $this->session->userdata('branch_id');
      }
      $result = $this->Customers->create_customer($data);

      $flash_data['status'] = $result['status'];
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Customer 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'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. A Customer with Same mobile number Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Customer Duplication !!';
    }
    echo(json_encode($flash_data));

  }

  public function update()
  {
    $data['customer_phone'] = $customer_where['customer_phone'] = $this->security->xss_clean($this->input->post('mobile_number'));
    $data['customer_id'] = $customer_where['customer_id !='] = $this->security->xss_clean($this->input->post('customer_id'));
    $count = $this->Customers->select_customer("",$customer_where)->num_rows();
    if($count == 0) {
      $data['contact_person'] = $this->security->xss_clean($this->input->post('contact_person'));
      $data['customer_name'] = $this->security->xss_clean($this->input->post('customer_name'));
      $data['customer_location'] = $this->security->xss_clean($this->input->post('address'));
      $data['customer_email'] = $this->security->xss_clean($this->input->post('email'));
      $data['updated_date'] = date('Y-m-d H:i:s');
      $data['updated_by'] = $this->session->userdata('user_id');
      if($this->input->post('taxno')){
        $data['customer_tax_no'] = $this->security->xss_clean($this->input->post('taxno'));
      }
      if($this->input->post('state_id')){
        $data['customer_tax_state'] = $this->security->xss_clean($this->input->post('state_id'));
      }
      if($this->input->post('sale_price_category')){
        $data['sale_price_category'] = $this->security->xss_clean($this->input->post('sale_price_category'));
      }
      $result = $this->Customers->update_customer($data);

      $client_data = $this->Client->select_client('client_id',array("customer_id"=>$data['customer_id']));
      if($client_data->num_rows()==1){
        $client_update_data['client_id'] = $client_data->row()->client_id;
        $client_update_data['client_name'] = $data['customer_name'];
        $client_update_data['client_contact'] = $data['customer_phone'];
        $client_update_data['contact_person'] = $data['contact_person'];
        $client_update_data['client_address'] = $data['customer_location'];
        $client_update_data['client_email'] = $data['customer_email'];
        $client_update_data['updated_date'] = date('Y-m-d H:i:s');
        $client_update_data['updated_by'] = $this->session->userdata('user_id');
        $result2 = $this->Client->update_client($client_update_data);
      }

      $flash_data['status'] = $result;
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Customer 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'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. A Customer with Same mobile number Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Customer Duplication !!';
    }
    echo(json_encode($flash_data));

  }

  public function select_customers()
  {
    $json_data=array();
    $j=0;
    $sl_no=0;
    $data=array();

    if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
      $data['c.branch_id'] = $_POST['branch_id'];
    }

    $result = $this->Customers->select_customer("",$data);
    $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):

      $btn_edit=$btn_delete='';

      if($this->session->userdata('user_role')!='auditor'){
        $btn_edit='<a style="margin-left: 5px;margin-right: 5px" id="customer_edit_btn" href="#customer_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="customer_delete_btn" href="#customer_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>';
      }

      $sl_no++;


      $array[$j][]=$row->customer_id;
      $array[$j][]=$sl_no;
      $array[$j][]=($row->branch_id==0)?'No Branch':$this->Branches->select_branches('*',array('branch_id'=>$row->branch_id))->row()->branch_name;
      // $array[$j][]='<a href="'.base_url().'customers/profile/'.$row->customer_id.'" >'.$row->customer_name.'</a>';
      $array[$j][]=$row->customer_name;
      $array[$j][]=$row->contact_person;
      $array[$j][]=$row->customer_phone;
      $array[$j][]=$row->customer_email;
      $array[$j][]=$row->customer_location;
      $array[$j][]=$this->config->item('Material_sale_price'.$row->sale_price_category.'_name');
      $array[$j][]=$row->customer_tax_no;
      $array[$j][]=$row->state_name."-".$row->state_code;
      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->state_id;
      $array[$j][]=$row->sale_price_category;


      $j++;
    endforeach;

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

  public function select(){
    $data['delete_status'] = 0;
    if(isset($_POST['id']) && $_POST['id']!=""){
      $data['customer_id'] = $_POST['id'];
    }
    if(isset($_POST['tax_type']) && $_POST['tax_type']!=""){
      if($_POST['tax_type']=='B2B'){
        $data['customer_tax_no !='] = '';
      }else{
        $data['customer_tax_no'] = '';
      }
    }
    $result	= $this->Customers->select_customer("",$data);
    if($result->num_rows()>0) {
      foreach ($result->result() as $row):
        $id[] = $row->customer_id;
        $name[] = $row->customer_name;
        $location[]  = $row->customer_location;
        $phone[] = $row->customer_phone;
      endforeach;
      echo json_encode(array("count" => $result->num_rows(),"id" => $id,"name" => $name,"location" => $location,"phone" => $phone));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }

  public function select_details(){
    if(isset($_POST['id']) && $_POST['id']!=""){
      $data['customer_id'] = $_POST['id'];
    }
    $result	= $this->Customers->select_customer("",$data);
    if($result->num_rows()==1) {
      echo json_encode(array("count" => $result->num_rows(),"data" => $result->row()));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }

  public function select_customers_2()
  {
    $data = array();
    if(isset($_POST['customer_id']) && $_POST['customer_id']!='' && $_POST['customer_id']!='all'){
      $data['c.customer_id'] = $_POST['customer_id'];
    }
    $result = $this->Customers->select_customer("*",$data);
    if($result->num_rows()>0) {
      foreach ($result->result() as $row):
        $id[] = $row->customer_id;
        $name[] = $row->customer_name;
        $phone[] = $row->customer_phone;
        $contact_person[] = $row->contact_person;

      endforeach;
      echo json_encode(array("count" => $result->num_rows(),"id" => $id,"name" => $name,"phone" => $phone,"contact_person" => $contact_person));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }

  public function delete()
  {
    $data['customer_id']=$this->security->xss_clean($this->input->post('customer_id'));
    $data['delete_status']=1;
    $result = $this->Customers->update_customer($data);
    $flash_data['status'] = $result;
    if ($result == 1 ) {
      $flash_data['flashdata_msg'] = 'Customer 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 !!';
    }
    echo(json_encode($flash_data));
  }

}
?>
