<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Purchases 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('Material_model', 'Material');
    $this->load->model('Stock_model', 'Stock');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Settings_model', 'Settings');
    $this->load->library('Stock_management','stock_management');
    $this->load->library('Bills_management','bills_management');
    $this->load->model('Boq_model', 'Boq');
    $this->load->model('Bills_model', 'Bills');
    $this->load->model('Labour_model', 'Labour');
    $this->load->model('Vehicle_model', 'Vehicle');
    $this->load->model('Vehicle_work_slips_model', 'Vehicle_work_slips');
    $this->load->library('Projects_management','projects_management');
    $this->load->library('Boq_management', 'boq_management');

    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin","admin","supervisor","general_manager","purchase_manager","accounts_manager","boq_manager","auditor","qs","qs_manager","procurement_engineer","project_manager","operation_manager");
    if($this->User->is_logged_in($allowed_user_roles)==false){
      redirect(base_url(), 'refresh');
    }
    $company_details = $this->Settings->select_settings('*',array("settings_category"=>"Company Details"))->result();
    foreach ($company_details as $key => $value) {
      $this->page_data[$value->settings_name] = $value->value;
    }
    //        File Directory
    $this->page_data['directory'] = "purchases";
    $this->page_data['supplier_categories'] = $this->Supplier->select_supplier_category()->result();

    $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();
  }
  public function index()
  {
    $this->view();
  }
  public function payments()
  {
    $this->page_data['page_name'] = 'purchase_payments';

    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, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    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)");
    }
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations()->result();

    $this->page_data['suppliers_list'] = $this->Supplier->select_supplier('*')->result();
    $this->load->view('Index',$this->page_data);
  }
  public function view($param='')
  {
    $this->page_data['material_list'] = $this->Material->select_material()->result();

    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, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    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)");
    }
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations()->result();

    $this->page_data['suppliers_list'] = $this->Supplier->select_supplier('*')->result();
    $this->page_data['list_type'] = $param;
    $this->page_data['page_name'] = 'purchase_view';
    $this->load->view('Index',$this->page_data);
  }
  public function return($param='')
  {
    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)");
    }
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations()->result();

    if ($this->session->userdata('user_role') == 'supervisor') {

    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['suppliers_list'] = $this->Supplier->select_supplier('*')->result();
    $this->page_data['materials'] = $this->Material->select_material()->result();
    $this->page_data['material_categories'] = $this->Material->select_category("")->result();
    if($param=='add'){
      $this->page_data['page_name'] = 'purchase_return_add';
    }else{
      $this->page_data['page_name'] = 'purchase_return_view';
    }

    $this->load->view('Index',$this->page_data);
  }
  public function materials()
  {
    $this->page_data['materials'] = $this->Material->select_material()->result();

    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, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    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)");
    }
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations()->result();

    $this->page_data['suppliers_list'] = $this->Supplier->select_supplier('*')->result();
    $this->page_data['page_name'] = 'purchased_materials';
    $this->load->view('Index',$this->page_data);
  }
  public function edit($id="")
  {
    if($id!=''){
      $this->page_data['purchase_data'] = $this->Purchases->select_purchase("*,p.created_by as purchase_created_by", array("p.purchase_id" =>$id,"p.sales_invoice_id"=>0 ),$this->config->item('select_data_entry_approval'),'','',$this->config->item('select_data_entry_approval'));
      if($this->page_data['purchase_data']->num_rows()==1 && ($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager' || $this->page_data['purchase_data']->row()->purchase_created_by == $this->session->userdata('user_id'))){
        $this->page_data['purchase_data'] = $this->page_data['purchase_data']->row();

        $this->page_data['page_name'] = 'purchase_edit';

        $this->page_data['purchase_order_id'] = "";
        $this->page_data['purchase_order_payment_total'] = 0;
        if($this->page_data['purchase_data']->purchase_order_id != 0){
          //        Select Order Details
          $this->page_data['purchase_order_data'] = $this->Purchase_order->select_purchase_order("po.*,u.user_alias,s.supplier_name,sl.location_name",array("po.order_id"=>$this->page_data['purchase_data']->purchase_order_id));
          if($this->page_data['purchase_order_data']->num_rows()==1){
            $this->page_data['purchase_order_data'] = $this->page_data['purchase_order_data']->row();
            $this->page_data['purchase_order_id'] = $this->page_data['purchase_order_data']->order_id;
            $this->page_data['purchase_order_items'] = $this->Purchase_order->select_purchase_order_items("", array("poi.order_id" =>$this->page_data['purchase_data']->purchase_order_id))->result();
            $this->page_data['purchase_order_payment_total'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $this->page_data['purchase_data']->purchase_order_id, "ats.reference_type" => 'purchase_order'),'purchase_order')->row()->total_paid_amount;
          }
        }

        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, w.assigned_users)");
        }
        $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

        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)");
        }
        $this->page_data['stock_locations'] = $this->Stock->select_stock_locations()->result();

        $this->page_data['suppliers_list'] = $this->Supplier->select_supplier('*')->result();
        $this->page_data['material_list'] = $this->Material->select_material()->result();
        $this->page_data['measure_units'] = $this->Material->select_unit()->result();
        $this->page_data['purchase_items'] = $this->Purchases->select_purchase_items("",array("pi.purchase_id"=>$id),'','','',$this->config->item('select_data_entry_approval'),'',$this->config->item('select_data_entry_approval'))->result();

        // Other Charges
        $this->page_data['loading_charge'] = $this->page_data['transportation_charge'] = 0;

        $other_data['b.purchase_id'] = $id;
        $other_data['ats.reference_type'] = 'expense_bill';
        $other_data['ats.tr_credit_acc'] = 19;

        $loading_charge = $this->Account->select_account_transaction("*", $other_data ,'expense_bill');
        if($loading_charge->num_rows()==1){
          $this->page_data['loading_charge'] = $loading_charge->row()->tr_amount;
        }

        $other_data['ats.tr_credit_acc'] = 20;
        $transportation_charge = $this->Account->select_account_transaction("*", $other_data,'expense_bill');
        if($transportation_charge->num_rows()==1){
          $this->page_data['transportation_charge'] = $transportation_charge->row()->tr_amount;
        }

        $this->load->view('Index',$this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }

  }
  public function profile($id="")
  {
    if($id!=''){
      $this->page_data['purchase_data'] = $this->Purchases->select_purchase("*,p.created_by as purchase_created_by", array("p.purchase_id" =>$id ),$this->config->item('select_data_entry_approval'),'','',$this->config->item('select_data_entry_approval'));
      if($this->page_data['purchase_data']->num_rows()==1){
        $this->page_data['purchase_data'] = $this->page_data['purchase_data']->row();
        $this->page_data['page_name'] = 'purchase_profile';
        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, w.assigned_users)");
        }
        $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
        $this->page_data['purchase_items'] = $this->Purchases->select_purchase_items("pi.*,m.material_name,mu.unit_name,tt.tax_percentage,tt.tax1_percent,tt.tax2_percent,tt.tax3_percent",array("pi.purchase_id"=>$id),'','','',$this->config->item('select_data_entry_approval'),'',$this->config->item('select_data_entry_approval'))->result();
        $order_id = $this->page_data['purchase_data']->purchase_order_id;
        $this->page_data['purchase_order_items'] = $this->Purchase_order->select_purchase_order_items("",array("poi.order_id"=>$order_id))->result();

        $this->page_data['purchase_payments'] = $this->Account->select_account_transaction("ats.*,ah1.acc_head_name as debit_account,u1.user_alias as created_user", array("ats.reference_id" => $id, "ats.reference_type" => 'purchase_bill'),'purchase_bill','','','','','','all','all')->result();
        $this->page_data['advance_return_payments'] = $this->Account->select_advance_return_transaction("art.*,u.user_alias as created_user",array("art.reference_id" => $id,"art.tr_type" => 'purchase_bill_transaction',"art.reference_type" => 'purchase_bill'))->result();
        $this->page_data['total_supplier_advance_payments'] = $this->Account->select_advance_return_transaction("COALESCE(SUM(art.tr_amount),0) as total_amount",array("art.reference_id" => $id,"art.tr_type" => 'purchase_bill_transaction',"art.reference_type" => 'purchase_bill'))->row()->total_amount;

        $other_charge_where['ats.reference_type'] = 'expense_bill';
        $other_charge_where['ats.tr_type'] = "expense_bill_transaction";
        $other_charge_columns = "b.bill_id,b.bill_no,b.bill_consignee_name,b.bill_type,wc.work_name,b.work_id,sc.sub_work_name,sc.contract_id";
        $other_charge_where['b.purchase_id'] = $id;
        $this->page_data['other_charges'] = $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,".$other_charge_columns,$other_charge_where,'expense_bill')->result();

        $this->load->view('Index',$this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }

  public function delivery_challan($page="",$challan_id='')
  {
    if($page=='add' && isset($_GET['order_id']) && $_GET['order_id']!=''){
      $this->page_data['purchase_order_data'] = $this->Purchase_order->select_purchase_order("po.*,u.user_alias,s.supplier_name,sl.location_name",array("po.order_id"=>$_GET['order_id']));
      if($this->page_data['purchase_order_data']->num_rows()==1){
        $this->page_data['purchase_order_data'] = $this->page_data['purchase_order_data']->row();
        $this->page_data['purchase_order_id'] = $this->page_data['purchase_order_data']->order_id;
        $this->page_data['purchase_order_items'] = $this->Purchase_order->select_purchase_order_items("", array("poi.order_id" =>$_GET['order_id']))->result();
        foreach ($this->page_data['purchase_order_items'] as $key => $value) {
          // Get Total Received Quantity
          $value->received_qty = $this->Purchases->select_purchase_items("COALESCE(SUM(pi.quantity),0) as total", array("p.purchase_order_id" =>$this->page_data['purchase_order_data']->order_id,"pi.material_id"=>$value->material_id))->row()->total;
        }

        $this->page_data['page_name'] = 'delivery_challan_add';
        $this->load->view('Index',$this->page_data);
      }else{
        show_404();
      }
    }else{
      if($challan_id!=''){
        $this->page_data['challan_data'] = $this->Purchases->select_delivery_challan("*,po.created_by as challan_created_by", array("pdc.challan_id" =>$challan_id ),$this->config->item('select_data_entry_approval'));
        if($this->page_data['challan_data']->num_rows()==1){
          $this->page_data['challan_data'] = $this->page_data['challan_data']->row();

          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, w.assigned_users)");
          }
          $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

          $this->page_data['suppliers_list'] = $this->Supplier->select_supplier('*')->result();
          $this->page_data['material_list'] = $this->Material->select_material()->result();
          $this->page_data['measure_units'] = $this->Material->select_unit()->result();
          $this->page_data['purchase_bills'] = $this->Purchases->select_purchase("*,p.created_by as purchase_created_by", array("p.delivery_challan_id" =>$challan_id ),$this->config->item('select_data_entry_approval'))->result();

          $this->page_data['challan_items'] = $this->Purchases->select_delivery_challan_items("", array("pdci.challan_id" =>$challan_id ))->result();
          foreach ($this->page_data['challan_items'] as $key => $value) {
            // Get Total Received Quantity
            $value->received_qty = $this->Purchases->select_purchase_items("COALESCE(SUM(pi.quantity),0) as total", array("p.delivery_challan_id" =>$challan_id,"pi.material_id"=>$value->material_id))->row()->total;
          }

          $this->page_data['page_name'] = 'delivery_challan_profile';
          $this->load->view('Index',$this->page_data);
        }else{
          show_404();
        }
      }else{
        $this->page_data['page_name'] = 'delivery_challan_view';
        $this->load->view('Index',$this->page_data);
      }
    }
  }
  public function add($work_id="")
  {
    $this->page_data['previous_purchase_id'] = "";
    $previous_purchase_id = $this->Purchases->select_purchase("max(p.purchase_id) as purchase_id");
    if($previous_purchase_id->num_rows()==1){
      $this->page_data['previous_purchase_id'] = $previous_purchase_id->row()->purchase_id;
    }

    $this->page_data['page_name'] = 'purchase_add';
    $this->page_data['work_id'] = "";
    if(isset($_GET['work']) && $_GET['work']!=''){
      $this->page_data['selected_location'] = $_GET['work'];
    }
    $this->page_data['purchase_order_id'] = $this->page_data['delivery_challan_id'] = "";
    $this->page_data['purchase_order_payment_total'] = 0;
    $this->page_data['purchase_order_payment_total_advance'] = 0;
    if(isset($_GET['order_id']) && $_GET['order_id']!=''){
      //        Select Order Details
      $this->page_data['purchase_order_data'] = $this->Purchase_order->select_purchase_order("po.*,u.user_alias,s.supplier_name,sl.location_name",array("po.order_id"=>$_GET['order_id']));
      if($this->page_data['purchase_order_data']->num_rows()==1){
        $this->page_data['purchase_order_data'] = $this->page_data['purchase_order_data']->row();
        $this->page_data['purchase_order_id'] = $this->page_data['purchase_order_data']->order_id;
        $this->page_data['purchase_order_items'] = $this->Purchase_order->select_purchase_order_items("", array("poi.order_id" =>$this->page_data['purchase_order_id']))->result();
        foreach ($this->page_data['purchase_order_items'] as $key => $value) {
          // Get Total Received Quantity
          $value->received_qty = $this->Purchases->select_purchase_items("COALESCE(SUM(pi.quantity),0) as total", array("p.purchase_order_id" =>$this->page_data['purchase_order_data']->order_id,"pi.material_id"=>$value->material_id))->row()->total;
        }
        $this->page_data['purchase_order_payment_total'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $this->page_data['purchase_order_id'], "ats.reference_type" => 'purchase_order'),'purchase_order')->row()->total_paid_amount;
        $this->page_data['purchase_order_payment_total_advance'] = $this->Account->select_advance_return_transaction("COALESCE(SUM(art.tr_amount),0) as total_amount",array("art.reference_id" => $this->page_data['purchase_order_id'],"art.tr_type" => 'purchase_order_transaction',"art.reference_type" => 'purchase_order'))->row()->total_amount;
      }
    }
    if(isset($_GET['challan_id']) && $_GET['challan_id']!=''){
      //        Select Order Details
      $this->page_data['purchase_order_data'] = $this->Purchases->select_delivery_challan("pdc.*,po.*,u.user_alias,s.supplier_name,sl.location_name",array("pdc.challan_id"=>$_GET['challan_id']));
      if($this->page_data['purchase_order_data']->num_rows()==1){
        $this->page_data['purchase_order_data'] = $this->page_data['purchase_order_data']->row();
        $this->page_data['purchase_order_id'] = $this->page_data['purchase_order_data']->order_id;
        $this->page_data['delivery_challan_id'] = $this->page_data['purchase_order_data']->challan_id;
        $this->page_data['purchase_order_items'] = $this->Purchases->select_delivery_challan_items("", array("pdci.challan_id" =>$this->page_data['delivery_challan_id']))->result();
        foreach ($this->page_data['purchase_order_items'] as $key => $value) {
          // Get Total Received Quantity
          $value->received_qty = $this->Purchases->select_purchase_items("COALESCE(SUM(pi.quantity),0) as total", array("p.purchase_order_id" =>$this->page_data['purchase_order_data']->order_id,"pi.material_id"=>$value->material_id))->row()->total;
        }
        $this->page_data['purchase_order_payment_total'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $this->page_data['purchase_order_id'], "ats.reference_type" => 'purchase_order'),'purchase_order')->row()->total_paid_amount;
        $this->page_data['purchase_order_payment_total_advance'] = $this->Account->select_advance_return_transaction("COALESCE(SUM(art.tr_amount),0) as total_amount",array("art.reference_id" => $this->page_data['purchase_order_id'],"art.tr_type" => 'purchase_order_transaction',"art.reference_type" => 'purchase_order'))->row()->total_amount;
      }
    }
    if($work_id!=0){
      $this->page_data['location_data'] = $this->Stock->select_stock_locations("*", array("sl.work_id" =>$work_id));
    }
    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, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    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)");
    }
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations()->result();

    $this->page_data['suppliers_list'] = $this->Supplier->select_supplier('*')->result();
    $this->page_data['material_list'] = $this->Material->select_material()->result();
    $this->page_data['measure_units'] = $this->Material->select_unit()->result();
    $this->page_data['purchase_data'] = $this->Purchases->select_purchase()->result();
    $this->load->view('Index',$this->page_data);

  }

  public function create(){
    if($this->config->item('app_module_vehicle_management')==1){
      $data['purchase_bill_type'] = $this->security->xss_clean($this->input->post('purchase_type'));
      if($this->input->post('vehicle_id')){
        $data['vehicle_id'] = $this->security->xss_clean($this->input->post('vehicle_id'));
      }
    }
    $data['location_id'] = $this->security->xss_clean($this->input->post('location'));
    $location_data = $this->Stock->select_stock_locations("sl.*",array("location_id"=>$data['location_id']));
    $data['purchase_order_id'] = $this->security->xss_clean($this->input->post('purchase_order_id'));
    $data['delivery_challan_id'] = $this->security->xss_clean($this->input->post('delivery_challan_id'));
    $data['supplier_id'] = $this->security->xss_clean($this->input->post('supplier'));
    $data['purchase_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('purchase_date'))));
    $data['bill_invoice_no'] = $this->security->xss_clean($this->input->post('invoice_no'));
    $count = 0;
    if($data['bill_invoice_no']!='' && $this->config->item('Purchase_disable_bill_no_duplication_check')==0){
      $count = $this->Purchases->select_purchase("p.purchase_id", array("p.bill_invoice_no" =>$data['bill_invoice_no'],"p.supplier_id" =>$data['supplier_id']),'all')->num_rows();
    }
    $data['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data['vehicle_no'] = $this->security->xss_clean($this->input->post('vehicle_no'));

    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');
    $data['bill_discount_amount'] = $this->security->xss_clean($this->input->post('bill_discount_amount'));
    $data['bill_tax_amount'] = $this->security->xss_clean($this->input->post('bill_tax_amount'));
    $data['bill_tds_amount'] = $this->security->xss_clean($this->input->post('bill_tds_amount'));
    $data['bill_other_amount'] = $this->security->xss_clean($this->input->post('bill_other_amount'));
    $data['bill_round_amount'] = $this->security->xss_clean($this->input->post('bill_round_amount'));
    $data['bill_total_amount'] = $this->security->xss_clean($this->input->post('bill_total_amount'));
    $data['bill_payable_amount'] = $this->security->xss_clean($this->input->post('bill_payable_amount'));
    if($count==0){
      $project_id = $location_data->row()->work_id;

      if($location_data->num_rows()==1 && $location_data->row()->location_type=='work_site'){
        $transaction_data['tr_project_stage_id'] = $data['project_stage_id'] = $this->projects_management->get_project_stage_id($location_data->row()->work_id);
      }
      if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
        $data['entry_approval_status'] = 0;
      }
      if($this->config->item('User_enable_data_entry_approval_2_level')==1 && $this->session->userdata('user_role_id')>2){
        $data['entry_approval_status_2'] = 0;
      }
      $data['bill_save_status'] = 1;

      // if($data['purchase_order_id']!=''){
      //   $purchase_count = $this->Purchases->select_purchase("",array("p.purchase_order_id"=>$data['purchase_order_id'],"p.delete_status"=>0));
      //   $count = $purchase_count->num_rows();
      //   if($count>0){
      //     $flash_data['flashdata_msg'] = 'A Purchase Bill (#'.$purchase_count->row()->purchase_id.') is Already Created For Purchase Order ID #'.$data['purchase_order_id'].'. Please Check..';
      //     $flash_data['flashdata_type'] = "warning";
      //     $flash_data['flashdata_title'] = "Already Created";
      //     $flash_data['status'] = 2;
      //   }
      // }else{
      //   $count = 0;
      // }
      // if($count==0){
      //      File Validations
      $file_error = 0;
      if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']["size"] > 0) {
        //      File Upload
        $config['upload_path']   = 'uploads/bills/';
        $config['allowed_types'] = 'jpg|jpeg|png|pdf|doc|docx|xls|xl';
        $config['max_size']      = 3000;
        // $config['max_width']     = 1980;
        // $config['max_height']    = 1080;
        $config['encrypt_name']    = TRUE;
        // $config['file_name'] = date('YmdHis');
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('uploaded_file')) {
          $error = array('error' => $this->upload->display_errors());
          $file_error = 1;
          $flash_data['flashdata_msg'] = $error['error'];
          $flash_data['flashdata_type'] = "warning";
          $flash_data['flashdata_title'] = "Uploaded File Error";
          $flash_data['status'] = 2;
        }else {
          $file_data = $this->upload->data();
          $data['bill_attachment'] = $file_data['file_name'];
        }
      }


      if($location_data->row()->location_type=='work_site' && $this->config->item('boq_purchase_integration')==1){
        // Cart Items
        $items_array=$newArrayitems=array();
        if($this->input->post('item')){
          $items_array = $this->input->post('item');
        }
        $items_array_length = sizeof($items_array);
        // Convert to New Formatted Array
        foreach (array_keys($items_array) as $fieldKey) {
          foreach ($items_array[$fieldKey] as $key=>$value) {
            $newArrayitems[$key][$fieldKey] = $value;
          }
        }

        $allow = array();

        foreach ($newArrayitems as $row) {
          // BOQ Intergration
          $integration = $this->select_boq_task_item_for_purchase($project_id,$data['location_id'],$row['material_id'],$row['unit_id'],'purchase');
          $boq_count = $integration['boq_count'];
          $boq_item_count = $integration['count'];
          $unit_rate = $integration['unit_rate'];
          $total_amount = $integration['total_amount'];
          $qnty = $integration['qnty'];

          if($boq_count>0){
            if($boq_item_count>0){
              if($row['quantity']>$qnty){
                $allow['quantity'][] = 0;
                $allowed = 0;
              }else{
                $allow['quantity'][] = 1;
                $allowed = 1;
              }

              if($row['unit_price']>$unit_rate){
                $allow['unit_price'][] = 0;
                $allowed = 0;
              }
              else{
                $allow['unit_price'][] = 1;
                $allowed = 1;
              }

              if($row['total_amount']>$total_amount){
                $allow['total_amount'][] = 0;
                $allowed = 0;
              }
              else{
                $allow['total_amount'][] = 1;
                $allowed = 1;
              }
            }
            else{
              $allow['item'][] = 0;
              $allowed = 0;
            }
          }else{
            $allow['boq'][] = 0;
            $allowed = 0;
          }
        }
      }else{
        $allowed = 1;
      }

      $message = '';

      if(isset($allow['boq']) && in_array(1, $allow['boq'])){
        $allowed = 0;
        $message .= 'No Approved BOQ available <br>';
      }

      if(isset($allow['quantity']) && in_array(0, $allow['quantity'])){
        $message = $this->set_items_messages($allow['quantity'],$message,'exceeds allowed quantity<br>');
        $allowed = 0;
      }
      if(isset($allow['unit_price']) && in_array(0, $allow['unit_price'])){
        $message = $this->set_items_messages($allow['unit_price'],$message,'exceeds allowed unit price<br>');
        $allowed = 0;
      }
      if(isset($allow['total_amount']) && in_array(0, $allow['total_amount'])){
        $message = $this->set_items_messages($allow['total_amount'],$message,'exceeds allowed total amount<br>');
        $allowed = 0;
      }

      // Insert  Cart Items
      $items_array=$newArrayitems=array();
      if($this->input->post('item')){
        $items_array = $this->input->post('item');
      }
      $items_array_length = sizeof($items_array);
      // Convert to New Formatted Array
      foreach (array_keys($items_array) as $fieldKey) {
        foreach ($items_array[$fieldKey] as $key=>$value) {
          $newArrayitems[$key][$fieldKey] = $value;
        }
      }

      if($data['purchase_order_id']!='' && ($this->config->item('Purchase_from_po_bill_item_unit_price_restriction')==1 || $this->config->item('Purchase_from_po_qty_exceed_restriction')==1)){
        $purchase_order_items = $this->Purchase_order->select_purchase_order_items("", array("poi.order_id" =>$data['purchase_order_id']))->result();
        $order_items_data = array();
        foreach ($purchase_order_items as $key => $value) {
          // Get Total Received Quantity
          $order_items_data[$value->item_id]['item_id'] = $value->item_id;
          $order_items_data[$value->item_id]['quantity'] = $value->quantity;
          $order_items_data[$value->item_id]['unit_price'] = $value->unit_price;
          $order_items_data[$value->item_id]['received_qty'] = $this->Purchases->select_purchase_items("COALESCE(SUM(pi.quantity),0) as total", array("p.purchase_order_id" =>$data['purchase_order_id'],"pi.material_id"=>$value->material_id))->row()->total;
          $order_items_data[$value->item_id]['balance_qty'] = round(($value->quantity-$order_items_data[$value->item_id]['received_qty']),2);
        }
        foreach ($newArrayitems as $row) {
          if(isset($row['order_item_id']) && isset($order_items_data[$row['order_item_id']]['item_id'])){
            if($this->config->item('Purchase_from_po_bill_item_unit_price_restriction')==1){
              if($row['unit_price']>$order_items_data[$row['order_item_id']]['unit_price']){
                $message = $this->set_items_messages(array(),$message,'Unit Price Exceeded than Purchase Order<br>');
                $allowed = 0;
              }
            }
            if($this->config->item('Purchase_from_po_qty_exceed_restriction')==1){
              if($row['quantity']>$order_items_data[$row['order_item_id']]['balance_qty']){
                $message = $this->set_items_messages(array(),$message,'Quantity Exceeded than Purchase Order<br>');
                $allowed = 0;
              }
            }
          }else{
            $message = $this->set_items_messages(array(),$message,'Exceeds than Qty in Purchase Order<br>');
            $allowed = 0;
          }
        }
      }


      if($allowed == 1){
        if($file_error==0){
          $result = $this->Purchases->insert_purchase($data);
          $flash_data['status'] = $result['status'];
          $order_error = 0;
          if($result['status']==1){
            $item_data['purchase_id'] = $purchase_data['purchase_id'] = $transaction_data['reference_id'] = $return_data['reference_id'] = $result['insert_id'];
            $transaction_data['reference_type'] = "purchase_bill";
            $transaction_data['tr_type'] = "purchase_bill_transaction";
            $transaction_data['created_date'] = date('Y-m-d H:i:s');
            $transaction_data['created_by'] = $this->session->userdata('user_id');

            if($data['purchase_order_id']!=''){

              // Copy Order Payments to Purchase Payments as Advance
              $order_by = array(array('column'=>"ats.tr_date",'order'=>'asc'),array('column'=>"ats.transaction_id",'order'=>'desc'));
              $order_payments = $this->Account->select_account_transaction("ats.*", array("ats.reference_id" => $data['purchase_order_id'], "ats.reference_type" => 'purchase_order'),'purchase_order','','',$order_by)->result();
              // $purchase_order_advance_paid_amount = $order_payments[0]->tr_amount;


              $order_advance_amount = $this->security->xss_clean($this->input->post('advance_amount'));

              foreach ($order_payments as $key => $value) {
                if($value->tr_amount>0 && $order_advance_amount > 0){
                  $transaction_data['tr_payment_part'] = 0; //Advance Payment
                  if($order_advance_amount<=$value->tr_amount){
                    $order_tr_amount = $value->tr_amount - $order_advance_amount;
                    $bill_tr_amount = $order_advance_amount;
                    $order_advance_amount -= $bill_tr_amount;
                  }
                  else {
                    $order_tr_amount = 0;
                    $bill_tr_amount = $value->tr_amount;
                    $order_advance_amount -= $bill_tr_amount;
                  }
                  if($bill_tr_amount > 0) {
                    $transaction_data['tr_copy_from'] = $value->transaction_id;
                    $transaction_data['tr_amount'] = $bill_tr_amount;
                    $transaction_data['tr_date'] = $value->tr_date;
                    $transaction_data['tr_debit_acc'] = $value->tr_debit_acc;
                    $transaction_data['tr_credit_acc'] = 5;//Purchase Bill
                    $transaction_data['tr_description'] = "Purchase Bill Transaction";
                    $transaction_data['tr_mode'] = $value->tr_mode;
                    $transaction_data['tr_reference_no'] = $value->tr_reference_no;
                    $transaction_data['tr_reference_date'] = $value->tr_reference_date;
                    $transaction_data['tr_remarks'] = $value->tr_remarks;
                    $transaction_result = $this->Account->create_account_transaction($transaction_data);
                    // break;
                  }
                  //update purchase order transaction
                  $data_update['transaction_id'] = $value->transaction_id;
                  $data_update['tr_amount'] = $order_tr_amount;
                  $transaction_Update_result = $this->Account->update_account_transaction($data_update);
                }
              }

              //advance returns
              $advance_return_payments = $this->Account->select_advance_return_transaction("art.*", array("art.reference_id" => $data['purchase_order_id'], "art.reference_type" => 'purchase_order'))->result();
              $supplier_advance = $this->security->xss_clean($this->input->post('advance_amount_supplier'));
              foreach ($advance_return_payments as $key => $value2) {
                if($value2->tr_amount>0 && $supplier_advance > 0){
                  if($supplier_advance<=$value2->tr_amount){
                    $order_tr_amount = $value2->tr_amount - $supplier_advance;
                    $bill_tr_amount2 = $supplier_advance;
                    $supplier_advance -= $bill_tr_amount2;
                  }
                  else{
                    $order_tr_amount = 0;
                    $bill_tr_amount2 = $value2->tr_amount;
                    $supplier_advance -= $bill_tr_amount2;
                  }
                  if($bill_tr_amount2 > 0) {
                    $transaction_data_return['tr_amount'] = $bill_tr_amount2;
                    $transaction_data_return['tr_date'] = $value2->tr_date;
                    $transaction_data_return['supplier_id'] = $value2->supplier_id;
                    $transaction_data_return['reference_type'] = "purchase_bill";//Supplier Payments
                    $transaction_data_return['reference_id'] = $purchase_data['purchase_id'];
                    $transaction_data_return['tr_type'] = "purchase_bill_transaction";
                    $transaction_data_return['created_date'] = date('Y-m-d H:i:s');
                    $transaction_data_return['created_by'] = $this->session->userdata('user_id');
                    $transaction_return_result = $this->Account->create_advance_return_transaction($transaction_data_return);
                  }

                  //update purchase order transaction
                  $data_update_return['tr_id'] = $value2->tr_id;
                  $data_update_return['tr_amount'] = $order_tr_amount;
                  $transaction_Update_result = $this->Account->update_advance_return_transaction($data_update_return);
                }
              }

              // Get Order Data
              $order_details =  $this->Purchase_order->select_purchase_order("purchase_bill_id",array("po.order_id"=>$data['purchase_order_id']));
              if($order_details->num_rows()==1){
                if($order_details->row()->purchase_bill_id==0){
                  $order_data['order_id'] = $data['purchase_order_id'];
                  $order_data['purchase_bill_id'] = $purchase_data['purchase_id'];
                  $this->Purchase_order->update_purchase_order($order_data);
                }
                else{
                  $order_data['order_id'] = $data['purchase_order_id'];
                  $order_data['purchase_bill_id'] = $order_details->row()->purchase_bill_id.','.$purchase_data['purchase_id'];
                  $this->Purchase_order->update_purchase_order($order_data);
                }
                // else{
                //   $order_error=1;
                // }
              }
            }

            //supplier advance return
            $payment_move = $this->input->post('payment_move');
            if($payment_move==1){
              $return_data['tr_amount'] = $this->security->xss_clean($this->input->post('advance_payment_amount'));
              $return_data['created_date'] = date('Y-m-d H:i:s');
              $return_data['supplier_id'] = $data['supplier_id'];//Supplier Head
              $return_data['tr_type'] = "purchase_bill_transaction";
              $return_data['reference_type'] = 'purchase_bill';
              $return_data['tr_date'] =  date('Y-m-d H:i:s');
              $return_data['created_by'] = $this->session->userdata('user_id');
              if($return_data['tr_amount']>0){
                $return_result = $this->Account->create_advance_return_transaction($return_data);
              }
            }

            // Insert  Cart Items
            $items_array=$newArrayitems=array();
            if($this->input->post('item')){
              $items_array = $this->input->post('item');
            }
            $items_array_length = sizeof($items_array);
            // Convert to New Formatted Array
            foreach (array_keys($items_array) as $fieldKey) {
              foreach ($items_array[$fieldKey] as $key=>$value) {
                $newArrayitems[$key][$fieldKey] = $value;
              }
            }

            foreach ($newArrayitems as $row) {
              $item_data['material_id'] = $row['material_id'];
              $item_data['quantity'] = $row['quantity'];
              $item_data['unit_id'] = $row['unit_id'];
              $item_data['total_amount'] = $row['total_amount'];
              $item_data['unit_price'] = $row['unit_price'];
              $item_data['item_code'] = $row['item_code'];

              if($this->config->item('Tax_tax_enabled')==1 && $this->config->item('Tax_purchase_tax_type')=='item_wise' && isset($row['tax_amount'])){
                $item_data['tax_percent'] = $row['tax_percent'];
                $item_data['tax_amount'] = $row['tax_amount'];
              }
              if(isset($row['description'])){
                $item_data['description'] = $row['description'];
              }

              $item_result = $this->Purchases->create_purchase_item($item_data);
            }


            // Insert Payment if Exist
            if($this->input->post('bill_paid_amount')>0) {

              $transaction_data['tr_payment_part'] = 1; //Bill Payment
              $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('bill_paid_amount'));
              $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'] = 5;//Supplier Payments
              $transaction_data['tr_description'] = "Purchase Bill Transaction";
              $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_result = $this->Account->create_account_transaction($transaction_data);

            }

            $other_charges_data = $data;
            $other_charges_data['purchase_id'] = $purchase_data['purchase_id'];
            if($this->input->post('loading_bill_amount')>0){
              $other_charges_data['type'] = 'loading_charge';
              $other_charges_data['bill_date'] = $data['purchase_date'];
              $other_charges_data['bill_total_amount'] = $this->input->post('loading_bill_amount');
              $other_charges_data['cosignee'] = $this->input->post('loading_consignee');
              $other_charges_data['amount'] = $this->input->post('loading_charge');
              $other_charges_data['paid_date'] = date('Y-m-d',strtotime($this->input->post('paid_date_2')));
              $other_charges_data['debit_acc'] = $this->input->post('debit_acc_2');
              $other_charges_data['payment_mode'] = $this->input->post('payment_mode_2');
              $this->add_update_other_charges_bill($other_charges_data);
            }
            if($this->input->post('transportation_bill_amount')>0){
              $other_charges_data['type'] = 'transportation_charge';
              $other_charges_data['bill_date'] = $data['purchase_date'];
              $other_charges_data['bill_total_amount'] = $this->input->post('transportation_bill_amount');
              $other_charges_data['cosignee'] = $this->input->post('transportation_consignee');
              $other_charges_data['amount'] = $this->input->post('transportation_charge');
              $other_charges_data['paid_date'] = date('Y-m-d',strtotime($this->input->post('paid_date_3')));
              $other_charges_data['debit_acc'] = $this->input->post('debit_acc_3');
              $other_charges_data['payment_mode'] = $this->input->post('payment_mode_3');
              $this->add_update_other_charges_bill($other_charges_data);
            }

            if($this->config->item('app_module_vehicle_management')==1 && $this->input->post('vehicle_id') && $this->input->post('vehicle_id')!=''){
              $vehicle_work_slip['vehicle_id'] =$this->security->xss_clean($this->input->post('vehicle_id'));
              $vehicle_work_slip['worked_date'] = $data['purchase_date'];
              $vehicle_work_slip['purchase_bill_id'] = $purchase_data['purchase_id'];
              if($location_data->row()->location_type=='work_site'){
                $vehicle_work_slip['work_slip_type'] = 'inside_work';
                $vehicle_work_slip['vehicle_work_id'] = $location_data->row()->work_id;
                $vehicle_work_slip['project_stage_id'] = $this->projects_management->get_project_stage_id($location_data->row()->work_id);
              }else{
                $vehicle_work_slip['work_slip_type'] = 'inside_warehouse';
                $vehicle_work_slip['vehicle_location_id'] = $location_data->row()->location_id;
              }
              $vehicle_work_slip['duration_type'] = $this->security->xss_clean($this->input->post('vehicle_work_duration_type'));
              $vehicle_work_slip['worked_duration'] = $this->security->xss_clean($this->input->post('vehicle_worked_duration'));
              $vehicle_work_slip['basic_charge'] = $this->security->xss_clean($this->input->post('vehicle_basic_charge'));
              if($this->input->post('vehicle_driver')){
                $vehicle_work_slip['driver_id'] = $this->security->xss_clean($this->input->post('vehicle_driver'));
                $vehicle_work_slip['start_time'] = date('H:i:s',strtotime($this->input->post('vehicle_start_time')));
                $vehicle_work_slip['end_time'] = date('H:i:s',strtotime($this->input->post('vehicle_end_time')));
                $vehicle_work_slip['start_km'] = $this->security->xss_clean($this->input->post('vehicle_start_km'));
                $vehicle_work_slip['end_km'] = $this->security->xss_clean($this->input->post('vehicle_end_km'));
                $vehicle_work_slip['total_km'] = $this->security->xss_clean($this->input->post('vehicle_total_km'));
                $vehicle_work_slip['driver_bata'] = $this->security->xss_clean($this->input->post('driver_bata'));
                $vehicle_work_slip['driver_bata_include'] = $this->security->xss_clean($this->input->post('driver_bata_include'));
              }
              $vehicle_work_slip['total_payable_amount'] = $this->security->xss_clean($this->input->post('vehicle_total_charge'));
              $vehicle_work_slip['total_paid'] = 0;
              $vehicle_work_slip['balance'] = $vehicle_work_slip['total_payable_amount'];
              if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
                $vehicle_work_slip['entry_approval_status'] = 0;
              }
              $vehicle_work_slip['created_date'] = date('Y-m-d H:i:s');
              $vehicle_work_slip['created_by'] = $this->session->userdata('user_id');
              $work_slips_result = $this->Vehicle_work_slips->create_vehicle_work_slip($vehicle_work_slip);

            }

            $this->bills_management->calculate_purchase_bill_total($purchase_data['purchase_id']);
            $this->stock_management->update_stock_register($purchase_data['purchase_id']);

            if($this->config->item('BOQ_dpr_template')==2){
              $this->boq_management->auto_correct_material_consumption_balance($location_data->row()->work_id,$data['purchase_date']);
            }
            $flash_data['flashdata_msg'] = 'Purchase Bill Saved Successfully!.';
            $flash_data['flashdata_type'] = 'success';
            $flash_data['alert_type'] = 'success';
            $flash_data['flashdata_title'] = 'Success !';
            $flash_data['purchase_id'] = $purchase_data['purchase_id'];

            $purchase_data_2 = $this->Purchases->select_purchase("sl.work_id,sl.location_type",array("p.purchase_id"=>$purchase_data['purchase_id']),'all','','','all')->row();
            $flash_data['location_type']=$purchase_data_2->location_type;
            $flash_data['work_id']=$purchase_data_2->work_id;
          }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{
        if(isset($message) && $message!=''){
          $flash_data['flashdata_msg'] = $message;
        }else{
          $flash_data['flashdata_msg'] = 'No BOQ Found or Some Errors Occurred With BOQ';
        }
        $flash_data['flashdata_type'] = 'warning';
        $flash_data['alert_type'] = 'warning';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else{
      $flash_data['status'] = 2;
      $flash_data['flashdata_msg'] = 'Sorry.. Provided Bill No is Already Exist with Same Supplier!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Bill No Exist !!';
    }
    // }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);  // send data as json format
  }
  public function update(){
    $data['purchase_id'] = $this->security->xss_clean($this->input->post('purchase_id'));
    $data['location_id'] = $this->security->xss_clean($this->input->post('location'));
    $data['supplier_id'] = $this->security->xss_clean($this->input->post('supplier'));
    $data['purchase_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('purchase_date'))));
    $data['bill_invoice_no'] = $this->security->xss_clean($this->input->post('invoice_no'));
    $count = 0;
    if($data['bill_invoice_no']!='' && $this->config->item('Purchase_disable_bill_no_duplication_check')==0){
      $count = $this->Purchases->select_purchase("p.purchase_id", array("p.purchase_id !=" =>$data['purchase_id'],"p.bill_invoice_no" =>$data['bill_invoice_no'],"p.supplier_id" =>$data['supplier_id']),'all','','','all')->num_rows();
    }
    $data['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data['vehicle_no'] = $this->security->xss_clean($this->input->post('vehicle_no'));
    $data['updated_date'] = date('Y-m-d H:i:s');
    $data['updated_by'] = $this->session->userdata('user_id');
    $data['bill_discount_amount'] = $this->security->xss_clean($this->input->post('bill_discount_amount'));
    $data['bill_commission_amount'] = $this->security->xss_clean($this->input->post('bill_commission'));
    $data['bill_tax_amount'] = $this->security->xss_clean($this->input->post('bill_tax_amount'));
    $data['bill_tds_amount'] = $this->security->xss_clean($this->input->post('bill_tds_amount'));
    $data['bill_other_amount'] = $this->security->xss_clean($this->input->post('bill_other_amount'));
    $data['bill_round_amount'] = $this->security->xss_clean($this->input->post('bill_round_amount'));
    $data['bill_total_amount'] = $this->security->xss_clean($this->input->post('bill_total_amount'));
    $data['bill_payable_amount'] = $this->security->xss_clean($this->input->post('bill_payable_amount'));
    if($this->config->item('Tax_tax_enabled')==1 && $this->config->item('Tax_purchase_tax_type')=='item_wise' && $this->input->post('tax_percent')){
      $data['bill_tax_percent'] = $this->security->xss_clean($this->input->post('tax_percent'));
    }
    //      File Validations
    $file_error = 0;
    if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']["size"] > 0) {
      //      File Upload
      $config['upload_path']   = 'uploads/bills/';
      $config['allowed_types'] = 'jpg|jpeg|png|pdf|doc|docx|xls|xl';
      $config['max_size']      = 3000;
      // $config['max_width']     = 1980;
      // $config['max_height']    = 1080;
      $config['encrypt_name']    = TRUE;
      // $config['file_name'] = date('YmdHis');
      $this->load->library('upload', $config);
      if (!$this->upload->do_upload('uploaded_file')) {
        $error = array('error' => $this->upload->display_errors());
        $file_error = 1;
        $flash_data['flashdata_msg'] = $error['error'];
        $flash_data['flashdata_type'] = "warning";
        $flash_data['flashdata_title'] = "Uploaded File Error";
        $flash_data['status'] = 2;
      }else {
        $file_data = $this->upload->data();
        $data['bill_attachment'] = $file_data['file_name'];
      }
    }else{
      // Check Existing Attachment Deleted
      if($this->input->post('attachment_delete_status')==1){
        $data['bill_attachment'] = "";
      }
    }
    if($file_error==0){
      if($count==0){
        $result = $this->Purchases->update_purchase($data);
        $flash_data['status'] = $result;
        $order_error = 0;
        if($result==1){
          $purchase_data['purchase_id'] = $payment_data['purchase_id'] = $data['purchase_id'];

          // Insert/Update Cart Items
          $items_array=$newArrayitems=array();
          if($this->input->post('item')){
            $items_array = $this->input->post('item');
          }
          $items_array_length = sizeof($items_array);
          // Convert to New Formatted Array
          foreach (array_keys($items_array) as $fieldKey) {
            foreach ($items_array[$fieldKey] as $key=>$value) {
              $newArrayitems[$key][$fieldKey] = $value;
            }
          }
          foreach ($newArrayitems as $row) {
            $item_data=array();
            $item_data['material_id'] = $row['material_id'];
            $item_data['quantity'] = $row['quantity'];
            $item_data['unit_id'] = $row['unit_id'];
            $item_data['total_amount'] = $row['total_amount'];
            $item_data['unit_price'] = $row['unit_price'];
            $item_data['item_code'] = $row['item_code'];
            if($this->config->item('Tax_tax_enabled')==1 && $this->config->item('Tax_purchase_tax_type')=='item_wise' && isset($row['tax_amount'])){
              $item_data['tax_percent'] = $row['tax_percent'];
              $item_data['tax_amount'] = $row['tax_amount'];
            }
            if(isset($row['description'])){
              $item_data['description'] = $row['description'];
            }
            if(isset($row['item_id']) && $row['item_id']!=''){
              // Update Existing Data
              $item_data['item_id'] = $row['item_id'];
              $item_result =  $this->Purchases->update_purchase_item($item_data);
            }else{
              // Create New Data
              $item_data['purchase_id'] =  $data['purchase_id'];
              $item_result =  $this->Purchases->create_purchase_item($item_data);
            }
          }

          // Check Items Deleted
          $deleted_items = $this->security->xss_clean($this->input->post('deleted_items'));
          if($deleted_items!=''){
            $items = explode(',',$deleted_items);
            foreach ($items as $key => $value) {
              $item_data=array();
              $item_data['delete_status'] = 1;
              $item_data['item_id'] = $value;
              $this->Purchases->update_purchase_item($item_data);
            }
          }

          $other_charges_data = $data;
          $other_charges_data['purchase_id'] = $purchase_data['purchase_id'];
          if($this->input->post('loading_bill_amount')>0){
            $other_charges_data['type'] = 'loading_charge';
            $other_charges_data['bill_date'] = $data['purchase_date'];
            $other_charges_data['bill_total_amount'] = $this->input->post('loading_bill_amount');
            $other_charges_data['cosignee'] = $this->input->post('loading_consignee');
            $other_charges_data['amount'] = $this->input->post('loading_charge');
            $other_charges_data['paid_date'] = date('Y-m-d',strtotime($this->input->post('paid_date_2')));
            $other_charges_data['debit_acc'] = $this->input->post('debit_acc_2');
            $other_charges_data['payment_mode'] = $this->input->post('payment_mode_2');
            $this->add_update_other_charges_bill($other_charges_data);
          }
          if($this->input->post('transportation_bill_amount')>0){
            $other_charges_data['type'] = 'transportation_charge';
            $other_charges_data['bill_date'] = $data['purchase_date'];
            $other_charges_data['bill_total_amount'] = $this->input->post('transportation_bill_amount');
            $other_charges_data['cosignee'] = $this->input->post('transportation_consignee');
            $other_charges_data['amount'] = $this->input->post('transportation_charge');
            $other_charges_data['paid_date'] = date('Y-m-d',strtotime($this->input->post('paid_date_3')));
            $other_charges_data['debit_acc'] = $this->input->post('debit_acc_3');
            $other_charges_data['payment_mode'] = $this->input->post('payment_mode_3');
            $this->add_update_other_charges_bill($other_charges_data);
          }

          $this->bills_management->calculate_purchase_bill_total($purchase_data['purchase_id']);
          $this->stock_management->update_stock_register($purchase_data['purchase_id']);

          $location_data = $this->Stock->select_stock_locations("sl.*",array("location_id"=>$data['location_id']));
          if($this->config->item('BOQ_dpr_template')==2){
            $this->boq_management->auto_correct_material_consumption_balance($location_data->row()->work_id);
          }

          $flash_data['flashdata_msg'] = 'Purchase Bill Details Updated Successfully!.';
          $flash_data['flashdata_type'] = 'success';
          $flash_data['alert_type'] = 'success';
          $flash_data['flashdata_title'] = 'Success !';
          $flash_data['purchase_id'] = $purchase_data['purchase_id'];

          $purchase_data_2 = $this->Purchases->select_purchase("sl.work_id,sl.location_type",array("p.purchase_id"=>$purchase_data['purchase_id']),'all','','','all')->row();
          $flash_data['location_type']=$purchase_data_2->location_type;
          $flash_data['work_id']=$purchase_data_2->work_id;
        }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.. Provided Bill No is Already Exist with Same Supplier!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Bill No Exist !!';
      }
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);  // send data as json format
  }

  public function add_update_other_charges_bill($data){
    $purchase_data = $this->Purchases->select_purchase("sl.*,p.project_stage_id",array("purchase_id"=>$data['purchase_id']),'all','','','all');
    if($purchase_data->num_rows()==1){
      $purchase_data = $purchase_data->row();
      if($purchase_data->location_type=='work_site'){
        $bill_data['work_id'] = $purchase_data->work_id;
        $transaction_data['tr_project_stage_id'] = $bill_data['project_stage_id'] = $purchase_data->project_stage_id;
      }
      $bill_data['bill_type'] = 'expense';
      if($data['type']=='transportation_charge'){
        $bill_data['bill_credit_ac'] = 20; //Expense Account Head - Transportation
        $bill_data['bill_consignee_name'] = $data['cosignee'];
        $bill_data['bill_description'] = 'Transportation Charge For Purchase Bill #'.$data['purchase_id'];
      }else{
        $bill_data['bill_credit_ac'] = 19; //Expense Account Head - Loading
        $bill_data['bill_consignee_name'] = $data['cosignee'];
        $bill_data['bill_description'] = 'Loading/Unloading Charge For Purchase Bill #'.$data['purchase_id'];
      }
      $bill_data['purchase_id'] = $data['purchase_id'];
      $bill_data['bill_date'] = $data['bill_date'];
      $bill_data['bill_no'] = $data['bill_invoice_no'];
      $bill_data['bill_gross_amount'] = $data['bill_total_amount'];
      $bill_data['bill_payable_amount'] = $bill_data['bill_amount'] = $bill_data['bill_gross_amount'];

      // Check Bill Already Created
      $bill_select_data = $this->Bills->select_bills("b.bill_id",array("b.purchase_id"=>$bill_data['purchase_id'],"b.bill_credit_ac"=>$bill_data['bill_credit_ac']),'expense_bill');
      if($bill_select_data->num_rows()==0){
        $bill_data['created_date'] = date('Y-m-d H:i:s');
        $bill_data['created_by'] = $this->session->userdata('user_id');
        if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
          $bill_data['entry_approval_status'] = 0;
        }
        if($this->config->item('User_enable_data_entry_approval_2_level')==1 && $this->session->userdata('user_role_id')>2){
          $bill_data['entry_approval_status_2'] = 0;
        }
        $bill_result =  $this->Bills->create_bills($bill_data);
        $bill_result_status = $bill_result['status'];
        $bill_id = $bill_result['insert_id'];
      }else{
        $bill_data['updated_date'] = date('Y-m-d H:i:s');
        $bill_data['updated_by'] = $this->session->userdata('user_id');
        $bill_data['bill_id'] = $bill_id = $bill_select_data->row()->bill_id;
        $bill_result =  $this->Bills->update_bills($bill_data);
        $bill_result_status = $bill_result;
      }

      if ($bill_result_status == 1) {
        $transaction_data['reference_id'] = $bill_id;
        $transaction_data['reference_type'] = $bill_data['bill_type']."_bill";
        $transaction_data['tr_type'] = $bill_data['bill_type']."_bill_transaction";
        if(isset($bill_data['bill_date'])){
          $transaction_data['tr_date'] = $bill_data['bill_date'];
        }
        if(isset($data['debit_acc'])){
          $transaction_data['tr_debit_acc'] = $data['debit_acc'];
        }
        $transaction_data['tr_credit_acc'] = $bill_data['bill_credit_ac'];
        $transaction_data['tr_description'] = ucwords($bill_data['bill_type'])." Bill Transaction";
        $transaction_data['tr_amount'] = $data['amount'];
        if(isset($data['payment_mode'])){
          $transaction_data['tr_mode'] = $data['payment_mode'];
        }
        $transaction_select_data = $this->Account->select_account_transaction("ats.transaction_id",array("b.bill_id" => $bill_id,"ats.tr_type" => 'expense_bill_transaction',"ats.reference_type" => 'expense_bill'),'expense_bill');
        if($transaction_select_data->num_rows()==0){
          $transaction_data['created_date'] = date('Y-m-d H:i:s');
          $transaction_data['created_by'] = $this->session->userdata('user_id');
          $transaction_result =  $this->Account->create_account_transaction($transaction_data);
        }else{
          $transaction_data['transaction_id'] = $transaction_select_data->row()->transaction_id;
          $transaction_data['updated_date'] = date('Y-m-d H:i:s');
          $transaction_data['updated_by'] = $this->session->userdata('user_id');
          $transaction_result =  $this->Account->update_account_transaction($transaction_data);
        }

      }
      // Calculate & Update Bill Total
      $this->bills_management->calculate_bill_total($bill_id);
    }

  }

  public function select_purchases($page_data_type=''){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $total_amount=$total_tax_amount=$total_amount1=$total_amount2=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(p.purchase_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(p.purchase_date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!=''){
      $data["p.purchase_date >="]= date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!=''){
      $data["p.purchase_date <="]= date('Y-m-d', strtotime($_POST['end_date']));
    }
    if(isset($_POST['supplier']) && $_POST['supplier']!='' && $_POST['supplier']!='all'){
      $data['s.supplier_id'] = $_POST['supplier'];
    }
    if(isset($_POST['location_id']) && $_POST['location_id']!='' && $_POST['location_id']!='all'){
      $data['p.location_id'] = $_POST['location_id'];
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['sl.work_id'] = $_POST['work'];
    }
    if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
      $this->db->where_in('sl.work_id',explode(',',$_POST['work_ids']));
    }
    if(isset($_POST['stage_id']) && $_POST['stage_id']!='' && $_POST['stage_id']!='all'){
      $data['p.project_stage_id'] = $_POST['stage_id'];
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['p.created_by'] = $_POST['user_id'];
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!='' && $_POST['start_date']!='all'){
      $data['p.purchase_date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!='' && $_POST['end_date']!='all'){
      $data['p.purchase_date <='] = date('Y-m-d', strtotime($_POST['end_date']));
    }
    if(isset($_POST['order_id']) && $_POST['order_id']!='' && $_POST['order_id']!='all'){
      $data['p.purchase_order_id'] = $_POST['order_id'];
    }
    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(isset($_POST['payment_status']) && $_POST['payment_status']!='' && $_POST['payment_status']!='all'){
      $data['p.payment_status'] = $_POST['payment_status'];
    }
    if($this->config->item('user_data_access_view_all')!=1){
      $data['p.created_by'] = $this->session->userdata('user_id');
    }
    $entry_approval = $entry_approval_2 = 1;
    if($this->config->item('User_enable_data_entry_approval')==1){//webapp users approval
      $entry_approval = $entry_approval_2 = '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'];
      }
    }
    if($page_data_type=='approval_entries_2_level'){
      $entry_approval_2 = 'all';
      $data['u.user_role >'] =2;
      $data['p.entry_approval_status'] =1;
      if(isset($_POST['approval_status']) && $_POST['approval_status']!='' && $_POST['approval_status']!='all'){
        $entry_approval_2 = $_POST['approval_status'];
      }
    }
    $result = $this->Purchases->select_purchase("p.*,u.user_alias,s.supplier_id,s.supplier_name,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id,u.user_role as created_user_role_id",$data,$entry_approval,'','',$entry_approval_2);
    $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):
      $id=$row->work_id;
      $bill_id_column= 17;//Column Where Bill ID Exist
      $btn_edit = $btn_delete = $btn_add_payment='';
      $btn_view='<a style="margin-left: 5px;margin-right: 5px"  href="'.base_url().'purchases/profile/'.$row->purchase_id.'" class="btn btn-primary m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
      <i class="la la-eye"></i>
      </a>';
      $location_name = $row->location_name;
      if($row->location_type=='work_site'){
        $location_name = '<a href="' . base_url() . 'work/profile/' . $row->location_work_id . '">' . $row->location_name . '<br/>[Work Site]</a>';
      }elseif($row->location_type=='ware_house'){
        $location_name = '<a href="' . base_url() . 'stock/locations/profile/' . $row->location_id . '">' . $row->location_name . '<br/>[Warehouse]</a>';
      }
      if($row->sales_invoice_id==0 && ($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager' || $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"  href="' . base_url() . 'purchases/edit/' . $row->purchase_id . '" 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>';
        if($row->purchase_order_id==0 || ($row->purchase_order_id!=0 && $row->total_paid==0) || ($row->purchase_order_id!=0 && $this->config->item('Purchase_enable_delete_bill_generated_from_po')==1)){
          // Delete Option Disabled For Bill Created from Order
          $btn_delete='<a style="margin-left: 5px;margin-right: 5px" data-bill-type="purchase_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($row->payment_status==1){
        $payment_status="<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Paid</span>";
      }else{
        if($row->total_paid>0){
          $payment_status="<span class='m-badge m-badge--info m-badge--wide'><i class='fa fa-times-circle'></i> Partially Paid</span>";
        }else{
          $payment_status="<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Not Paid</span>";
        }
        // if($this->session->userdata('user_role')=='admin' || ($this->session->userdata('user_role')=='supervisor' && $this->session->userdata('user_id')==$row->created_by)) {

        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" data-bill-type="purchase_bill" data-bill-id-column="'.$bill_id_column.'" id="btn_add_bill_payment" data-toggle="modal"  href="#bill_payment_add_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>';
        }

        // }
      }

      $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){
        if($this->config->item('User_enable_data_entry_approval_2_level')==0 || ($this->config->item('User_enable_data_entry_approval_2_level')==1 && $row->entry_approval_status_2 == 0)){
          $btn_approve = '<a style="margin-left: 5px;margin-right: 5px" data-type="purchase_bill" data-approval-status="'.$row->entry_approval_status.'" data-id="'.$row->purchase_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($this->config->item('User_enable_data_entry_approval_2_level')==1 && $this->session->userdata('user_role')=='admin' && $page_data_type=='approval_entries_2_level'){
        $btn_approve = '<a style="margin-left: 5px;margin-right: 5px" data-type="purchase_bill" data-approval-status="'.$row->entry_approval_status_2.'" data-id="'.$row->purchase_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){
        $level='';
        if($this->config->item('User_enable_data_entry_approval_2_level')==1){
          $level='1st Level ';
        }
        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> ".$level."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> ".$level."Rejected</span>";
        }else{
          $entry_approval_status="<br/><span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> ".$level."Pending</span>";
        }
        if($this->config->item('User_enable_data_entry_approval_2_level')==1 && $row->entry_approval_status == 1){
          if ($row->entry_approval_status_2 == 1) {
            $entry_approval_status .= "<br/><span style='margin-top:5px' class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> 2nd Level Approved</span>";
          } elseif ($row->entry_approval_status_2 == 2) {
            $entry_approval_status .= "<br/><span style='margin-top:5px' class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> 2nd Level Rejected</span>";
          } else {
            $entry_approval_status .= "<br/><span style='margin-top:5px' class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> 2nd Level Pending</span>";
          }
        }
      }

      $sl_no++;
      $other_charges_list='';
      if($row->other_charges!=''){
        $other_charges = unserialize($row->other_charges);
        $other_charges_list.='<ul style="padding: .75rem;margin-bottom: 0">';
        foreach($other_charges as $key3=>$value3){
          $other_charges_list.='<li> '.$value3['type'].': <strong>'.$this->config->item('Currency_currency_format')." ".$value3['amount'].'</strong></li>';
        }
        $other_charges_list.='</ul>';
      }

      $approval_pending_payments = '';
      $pending_amount = 0;
      // Check For Approval Pending Payments
      if($this->config->item('Mobile_App_enable_data_entry_approval')==1 || $this->config->item('User_enable_data_entry_approval')==1){
        $pending_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $row->purchase_id, "ats.reference_type" => 'purchase_bill'),'purchase_bill','','','','0','all','all')->row()->total_paid_amount;
        if($pending_amount>0){
          $approval_pending_payments = '<br/><strong>Approval Pending Payment : '.$pending_amount.'</strong>';
        }
      }

      $array[$j][]=$sl_no;
      $array[$j][]='<a href="' . base_url() . 'purchases/profile/' . $row->purchase_id . '">#' . $row->purchase_id . '</a>';
      $array[$j][]=date('d-m-Y',strtotime($row->purchase_date));
      $array[$j][]=$row->bill_invoice_no;
      $array[$j][]='<a href="' . base_url() . 'supplier/profile/' . $row->supplier_id . '">' . $row->supplier_name . '</a>';
      $array[$j][]=$location_name;
      $array[$j][]=$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($row->bill_total_amount,$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$row->bill_tax_percent;
      $array[$j][]=$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($row->bill_tax_amount,$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($row->bill_payable_amount,$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($row->total_paid,$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($row->balance_amount,$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$payment_status.$approval_pending_payments;
      $array[$j][]=$other_charges_list;
      $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Bill No : '.$row->bill_invoice_no."</li><li>Vehicle No : ".$row->vehicle_no."</li><li>Remarks : ".$row->remarks."</li>";
      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>".$entry_approval_status;
      }else{
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->user_alias.'</li>'.$entry_approval_status;
      }
      $array[$j][]=$btn_add_payment.$btn_view.$btn_edit.$btn_delete.$btn_approve;
      $array[$j][]=$row->purchase_id;
      $array[$j][]=$row->entry_approval_status;
      $array[$j][]=$row->entry_approval_status_2;

      $total_amount+=$row->bill_payable_amount;
      $total_tax_amount += $row->bill_tax_amount;
      $total_amount1+=$row->total_paid;
      $total_amount2+=$row->balance_amount;

      $j++;
    endforeach;

    if($result->num_rows()>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][] = '';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][] = '';
      $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_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_amount1,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_amount2,$this->config->item('Currency_currency_shortname'))."</strong>";
      $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_purchased_items_list(){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $total_amount=$total_qty=$total_without_tax=$total_tax_amount=$total_tax1_amount=$total_tax2_amount=$total_tax3_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(p.purchase_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(p.purchase_date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['material']) && $_POST['material']!='' && $_POST['material']!='all'){
      $data['m.material_id'] = $_POST['material'];
    }
    if(isset($_POST['material_category']) && $_POST['material_category']!='' && $_POST['material_category']!='all'){
      $data['m.category'] = $_POST['material_category'];
    }
    if(isset($_POST['supplier']) && $_POST['supplier']!='' && $_POST['supplier']!='all'){
      $data['s.supplier_id'] = $_POST['supplier'];
    }
    if(isset($_POST['supplier_category']) && $_POST['supplier_category']!='' && $_POST['supplier_category']!='all'){
      $data['s.supplier_category'] = $_POST['supplier_category'];
    }
    if(isset($_POST['unit_id']) && $_POST['unit_id']!='' && $_POST['unit_id']!='all'){
      $data['pi.unit_id'] = $_POST['unit_id'];
    }

    if(isset($_POST['location_id']) && $_POST['location_id']!='' && $_POST['location_id']!='all'){
      $data['p.location_id'] = $_POST['location_id'];
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['sl.work_id'] = $_POST['work'];
    }
    if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
      $this->db->where_in('sl.work_id',explode(',',$_POST['work_ids']));
    }
    if(isset($_POST['stage_id']) && $_POST['stage_id']!='' && $_POST['stage_id']!='all'){
      $data['p.project_stage_id'] = $_POST['stage_id'];
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['p.created_by'] = $_POST['user_id'];
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!='' && $_POST['start_date']!='all'){
      $data['p.purchase_date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!='' && $_POST['end_date']!='all'){
      $data['p.purchase_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(isset($_POST['unit_price']) && $_POST['unit_price']!='' && $_POST['unit_price']!='all'){
      $this->db->where('(pi.total_amount/pi.quantity) like "%'.$_POST['unit_price'].'%"');
    }
    if($this->config->item('user_data_access_view_all')!=1){
      $data['p.created_by'] = $this->session->userdata('user_id');
    }
    $result = $this->Purchases->select_purchase_items("pi.*,p.vehicle_no,p.remarks,s.supplier_id,s.supplier_name,p.purchase_date,m.material_name,mu.unit_name,u.user_alias,p.created_date,p.location_id,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id,tt.tax_percentage,tt.tax1_percent,tt.tax2_percent,tt.tax3_percent",$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):

      if($row->item_type=="from_warehouse"){
        $item_type="From Ware House";
      }else{
        $item_type="New Purchase";
      }

      $location_name = $row->location_name;
      if($row->location_type=='work_site'){
        $location_name = '<a href="' . base_url() . 'work/profile/' . $row->location_work_id . '">' . $row->location_name . '<br/>[Work Site]</a>';
      }elseif($row->location_type=='ware_house'){
        $location_name = '<a href="' . base_url() . 'stock/locations/profile/' . $row->location_id . '">' . $row->location_name . '<br/>[Warehouse]</a>';
      }

      $row->tax1_amount = round($row->unit_price*$row->quantity*$row->tax1_percent/100,$this->config->item('Currency_amount_decimals_2'));
      $row->tax2_amount = round($row->unit_price*$row->quantity*$row->tax2_percent/100,$this->config->item('Currency_amount_decimals_2'));
      $row->tax3_amount = round($row->unit_price*$row->quantity*$row->tax3_percent/100,$this->config->item('Currency_amount_decimals_2'));

      $btn_view='<a style="margin-left: 5px;margin-right: 5px"  href="'.base_url().'purchases/profile/'.$row->purchase_id.'" class="btn btn-primary m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
      <i class="la la-eye"></i>
      </a>';
      $sl_no++;
      $array[$j][]=$sl_no;
      $array[$j][]='<a href="' . base_url() . 'purchases/profile/' . $row->purchase_id . '">#' . $row->purchase_id . '</a>';
      $array[$j][]=date('d-m-Y',strtotime($row->purchase_date));
      $array[$j][]='<a href="' . base_url() . 'supplier/profile/' . $row->supplier_id . '">' . $row->supplier_name . '</a>';
      $array[$j][]=$row->material_name;
      $array[$j][]=$row->item_code;
      $array[$j][]=$row->quantity;
      $array[$j][]=$row->unit_name;
      $array[$j][]=$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($row->unit_price,$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$row->tax_percentage."%";
      $array[$j][]=number_format($row->tax_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=$row->tax1_percent;
      $array[$j][]=number_format($row->tax1_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=$row->tax2_percent;
      $array[$j][]=number_format($row->tax2_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=$row->tax3_percent;
      $array[$j][]=number_format($row->tax3_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency(($row->total_amount-$row->tax_amount),$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($row->total_amount,$this->config->item('Currency_currency_shortname'));
      $array[$j][]=$row->description;
      $array[$j][]=$row->remarks;
      $array[$j][]=$row->user_alias;
      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][] = $location_name;
      $array[$j][] = $row->vehicle_no;
      $array[$j][]=$btn_view;

      $total_amount=$total_amount+$row->total_amount;
      $total_qty+=$row->quantity;
      $total_without_tax+=$row->total_amount-$row->tax_amount;
      $total_tax_amount+=$row->tax_amount;
      $total_tax1_amount+=$row->tax1_amount;
      $total_tax2_amount+=$row->tax2_amount;
      $total_tax3_amount+=$row->tax3_amount;

      $j++;
    endforeach;
    if($result->num_rows()>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]="<strong>".$total_qty."</strong>";
      $array[$j][]='';
      $array[$j][]="";
      $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][]='';
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_tax1_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]='';
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_tax2_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]='';
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_tax3_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_without_tax,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $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_purchase_total()
  {
    $data['purchase_id'] = $this->security->xss_clean($this->input->post('purchase_id'));
    $this->bills_management->calculate_purchase_bill_total($data['purchase_id']);
    //       Get Purchase Data
    $purchase_data  = $this->Purchases->select_purchase("",array("p.purchase_id"=>$data['purchase_id'],"p.delete_status"=>0));
    if($purchase_data->num_rows()==1) {
      $purchase_data = $purchase_data->row();
      $json_data['bill_discount_amount'] = $purchase_data->bill_discount_amount;
      $json_data['bill_total_amount'] = $purchase_data->bill_total_amount;
      $json_data['bill_grand_total'] = $purchase_data->bill_payable_amount;
      $json_data['balance_amount'] = $purchase_data->balance_amount;
      $json_data['bill_commission_amount'] = $purchase_data->bill_commission_amount;
      $json_data['advance_amount'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $data['purchase_id'], "ats.reference_type" => 'purchase_bill', "ats.tr_payment_part" => 0),'purchase_bill')->row()->total_paid_amount;
      $json_data['down_payment'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $data['purchase_id'], "ats.reference_type" => 'purchase_bill', "ats.tr_payment_part" => 2),'purchase_bill')->row()->total_paid_amount;
      $json_data['bill_payment'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $data['purchase_id'], "ats.reference_type" => 'purchase_bill', "ats.tr_payment_part !=" => 0),'purchase_bill')->row()->total_paid_amount;
      $json_data['total_paid'] = $purchase_data->total_paid;
      $json_data['status']=1;

    }else{
      $json_data['status']=0;
    }
    echo json_encode($json_data);
  }


  // BOQ Intergration

  public function select_boq_task_item_for_purchase($project,$location,$material,$unit,$type='')
  {
    $array = array();
    $data2['b.project_id'] = $data['b.project_id'] = $project;
    $data3['sr.location_id'] = $location;
    $data3['m.material_id'] = $data['bti.material_id'] = $material;
    $data2['b.boq_approval_status'] = $data['b.boq_approval_status'] = 1;
    $data['bti.unit'] = $data3['sr.unit'] = $unit;

    $array['boq_count'] = $this->Boq->select_boq('b.boq_id',$data2)->num_rows();
    $column = 'b.boq_id,b.boq_name,b.total_est_amount,COALESCE(SUM(bti.total_amount),0) as bti_total_amount,bti.unit_rate as bti_unit_rate,COALESCE(SUM(bti.qnty),0) as bti_qnty,bti.unit as bti_unit';

    $array['count'] = $array['qnty'] = $array['unit_rate'] = $array['total_amount'] =  $array['unit_rate'] = 0;

    $result = $this->Boq->select_task_items($column,$data,'','','','bti.boq_task_id');
    $result_array = $result->result();

    $column2 = "COALESCE(SUM(sr.total_purchased_qty),0) as total_purchased_qty,COALESCE(SUM(sr.total_transferred_in_qty),0) as total_transferred_in_qty,COALESCE(SUM(sr.total_transferred_out_qty),0) as total_transferred_out_qty,COALESCE(total_balance_qty*unit_price) as total_price";


    // $purchase_data = $this->Purchases->select_purchase_items($column2, $data3,'','','','p.purchase_id')->row();

    $stock_data = $this->Stock->select_stock_register($column2, $data3,'sr.stock_id')->row();

    if(isset($stock_data)){
      $array['qnty'] = -($stock_data->total_purchased_qty+$stock_data->total_transferred_in_qty-$stock_data->total_transferred_out_qty);
      $array['total_amount'] = -$stock_data->total_price;
    }
    else{
      $array['qnty'] =  $array['total_amount'] = 0;
    }


    foreach ($result_array as $key => $value) {
      $array['qnty'] += $value->bti_qnty;
      $unit_rates_array[] = $value->bti_unit_rate;
    }
    if(isset($unit_rates_array) && $unit_rates_array!=''){
      $array['unit_rate'] = min($unit_rates_array);
      $array['total_amount'] = $array['unit_rate']*$array['qnty'];

    }
    $array['count'] = sizeof($result_array);

    if($type=='purchase'){
      return $array;
    }else{
      echo json_encode($array);
    }
  }

  public function set_items_messages($array,$message,$msg)
  {
    $items2 = '';
    foreach (array_keys($array,0) as $value) {
      $items2 .= ($value+1).',' ;
    }
    $items2 = substr(trim($items2), 0, -1);
    $message .= 'Items '.$items2.' '.$msg;
    return $message;
  }
  public function create_return()
  {
    $stock_slnos = $this->input->post('stock_slnos');

    $stock_cons_data = $this->Purchases->select_purchase_return("MAX(return_group_id) as last_group_id");
    if ($stock_cons_data->num_rows() == 1) {
      $data['return_group_id'] = ($stock_cons_data->row()->last_group_id) + 1;
    } else {
      $data['return_group_id'] = 1;
    }

    $data['return_date'] = date('Y-m-d', strtotime($this->input->post('returned_date')));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');
    // $data['remarks'] = "";
    $count = $this->security->xss_clean($this->input->post('count'));
    $work_id = '';
    foreach ($stock_slnos as $key22 => $i) {
      $stock_ids = explode(',', $this->security->xss_clean($this->input->post('stock_ids_' . $i)));
      $remaining_qty = $qty = $this->security->xss_clean($this->input->post('qty_' . $i));
      if ($qty > 0) {
        foreach ($stock_ids as $key => $value) {
          $stock_register = $this->Stock->select_stock_register("stock_id,total_balance_qty,purchase_supplier_id,sl.work_id", array("sr.stock_id" => $value));
          if ($stock_register->num_rows() == 1 && $stock_register->row()->total_balance_qty > 0 && $remaining_qty > 0) {
            $available_stock_item_qty = $stock_register->row()->total_balance_qty;
            if ($remaining_qty > $available_stock_item_qty) {
              $data['returned_qty']  = $available_stock_item_qty;
            } else {
              $data['returned_qty']  = $remaining_qty;
            }

            $remaining_qty = $remaining_qty - $data['returned_qty'];
            $data['unit_price'] = $this->security->xss_clean($this->input->post('rate_' . $i));
            $data['tax_percent'] = $this->security->xss_clean($this->input->post('tax_percent_' . $i));
            $data['stock_id'] = $value;
            $data['supplier_id'] = $stock_register->row()->purchase_supplier_id;
            // Update Stock Consumption
            $result = $this->Purchases->insert_purchase_return($data);
            //  Update Stock Register
            $result2 = $this->stock_management->calculate_stock_balance($data['stock_id']);
            $work_id = $stock_register->row()->work_id;
          }
        }
      }
    }
    if (isset($result) && $result['status'] == 1) {
      // Insert Amount As Supplier Advance

      $transaction_data['tr_date'] = $data['return_date'];
      $transaction_data['tr_debit_acc'] = 27;
      $transaction_data['tr_mode'] = 'CASH';
      $transaction_data['tr_reference_no'] = $data['return_group_id'];
      $transaction_data['created_date'] = date('Y-m-d H:i:s');
      $transaction_data['created_by'] = $this->session->userdata('user_id');
      $account_head_data = $this->Account->select_account_heads("", array("acc_supplier_id" => $data['supplier_id']));

      if ($account_head_data->num_rows() == 1) {
        $transaction_data['tr_credit_acc'] = $account_head_data->row()->acc_head_id;
        $transaction_data['reference_id'] = $data['supplier_id'];
        $transaction_data['reference_type'] = "supplier";
        $transaction_data['tr_other_data'] = "Purchase Return Refund for #".$data['return_group_id'];
        $transaction_data['tr_amount'] = $this->input->post("total_return_amount");
        $transaction_data['tr_type'] = "supplier_advance_transaction";
        $transaction_data['tr_description'] = ucwords(str_replace('_', ' ', $transaction_data['tr_type']));
        $transaction_result =  $this->Account->create_account_transaction($transaction_data);
      }

      if($this->config->item('BOQ_dpr_template')==2){
        $this->boq_management->auto_correct_material_consumption_balance($work_id);
      }

      $flash_data['status'] = $result['status'];
      $flash_data['flashdata_msg'] = 'Purchase Return Saved Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['status'] = 0;
      $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_purchase_return($page_data_type = "")
  {

    $json_data = array();
    $j = 0;
    $sl_no = 0;
    $data = $array = array();
    if (isset($_POST['location_id']) && $_POST['location_id'] != '' && $_POST['location_id'] != 'all') {
      $data['sr.location_id'] = $_POST['location_id'];
    }
    if (isset($_POST['work_id']) && $_POST['work_id'] != '' && $_POST['work_id'] != 'all') {
      $data['pr.work_id'] = $_POST['work_id'];
    }
    if (isset($_POST['stage_id']) && $_POST['stage_id'] != '' && $_POST['stage_id'] != 'all') {
      $data['pr.project_stage_id'] = $_POST['stage_id'];
    }
    if (isset($_POST['material_id']) && $_POST['material_id'] != '' && $_POST['material_id'] != 'all') {
      $data['sr.material_id'] = $_POST['material_id'];
    }
    if (isset($_POST['material_category']) && $_POST['material_category'] != '' && $_POST['material_category'] != 'all') {
      $data['m.category'] = $_POST['material_category'];
    }
    if (isset($_POST['user_id']) && $_POST['user_id'] != '' && $_POST['user_id'] != 'all') {
      $data['pr.created_by'] = $_POST['user_id'];
    }
    if(isset($_POST['supplier']) && $_POST['supplier']!='' && $_POST['supplier']!='all'){
      $data['pr.supplier_id'] = $_POST['supplier'];
    }
    if (isset($_POST['start_date']) && $_POST['start_date'] != '' && $_POST['start_date'] != 'all') {
      $data['pr.return_date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if (isset($_POST['end_date']) && $_POST['end_date'] != '' && $_POST['end_date'] != 'all') {
      $data['pr.return_date <='] = date('Y-m-d', strtotime($_POST['end_date']));
    }
    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(pr.return_date,'%Y-%m-%d') <="] = $end_date;
      $data["STR_TO_DATE(pr.return_date,'%Y-%m-%d') >="] = $start_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)");
    }
    $entry_approval = 1;
    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'];
      }
    }
    // Select All Available Materials in Stock
    $purchase_returns  = $this->Purchases->select_purchase_return("pr.*,sl.location_type,sl.work_id as location_work_id,s.supplier_name,sr.material_id,m.material_name,mu.unit_name,sr.location_id,u.user_alias as created_user,sl.location_name,u.user_role as created_user_role_id,tt.tax_percentage", $data, '', $entry_approval);
    $grand_total_amount = $grand_total_tax_amount = 0;
    foreach ($purchase_returns->result() as $row) :
      if ($row->return_id != '') {

        $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="purchase_return" data-approval-status="' . $row->entry_approval_status . '" data-id="' . $row->cons_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) {
          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>";
          }
        }
        if($row->location_type=='work_site'){
          $location_name = '<a href="' . base_url() . 'work/profile/' . $row->location_work_id . '">' . $row->location_name . '<br/>[Work Site]</a>';
        }elseif($row->location_type=='ware_house'){
          $location_name = '<a href="' . base_url() . 'stock/locations/profile/' . $row->location_id . '">' . $row->location_name . '<br/>[Warehouse]</a>';
        }
        $tax_amount = ($row->returned_qty*$row->unit_price)*$row->tax_percentage/100;
        $total_amount = ($row->returned_qty*$row->unit_price)+$tax_amount;
        $grand_total_amount += $total_amount;
        $grand_total_tax_amount += $tax_amount;

        $sl_no++;
        $array[$j][] = $sl_no;
        $array[$j][] = $row->return_id ;
        $array[$j][] = date('d-m-Y', strtotime($row->return_date));
        $array[$j][] = $row->supplier_name ;
        $array[$j][] = $row->material_name;
        $array[$j][] = $row->unit_name;
        $array[$j][] = number_format($row->returned_qty,2);
        $array[$j][] = number_format($row->unit_price,2);
        $array[$j][] = $row->tax_percentage."%";
        $array[$j][] = number_format($tax_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $array[$j][] = number_format($total_amount,2);
        $array[$j][] = $location_name;
        $array[$j][] = $row->created_user . $entry_approval_status;
        $array[$j][] = $btn_approve;

        $j++;
      }

    endforeach;
    if (sizeof($array) > 0) {
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = "<strong>Grand Total</strong>";
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = "<strong>" . round($grand_total_tax_amount,$this->config->item('Currency_amount_decimals_2')) . "</strong>";
      $array[$j][] = "<strong>" . round($grand_total_amount,$this->config->item('Currency_amount_decimals_2')) . "</strong>";
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
    }
    $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
  }

  public function create_delivery_challan(){

    $data['order_id'] = $this->security->xss_clean($this->input->post('order_id'));
    $data['challan_no'] = $this->security->xss_clean($this->input->post('challan_no'));
    $data['challan_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('challan_date'))));
    $data['delivery_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('delivery_date'))));
    $data['gate_entry'] = $this->security->xss_clean($this->input->post('gate_entry'));
    $data['qc_stamp'] = $this->security->xss_clean($this->input->post('qc_stamp'));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');
    // if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
    //   $data['entry_approval_status'] = 0;
    // }

    $result = $this->Purchases->insert_delivery_challan($data);
    $flash_data['status'] = $result['status'];
    if($result['status']==1){
      $item_data['challan_id'] = $result['insert_id'];

      // Insert Cart Items
      $items_array=$newArrayitems=array();
      if($this->input->post('item')){
        $items_array = $this->input->post('item');
      }
      $items_array_length = sizeof($items_array);
      // Convert to New Formatted Array
      foreach (array_keys($items_array) as $fieldKey) {
        foreach ($items_array[$fieldKey] as $key=>$value) {
          $newArrayitems[$key][$fieldKey] = $value;
        }
      }
      foreach ($newArrayitems as $row) {
        if($row['quantity']>0){
          $item_data['order_item_id'] = $row['item_id'];
          $item_data['delivery_qty'] = $row['quantity'];
          $item_result = $this->Purchases->create_delivery_challan_item($item_data);
        }
      }



      $flash_data['flashdata_msg'] = 'Delivery Challan Saved Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
      $flash_data['challan_id'] = $result['insert_id'];

      $order_data_2 = $this->Purchase_order->select_purchase_order("sl.work_id,sl.location_type",array("po.order_id"=>$data['order_id']),'all')->row();
      $flash_data['location_type']=$order_data_2->location_type;
      $flash_data['work_id']=$order_data_2->work_id;
    }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);  // send data as json format
  }
  public function select_delivery_challan($page_data_type=''){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $total_amount_paid=$total_est_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(pdc.challan_date,'%Y-%m-%d') <="]= $end_date;
      $data["STR_TO_DATE(pdc.challan_date,'%Y-%m-%d') >="]= $start_date;
    }
    if(isset($_POST['supplier']) && $_POST['supplier']!='' && $_POST['supplier']!='all'){
      $data['s.supplier_id'] = $_POST['supplier'];
    }
    if(isset($_POST['location']) && $_POST['location']!='' && $_POST['location']!='all'){
      $data['po.location_id'] = $_POST['location'];
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['sl.work_id'] = $_POST['work'];
    }
    if(isset($_POST['stage_id']) && $_POST['stage_id']!='' && $_POST['stage_id']!='all'){
      $data['po.project_stage_id'] = $_POST['stage_id'];
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['po.created_by'] = $_POST['user_id'];
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!='' && $_POST['start_date']!='all'){
      $data['pdc.challan_date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!='' && $_POST['end_date']!='all'){
      $data['pdc.challan_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['po.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'];
      }
    }

    $result = $this->Purchases->select_delivery_challan("pdc.*,po.order_date,u.user_alias,s.supplier_name,s.supplier_id,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id,u.user_role as created_user_role_id",$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):
      $bill_id_column= 11;//Column Where Bill ID Exist
      $btn_view='<a style="margin-left: 5px;margin-right: 5px"  href="'.base_url().'purchases/delivery_challan/view/'.$row->challan_id.'" class="btn btn-primary m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
      <i class="la la-eye"></i>
      </a>';
      $btn_edit = $btn_delete = '';
      $btn_add_payment='';
      $location_name = $row->location_name;
      if($row->location_type=='work_site'){
        $location_name = '<a href="' . base_url() . 'work/profile/' . $row->location_work_id . '">' . $row->location_name . '<br/>[Work Site]</a>';
      }elseif($row->location_type=='ware_house'){
        $location_name = '<a href="' . base_url() . 'stock/locations/profile/' . $row->location_id . '">' . $row->location_name . '<br/>[Warehouse]</a>';
      }

      $purchase_bill_id_s = 0;
      $no_of_bills = 0;

      if($no_of_bills!=0){
        $bill_creation_status="<span style='margin-left: 5px;margin-right: 5px' class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check-circle'></i> $no_of_bills Bill Created</span>";
        foreach ($purchase_bill_id_s as $key => $bill_id) {
          $bill_creation_status.='<br/><a style="margin-top: 5px;margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'purchases/profile/' . $bill_id . '" class="btn btn-warning btn-sm m-btn m-btn--icon   m-btn--pill m-btn--air">
          <i class="la la-eye"></i> # '.$bill_id.'
          </a>';
        }
      }else{
        $bill_creation_status="<span style='margin-left: 5px;margin-right: 5px' class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Bill Not Created</span>";
        if($this->session->userdata('user_role')!='auditor' || $this->session->userdata('user_data_permission')['adding']==1){
          // if($row->entry_approval_status==1){
          $bill_creation_status.='<br/><a style="margin-top: 5px;margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'purchases/add?challan_id=' . $row->challan_id . '" class="btn btn-info btn-sm m-btn m-btn--icon   m-btn--pill m-btn--air">
          <i class="la la-plus-circle"></i> Add Purchase Bill
          </a>';
          // }
        }

        // if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_id')==$row->created_by) {
        //   $btn_edit = '<a style="margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'purchase_order/edit/' . $row->challan_id . '" 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>';
        // }
        // if($this->session->userdata('user_role')=='admin'){
        //   $btn_delete='<a style="margin-left: 5px;margin-right: 5px" data-bill-type="purchase_order" 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>';
        // }

      }

      $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="purchase_order" data-approval-status="'.$row->entry_approval_status.'" data-id="'.$row->challan_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>";
      //   }
      // }

      $sl_no++;

      $array[$j][]=$sl_no;
      $array[$j][]='<a href="' . base_url() . 'purchases/delivery_challan/view/' . $row->challan_id . '">#' . $row->challan_id . '</a>';
      $array[$j][]=date('d-m-Y',strtotime($row->challan_date));
      $array[$j][]=$row->challan_no;
      $array[$j][]=date('d-m-Y',strtotime($row->delivery_date));
      $array[$j][]='<a href="' . base_url() . 'supplier/profile/' . $row->supplier_id . '">' . $row->supplier_name . '</a>';
      $array[$j][]=$location_name;
      $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Gate Entry : '.$row->gate_entry."</li><li>QC Stamp : ".$row->qc_stamp."</li>";
      $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Order ID : #'.$row->order_id."</li><li>Order Date : ".date('d-m-Y',strtotime($row->order_date))."</li>";
      $array[$j][]=$bill_creation_status;
      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>".$entry_approval_status;
      }else{
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->user_alias.'</li>'.$entry_approval_status;
      }
      $array[$j][]=$btn_view.$btn_edit.$btn_delete;
      $array[$j][]=$row->challan_id;


      $j++;
    endforeach;


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