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

class Accounts extends CI_Controller
{

  public $page_data = array();

  function __construct()
  {
    parent::__construct();
    //Calling Initial Functions
    $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('Subcontracts_model', 'Subcontracts');
    $this->load->model('Labour_model', 'Labour');
    $this->load->model('Labour_wages_model', 'Labour_wages');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Bills_model', 'Bills');
    $this->load->model('Loan_model', 'Loan');
    $this->load->model('Vehicle_model', 'Vehicle');
    $this->load->model('Employees_model', 'Employee');
    $this->load->model('Vehicle_work_slips_model', 'Vehicle_work_slips');
    $this->load->library('Bills_management', 'bills_management');
    $this->load->library('Accounts_management', 'accounts_management');
    $this->load->library('Projects_management', 'projects_management');
    $this->load->library('Supplier_management', 'supplier_management');

    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin", "admin", "supervisor", "general_manager", "purchase_manager", "accounts_manager", "auditor","qs","qs_manager","procurement_engineer","project_manager","hr_manager","operation_manager");
    if ($this->User->is_logged_in($allowed_user_roles) == false) {
      redirect(base_url(), 'refresh');
    }

    //        File Directory
    $this->page_data['directory'] = "account";
  }
  public function index()
  {
    $this->view();
  }
  public function view()
  {
    $this->page_data['page_name'] = 'account_heads';
    $this->load->view('Index', $this->page_data);
  }
  public function security_deposits()
  {
    $work_data = array();
    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("*", $work_data)->result();

    $this->page_data['page_name'] = 'security_deposits';
    $this->load->view('Index', $this->page_data);
  }
  public function assets()
  {
    $work_data = array();
    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("*", $work_data)->result();

    $this->page_data['page_name'] = 'assets';
    $this->load->view('Index', $this->page_data);
  }
  public function transfer()
  {
    $this->page_data['page_name'] = 'account_transfer';
    $this->load->view('Index', $this->page_data);
  }
  public function creditors()
  {
    $this->page_data['page_name'] = 'creditors_list';
    $this->load->view('Index', $this->page_data);
  }
  public function ledger($account_id = '')
  {
    $this->page_data['selected_financial_year'] = $this->page_data['selected_employee_account_type'] = $this->page_data['selected_account_category'] = $this->page_data['selected_account_prefix'] = $this->page_data['dropdown_selected_account'] = $this->page_data['selected_account_data'] = $this->page_data['selected_account'] = $this->page_data['selected_end_date'] = $this->page_data['selected_start_date'] = '';
    $this->page_data['financial_year'] = $this->Settings->select_finyear("*")->result();

    if ($account_id != '') {
      $this->page_data['dropdown_selected_account'] = $account_id;
    }
    if (isset($_POST['start_date']) && $_POST['start_date'] != '') {
      $this->page_data['selected_start_date'] = $_POST['start_date'];
    }
    if (isset($_POST['end_date']) && $_POST['end_date'] != '') {
      $this->page_data['selected_end_date'] = $_POST['end_date'];
    }
    if (isset($_POST['account_category']) && $_POST['account_category'] != '') {
      $this->page_data['selected_account_category'] = $_POST['account_category'];
    }
    if (isset($_POST['financial_year']) && $_POST['financial_year'] != '') {
      $this->page_data['selected_financial_year'] = $_POST['financial_year'];
    }
    if (isset($_POST['account']) && $_POST['account'] != '') {
      $this->page_data['selected_account'] = $_POST['account'];
      if(isset($_POST['employee_account_type'])){
        $this->page_data['selected_employee_account_type'] = $_POST['employee_account_type'];
      }
      $ledger_data = $this->accounts_management->get_account_statement('ledger',$this->page_data['selected_account'],$this->page_data['selected_start_date'],$this->page_data['selected_end_date'],$this->session->userdata('user_role'),$this->session->userdata('user_id'),$this->page_data['selected_employee_account_type'],$this->page_data['selected_account_category']);
      foreach ($ledger_data as $key => $value) {
        $this->page_data[$key] = $value;
      }
    }


    $this->page_data['page_name'] = 'account_ledger';
    $this->load->view('Index', $this->page_data);
  }
  public function select_ledger_account_heads()
  {
    $i = 0;
    $type1='';
    $account_category = $this->input->post('account_category');
    $heads = $data =   $employee_where = array();
    if($account_category=='all' || $account_category=='Expense Head' || $account_category=='Supplier' || $account_category=='Employee' || $account_category=='Bank' || $account_category=='Cash'){
      if ($this->session->userdata('user_role') == 'accounts_manager' || $this->session->userdata('user_role') == 'admin' || $this->session->userdata('user_role') == 'madmin'  || $this->session->userdata('user_role') == 'general_manager' || $this->session->userdata('user_role') == 'auditor') {
        if($this->session->userdata('user_role') != 'admin'){
          $this->db->where('acc_user_id!=1');
        }
        $this->db->where('account_type != 2 and  account_type != 37');
        $this->db->where('((account_type=12 and acc_supplier_id!=0) or (account_type!=12))');
      } else {
        $this->db->where('account_type != 2 and account_type != 12 and account_type != 37');
        $this->db->where('((acc_user_id=' . $this->session->userdata('user_id') . " and account_type = 32) or (account_type = 11)) ");
      }
      if ($this->session->userdata('user_role') == 'supervisor') {
        $data['ah.acc_user_id'] = $this->session->userdata('user_id');
        $employee_where['e.user_id'] = $this->session->userdata('user_id');
      }
      if (isset($_POST['account_type']) && $_POST['account_type'] != '') {
        if (is_array($_POST['account_type']) == 1) {
          $account_type = implode(',', $_POST['account_type']);
          $this->db->where('ah.account_type IN(' . $account_type . ')');
        } else {
          $data['ah.account_type'] = $_POST['account_type'];
        }
      }
      if($account_category=='all' || $account_category=='Cash'){
        $data['ah.account_type'] = 32;
        $data['ah.acc_user_id'] = 0;
        $data['ah.acc_employee_id'] = 0;
        // $heads[$i]['account_type_display'] = 'Company Cash in Hand';
      }
      if($account_category=='all' || $account_category=='Bank'){
        $data['ah.account_type'] = 36;
        // $heads[$i]['account_type_display'] = 'Bank';
      }
      if($account_category=='all' || $account_category=='Employee'){
        $data['ah.acc_employee_id !='] = 0;
        $data['ah.account_type'] = 32;
        $type1='user';
        // $heads[$i]['account_type_display'] = 'Employee';
      }
      if($account_category=='all' || $account_category=='Supplier'){
        $data['ah.acc_supplier_id !='] = 0;
        $data['ah.account_type'] = 12;
        // $heads[$i]['account_type_display'] = 'Supplier';
      }
      if($account_category=='all' || $account_category=='Expense Head'){
        $data['ah.account_type'] = 11;
        // $heads[$i]['account_type_display'] = 'Expense Head';
      }

      // $heads[$i]['acc_head_id'] = 'acchead_all';
      // $heads[$i]['acc_head_name'] = 'All Account Heads';
      // $i++;

      $account_heads = $this->Account->select_account_heads("", $data,$type1);

      foreach ($account_heads->result() as $row) :
        $heads[$i]['account_type_display'] = '';
        if ($row->acc_head_id == 1) {
          $heads[$i]['account_type_display'] = 'Company Cash in Hand';
        } elseif ($row->acc_head_id != 1 && $row->account_type == 32 && $row->acc_employee_id != 0) {
          $heads[$i]['account_type_display'] = 'Employee';
        } elseif ($row->account_type == 36) {
          $heads[$i]['account_type_display'] = 'Bank';
        } elseif ($row->account_type == 11) {
          $heads[$i]['account_type_display'] = 'Expense Head';
        } elseif ($row->account_type == 12 && $row->acc_supplier_id != 0) {
          $heads[$i]['account_type_display'] = 'Supplier';
        }
        $heads[$i]['acc_head_id'] = 'acchead_' . $row->acc_head_id;
        $heads[$i]['acc_head_name'] = $row->acc_head_name;
        if($type1=='user'){
          $heads[$i]['department'] = $row->department_name;
          $heads[$i]['designation'] = $row->user_designation;
        }else{
          $heads[$i]['department'] = '';
          $heads[$i]['designation'] = '';
        }

        $i++;

      endforeach;
    }
    if($account_category=='all' || $account_category=='Expense Type'){
      // $heads[$i]['acc_head_id'] = 'expensetype_all';
      // $heads[$i]['acc_head_name'] = "All Account Heads";
      // $heads[$i]['account_type_display']='Expense Type';
      // $heads[$i]['account_prefix'] = 'expense_type';
      // $i++;

      $heads[$i]['acc_head_id'] = 'expensetype_28';
      $heads[$i]['acc_head_name'] = "Office Income/Expenses";
      $heads[$i]['account_type_display']='Expense Type';
      $heads[$i]['account_prefix'] = 'expense_type';
      $i++;

      $heads[$i]['acc_head_id'] = 'expensetype_29';
      $heads[$i]['acc_head_name'] = "Marketing Expenses";
      $heads[$i]['account_type_display']='Expense Type';
      $heads[$i]['account_prefix'] = 'expense_type';
      $i++;

      $heads[$i]['acc_head_id'] = 'expensetype_30';
      $heads[$i]['acc_head_name'] = "Project Expenses";
      $heads[$i]['account_type_display']='Expense Type';
      $heads[$i]['account_prefix'] = 'expense_type';
      $i++;
    }
    if($account_category=='all' || $account_category=='Payment Mode'){
      // $heads[$i]['acc_head_id'] = 'paymentmode_all';
      // $heads[$i]['acc_head_name'] = 'All Account Heads';
      // $heads[$i]['account_type_display']='Payment Mode';
      // $heads[$i]['account_prefix'] = 'payment_mode';
      // $i++;

      foreach($this->config->item('payment_modes') as $row):
        $heads[$i]['acc_head_id'] = 'paymentmode_'.str_replace(' ','&',$row);
        $heads[$i]['acc_head_name'] = $row;
        $heads[$i]['account_type_display']='Payment Mode';
        $heads[$i]['account_prefix'] = 'payment_mode';
        $i++;
      endforeach;
    }
    if($account_category=='all' || $account_category=='Vehicle Owner'){
      // $heads[$i]['acc_head_id'] = 'vehicleconsignee_all';
      // $heads[$i]['acc_head_name'] = 'All Account Heads';
      // $heads[$i]['account_type_display']='Vehicle Consignee';
      // $heads[$i]['account_prefix'] = 'vehicle_consignee';
      // $i++;

      $vehicle_consignees = $this->Vehicle->select_consignee('*')->result();
      foreach ($vehicle_consignees as $row):
        $heads[$i]['acc_head_id'] = 'vehicleconsignee_'.$row->consignee_id;
        $heads[$i]['acc_head_name'] = $row->consignee_name." (".$row->consignee_place.")";
        $heads[$i]['account_type_display']='Vehicle Consignee';
        $heads[$i]['account_prefix'] = 'vehicle_consignee';
        $i++;
      endforeach;
    }
    if($account_category=='all' || $account_category=='Vehicle'){
      // $heads[$i]['acc_head_id'] = 'vehicle_all';
      // $heads[$i]['acc_head_name'] = 'All Account Heads';
      // $heads[$i]['account_type_display']='Vehicle';
      // $heads[$i]['account_prefix'] = 'vehicle';
      // $i++;

      $vehicles = $this->Vehicle->select_vehicle('v.*,vc.consignee_name')->result();
      foreach ($vehicles as $row):
        $heads[$i]['acc_head_id'] = 'vehicle_'.$row->id;
        $heads[$i]['acc_head_name'] = $row->vehicle_no." (".$row->vehicle_name." - ".$row->consignee_name.")";
        $heads[$i]['account_type_display']='Vehicle';
        $heads[$i]['account_prefix'] = 'vehicle';
        $i++;
      endforeach;
    }
    if($account_category=='all' || $account_category=='Labour'){

      // $heads[$i]['acc_head_id'] = 'labour_all';
      // $heads[$i]['acc_head_name'] = 'All Account Heads';
      // $heads[$i]['account_type_display']='Labour';
      // $heads[$i]['account_prefix'] = 'labour';
      // $i++;

      $this->db->where('(l.labour_type=0 or (l.labour_type=1 and group_position=1))');
      $labours = $this->Labour->select_labours('l.*,wt.type_name')->result();
      foreach ($labours as $row):
        if($row->labour_type==0){
          $labour_type = "Individual";
        }else{
          if($row->group_position==1){
            $labour_type = "Group Leader";
          }else{
            $labour_type = "Group Member";
          }
        }
        $heads[$i]['acc_head_id'] = 'labour_'.$row->labour_id;
        $heads[$i]['acc_head_name'] = $row->labour_name." (".$row->type_name." - ".$labour_type.")";
        $heads[$i]['account_type_display']='Labour';
        $heads[$i]['account_prefix'] = 'labour';
        $i++;
      endforeach;
    }
    if($account_category=='all' || $account_category=='Client'){
      // $heads[$i]['acc_head_id'] = 'client_all';
      // $heads[$i]['acc_head_name'] = 'All Account Heads';
      // $heads[$i]['account_type_display']='Client';
      // $heads[$i]['account_prefix'] = 'client';
      // $i++;

      if ($this->session->userdata('user_role') == 'accounts_manager' || $this->session->userdata('user_role') == 'admin' || $this->session->userdata('user_role') == 'madmin'  || $this->session->userdata('user_role') == 'general_manager') {
        $clients = $this->Client->select_client('')->result();
        foreach ($clients as $row):
          $heads[$i]['acc_head_id'] = 'client_'.$row->client_id;
          $heads[$i]['acc_head_name'] = $row->client_name;
          $heads[$i]['account_type_display']='Client';
          $heads[$i]['account_prefix'] = 'client';
          $i++;
        endforeach;
      }
    }
    // if($account_category=='all' || $account_category=='Employee'){
    //   $employees = $this->Employee->select_employee('e.*',$employee_where)->result();
    //   foreach ($employees as $row):
    //     $heads[$i]['acc_head_id'] = 'employee_'.$row->employee_id;
    //     $heads[$i]['acc_head_name'] = $row->employee_name;
    //     $heads[$i]['account_type_display']='Employee Salary A/C';
    //     $heads[$i]['account_prefix'] = 'employee';
    //     $i++;
    //   endforeach;
    // }
    if($account_category=='all' || $account_category=='Contractor'){
      // $heads[$i]['acc_head_id'] = 'contractor_all';
      // $heads[$i]['acc_head_name'] = 'All Account Heads';
      // $heads[$i]['account_type_display']='Contractor';
      // $heads[$i]['account_prefix'] = 'contractor';
      // $i++;

      $contractors = $this->Subcontracts->select_contractors('c.*')->result();
      foreach ($contractors as $row):
        $heads[$i]['acc_head_id'] = 'contractor_'.$row->contractor_id;
        $heads[$i]['acc_head_name'] = $row->contractor_name;
        $heads[$i]['account_type_display']='Contractor';
        $heads[$i]['account_prefix'] = 'contractor';
        $i++;
      endforeach;
    }

    if(sizeof($heads)>0) {
      echo json_encode(array("count" => sizeof($heads),"data" => $heads));
    }else{
      echo json_encode(array("count" => 0));
    }
  }

  public function create_head($param1="")
  {
    $data['acc_head_name'] = $this->security->xss_clean($this->input->post('acc_head'));
    $data['account_type'] = $this->security->xss_clean($this->input->post('acc_type'));
    $count = $this->Account->select_account_heads("", $data)->num_rows();
    if ($count == 0) {
      $data['head_editable'] = 1;
      $data['op_balance'] = $this->security->xss_clean($this->input->post('op_balance'));
      $data['op_balance_date'] = date('Y-m-d',strtotime($this->input->post('op_balance_date')));
      $data['created_date'] = date('Y-m-d H:i:s');
      $data['created_by'] = $this->session->userdata('user_id');
      $result = $this->Account->create_account_head($data);
      $flash_data['status'] = $result['status'];
      if ($result['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Account Head Created Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'info';
        $flash_data['flashdata_title'] = 'Success !';

        // Add User Activity
        $this->User->add_user_activity('Accounts', $result['insert_id'], 'Account Head Created');
      } 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.. Account Head With Same Name Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    if ($param1 == "modal") {
      echo (json_encode($flash_data));
    } else {
      $this->session->set_flashdata($flash_data);
      redirect(base_url() . 'accounts', 'refresh');
    }
  }
  public function update_head($param1 = "")
  {
    $redirect_url = $this->security->xss_clean($this->input->post('redirect_url'));
    $data['acc_head_id'] = $this->security->xss_clean($this->input->post('acc_head_id'));
    $acc_head_data = $this->Account->select_account_heads("", array("acc_head_id" => $data['acc_head_id']))->row();
    $data['acc_head_name'] = $this->security->xss_clean($this->input->post('acc_head'));
    $count = 0;
    if ($acc_head_data->head_editable == 1) {
      $data['account_type'] = $this->security->xss_clean($this->input->post('acc_type'));
      $count = $this->Account->select_account_heads("", array("account_type" => $data['account_type'], "acc_head_name" => $data['acc_head_name'], "acc_head_id !=" => $data['acc_head_id']))->num_rows();
    }
    if ($count == 0) {
      $data['op_balance'] = $this->security->xss_clean($this->input->post('op_balance'));
      $data['op_balance_date'] = date('Y-m-d',strtotime($this->input->post('op_balance_date')));
      $result = $this->Account->update_account_head($data);

      if ($result == 1) {
        $flash_data['flashdata_msg'] = 'Account Head Details Updated Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'info';
        $flash_data['flashdata_title'] = 'Success !';
        // Add User Activity
        $this->User->add_user_activity('Accounts', $data['acc_head_id'], 'Account Head Details Updated');
      } 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['flashdata_msg'] = 'Sorry.. Account Head With Same Name Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }

    $this->session->set_flashdata($flash_data);
    redirect($redirect_url, 'refresh');
  }
  public function delete_head($param1 = "")
  {
    $redirect_url = $this->security->xss_clean($this->input->post('redirect_url'));
    $data['acc_head_id'] = $this->security->xss_clean($this->input->post('acc_head_id'));
    $bills  = $this->Bills->select_bills("b.bill_id", array("b.bill_credit_ac" => $data['acc_head_id']));
    $this->db->where('(ats.tr_debit_acc=' . $data['acc_head_id'] . ' or ats.tr_credit_acc=' . $data['acc_head_id'] . ')');
    $transactions  = $this->Account->select_account_transaction("ats.transaction_id");
    if ($bills->num_rows() == 0 && $transactions->num_rows() == 0) {
      $data['delete_status'] = 1;
      $result = $this->Account->update_account_head($data);
      if ($result == 1) {
        $flash_data['flashdata_msg'] = 'Account Head Deleted Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'info';
        $flash_data['flashdata_title'] = 'Success !';
        // Add User Activity
        $this->User->add_user_activity('Accounts', $data['acc_head_id'], 'Account Head Deleted');
      } 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['flashdata_msg'] = 'Sorry.. There is Bills or Transactions Exist in Selected Head!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Data Exist !!';
    }
    $this->session->set_flashdata($flash_data);
    redirect($redirect_url, 'refresh');
  }
  public function select_heads()
  {

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

    $data = array();
    $data['ah.delete_status'] = 0;
    if ($this->session->userdata('user_role') == 'auditor' || $this->session->userdata('user_role') == 'accounts_manager' || $this->session->userdata('user_role') == 'admin' || $this->session->userdata('user_role') == 'madmin' || $this->session->userdata('user_role') == 'general_manager') {
      if($this->session->userdata('user_role') != 'admin'){
        $this->db->where('acc_user_id!=1');
      }
      $this->db->where('account_type != 2 and account_type != 12 and account_type != 37');
    } else {
      $this->db->where('account_type != 2 and account_type != 12 and account_type != 37');
      $this->db->where('((acc_user_id=' . $this->session->userdata('user_id') . " and account_type = 32) or (account_type = 11))");
    }
    if ($this->session->userdata('user_role') == 'supervisor') {
      $data['ah.acc_user_id'] = $this->session->userdata('user_id');
    }

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

    $result = $this->Account->select_account_heads("", $data);
    $result_array = $result->result();

    $json_data['draw'] = 5;
    $json_data['recordsTotal'] = $result->num_rows();
    $json_data['recordsFiltered'] = $result->num_rows();
    $array = array();
    $sl_no = 0;
    foreach ($result_array as $row) :
      $sl_no++;
      $btn_view = $btn_edit = $btn_delete = '';
      $acc_head_name = $row->acc_head_name;
      if ($this->session->userdata('user_role') == 'admin' || $this->session->userdata('user_role') == 'general_manager' || $this->session->userdata('user_role') == 'accounts_manager' || $this->session->userdata('user_role') == 'madmin') {
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="acc_head_edit_btn" href="#acc_head_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-edit"></i>
        </a>';
        if ($row->head_editable == 1) {
          $btn_delete = '<a style="margin-left: 5px;margin-right: 5px" id="acc_head_delete_btn" href="#acc_head_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->account_type!=11){

      $btn_view = '<a style="margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'accounts/ledger/acchead_' . $row->acc_head_id . '" class="btn btn-focus m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
      <i class="la la-th-list"></i></a>';
      $acc_head_name = '<a href="' . base_url() . 'accounts/ledger/acchead_' . $row->acc_head_id . '">' . $row->acc_head_name . '</a>';

      // }
      $branch_name = 'No Branch';
      $branch_data = $this->Branches->select_branches('*', array('branch_id' => $row->acc_head_branch_id));
      if($branch_data->num_rows()==1){
        $branch_name = $branch_data->row()->branch_name;
      }
      $current_balance = 0;
      // $current_balance = $this->accounts_management->calculate_trial_balance($row->acc_head_id,'','','',$this->session->userdata('user_role'),$this->session->userdata('user_id'));

      $array[$j][] = $sl_no;
      $array[$j][] = $branch_name;
      $array[$j][] = $row->acc_head_id;
      $array[$j][] = $acc_head_name;
      $array[$j][] = $row->ac_type_name;
      $array[$j][] = $row->account_type;
      $array[$j][] = $row->op_balance;
      $array[$j][] = date('d-m-Y', strtotime($row->op_balance_date));
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($current_balance, $this->config->item('Currency_currency_shortname'));
      $array[$j][] = $row->head_editable;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][] = date('d-m-Y', strtotime($row->created_date));
      }else{
        $array[$j][] = '';
      }
      $array[$j][] = $btn_view . $btn_edit . $btn_delete;

      $j++;
    endforeach;

    $json_data['data'] = $array;
    echo json_encode($json_data);  // send data as json format
  }
  public function select_heads_2()
  {
    $data = array();
    if (isset($_POST['account_type']) && $_POST['account_type'] != '') {
      if (is_array($_POST['account_type']) == 1) {
        $account_type = implode(',', $_POST['account_type']);
        $this->db->where('ah.account_type IN(' . $account_type . ')');
      } else {
        $data['ah.account_type'] = $_POST['account_type'];
      }
    }
    $result = $this->Account->select_account_heads("", $data);
    if ($result->num_rows() > 0) {
      foreach ($result->result() as $row) :
        $id[] = $row->acc_head_id;
        $name[] = $row->acc_head_name;
      endforeach;
      echo json_encode(array("count" => $result->num_rows(), "id" => $id, "name" => $name));
    } else {
      echo json_encode(array("count" => $result->num_rows()));
    }
  }

  public function create_transaction()
  {
    $redirect_url = $this->security->xss_clean($this->input->post('redirect_url'));

    $reference_id = $this->security->xss_clean($this->input->post('reference_id'));
    $reference_type = $this->security->xss_clean($this->input->post('reference_type'));
    $transaction_data['tr_type'] = $this->security->xss_clean($this->input->post('tr_type'));
    $transaction_data['reference_id'] = $reference_id;
    $transaction_data['reference_type'] = $reference_type;
    $transaction_data['tr_description'] = ucwords(str_replace('_', ' ', $transaction_data['tr_type']));
    $transaction_data['tr_reference_no'] = $this->security->xss_clean($this->input->post('reference_no'));
    $transaction_data['tr_remarks'] = $this->security->xss_clean($this->input->post('tr_remarks'));
    $transaction_data['created_date'] = date('Y-m-d H:i:s');
    $transaction_data['created_by'] = $this->session->userdata('user_id');
    if ($this->config->item('User_enable_data_entry_approval') == 1 && $this->session->userdata('user_role_id') > 2) {
      $transaction_data['tr_entry_approval_status'] = 0;
    }
    if(($transaction_data['tr_type'] == 'expense_bill_transaction' || $transaction_data['tr_type'] == 'purchase_bill_transaction' || $transaction_data['tr_type'] == 'loan_transaction' || $transaction_data['tr_type'] == 'loan_receipt_transaction') && $this->config->item('User_enable_data_entry_approval_2_level')==1 && $this->session->userdata('user_role_id')>2){
      $transaction_data['tr_entry_approval_status_2'] = 0;
    }
    $file_error = 0;

    if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']["size"] > 0) {
      //          Check Allowed File Type
      // $file_type = $_FILES['uploaded_file']['type']; //returns the mimetype
      // $allowed = array("image/jpeg", "image/png");
      // if (!in_array($file_type, $allowed)) {
      //   $file_error = 1;
      // }
      //          Check Image Size (Only For Image Upload)
      // $imageinfo = getimagesize($_FILES['uploaded_file']['tmp_name']); //check image size
      // if ($imageinfo['mime'] != 'image/png' && $imageinfo['mime'] != 'image/jpeg') {
      //     $file_error = 1;
      // }
      //          Check Blacklist Extensions
      $blacklist = array(".php", ".phtml", ".php3", ".php4", ".html", ".htm", ".js");
      foreach ($blacklist as $item) {
        if (preg_match("/$item\$/i", $_FILES['uploaded_file']['name'])) {
          $file_error = 1;
        }
      }

      if ($file_error == 1) {
        $flash_data['flashdata_msg'] = 'Selected File Not allowed to Upload.';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'File Format Error !!';
      }

      //      File Upload
      $config['upload_path']   = 'uploads/transaction/';
      $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();
        $transaction_data['tr_file_attachment'] = $file_data['file_name'];
      }
    }
    if ($transaction_data['tr_type'] == 'client_payment_transaction') {

      $transaction_data['tr_project_stage_id'] = $this->projects_management->get_project_stage_id($transaction_data['reference_id']);

      $transaction_data['tr_other_data'] = $this->security->xss_clean($this->input->post('received_from'));
      $transaction_data['invoice_id'] = $this->security->xss_clean($this->input->post('invoice_id'));
      $transaction_data['tr_credit_acc'] = $this->security->xss_clean($this->input->post('credit_acc'));
      $transaction_data['tr_debit_acc'] = 2; //Client Payment Receipts

      if ($transaction_data['invoice_id'] == 0) {
        //TAX
        $transaction_data['taxable_amount'] = $this->security->xss_clean($this->input->post('client_payment_taxable_amount'));
        $transaction_data['tax_inclusive'] = $this->security->xss_clean($this->input->post('tax_inclusive_add'));
        $transaction_data['tax_percent'] = $this->security->xss_clean($this->input->post('client_payment_tax_percent'));
        $transaction_data['tax_amount'] = $this->security->xss_clean($this->input->post('client_payment_tax_amount'));
      } else {
        $transaction_data['taxable_amount'] = $this->security->xss_clean($this->input->post('received_amount'));
        $transaction_data['tax_percent'] = 0;
        $transaction_data['tax_amount'] = 0;
        $transaction_data['tax_inclusive'] = 0;
      }

      $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('received_amount'));
      $transaction_data['tr_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('received_date'))));
    } elseif ($transaction_data['tr_type'] == 'income_receipt_transaction') {
      if($this->input->post('received_from')){
        $transaction_data['tr_other_data'] = $this->security->xss_clean($this->input->post('received_from'));
      }
      if($this->input->post('invoice_id')){
        $transaction_data['invoice_id'] = $this->security->xss_clean($this->input->post('invoice_id'));
      }
      $transaction_data['tr_work_id'] = $this->security->xss_clean($this->input->post('work'));
      $transaction_data['tr_description'] = $this->security->xss_clean($this->input->post('income_head'));
      $transaction_data['tr_credit_acc'] = $this->security->xss_clean($this->input->post('credit_acc'));
      $transaction_data['tr_debit_acc'] = 14; //Income Receipts
      $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('received_amount'));
      $transaction_data['tr_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('received_date'))));
    }elseif ($transaction_data['tr_type'] == 'sales_invoice_transaction') {
      $transaction_data['tr_credit_acc'] = $this->security->xss_clean($this->input->post('credit_acc'));
      $transaction_data['tr_debit_acc'] = 11; //Sales Invoice Receipts
      $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('received_amount'));
      $transaction_data['tr_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('received_date'))));
    } elseif ($transaction_data['tr_type'] == 'loan_receipt_transaction') {
      $transaction_data['tr_credit_acc'] = $this->security->xss_clean($this->input->post('credit_acc'));
      $transaction_data['tr_debit_acc'] = 15; //Loan Receipts
      $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('received_amount'));
      $transaction_data['tr_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('received_date'))));
    } else {
      if ($transaction_data['tr_type'] == 'purchase_bill_transaction') {
        $transaction_data['tr_credit_acc'] = 5; //Purchase Bill Payments
        $transaction_data['tr_payment_part'] = 2;
      } elseif ($transaction_data['tr_type'] == 'purchase_order_transaction') {
        $transaction_data['tr_credit_acc'] = 6; //Purchase Order Payments
      } elseif ($transaction_data['tr_type'] == 'expense_bill_transaction' || $transaction_data['tr_type'] == 'subcontract_bill_transaction' || $transaction_data['tr_type'] == 'vehicle_bill_transaction') {
        $bill_details = $this->Bills->select_bills("b.bill_type,b.bill_credit_ac", array("b.bill_id" => $transaction_data['reference_id']), '', '', '', 'all', 'all')->row();
        $transaction_data['tr_credit_acc'] = $bill_details->bill_credit_ac;
      } elseif ($transaction_data['tr_type'] == 'labour_transaction') {
        $transaction_data['tr_credit_acc'] = 7; //Labour Payments
      } elseif ($transaction_data['tr_type'] == 'labour_insurance_fd_transaction') {
        $transaction_data['tr_credit_acc'] = 24; //Labour Payments
        $transaction_data['tr_other_data'] = $this->security->xss_clean($this->input->post('labour_payment_type'));
      } elseif ($transaction_data['tr_type'] == 'salary_slip_transaction') {
        $transaction_data['tr_credit_acc'] = 10; //Salary Payments
      } elseif ($transaction_data['tr_type'] == 'loan_transaction') {
        $transaction_data['tr_credit_acc'] = 13; //Loan Payments
      } elseif ($transaction_data['tr_type'] == 'tool_payment_transaction') {
        $transaction_data['tr_credit_acc'] = 18; //Tool Payments
      } elseif ($transaction_data['tr_type'] == 'vehicle_work_slip_transaction') {
        $transaction_data['tr_credit_acc'] = 12; //vehicle Payments
      } elseif ($transaction_data['tr_type'] == 'user_payment_receipt_transaction') {
        $transaction_data['tr_credit_acc'] =  $this->security->xss_clean($this->input->post('user_acc'));
      } elseif ($transaction_data['tr_type'] == 'account_transfer') {
        $transaction_data['tr_credit_acc'] =  $this->security->xss_clean($this->input->post('credit_acc'));
      } elseif ($transaction_data['tr_type'] == 'user_commission_transaction') {
        $transaction_data['tr_credit_acc'] = $this->security->xss_clean($this->input->post('reference_id'));
        $transaction_data['tr_work_id'] = $this->security->xss_clean($this->input->post('work_id'));
      }

      if ($transaction_data['tr_type'] == 'user_payment_return_transaction') {
        $transaction_data['tr_debit_acc'] =  $this->security->xss_clean($this->input->post('user_acc'));
        $transaction_data['tr_credit_acc'] = $this->security->xss_clean($this->input->post('debit_acc'));
      } else {
        $transaction_data['tr_debit_acc'] = $this->security->xss_clean($this->input->post('debit_acc'));
      }

      $transaction_data['tr_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('paid_date'))));
      $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('paid_amount'));
      $transaction_data['tr_mode'] = $this->security->xss_clean($this->input->post('payment_mode'));

      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'))));
      }
    }
    if ($file_error == 0) {
      $transaction_result =  $this->Account->create_account_transaction($transaction_data);
      $flash_data['status'] = $transaction_result['status'];
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = $transaction_data['tr_description'] . ' Created Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';

        // Add User Activity
        $this->User->add_user_activity('Account Transaction', $transaction_result['insert_id'], $transaction_data['tr_description'] . ' Created');

        if ($transaction_data['tr_type'] == 'purchase_bill_transaction') {
          $this->bills_management->calculate_purchase_bill_total($transaction_data['reference_id']);
        } elseif ($transaction_data['tr_type'] == 'expense_bill_transaction' || $transaction_data['tr_type'] == 'subcontract_bill_transaction' || $transaction_data['tr_type'] == 'vehicle_bill_transaction') {
          $this->bills_management->calculate_bill_total($transaction_data['reference_id']);
        } elseif ($transaction_data['tr_type'] == 'salary_slip_transaction') {
          $this->bills_management->calculate_salary_slip_total($transaction_data['reference_id']);
        } elseif ($transaction_data['tr_type'] == 'vehicle_work_slip_transaction') {
          $this->bills_management->calculate_vehicle_work_slip_total($transaction_data['reference_id']);
        } elseif (isset($transaction_data['invoice_id'])) {
          $this->bills_management->calculate_invoice_payment_total($transaction_data['invoice_id']);
        } elseif ($transaction_data['tr_type'] == 'user_commission_transaction') {
          $this->bills_management->calculate_project_commission($transaction_data['tr_work_id']);
        }elseif ($transaction_data['tr_type'] == 'sales_invoice_transaction') {
          $this->bills_management->calculate_sales_invoice_total($transaction_data['reference_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 !!';
      }
    }
    echo json_encode($flash_data);
  }
  public function update_transaction()
  {
    $error_flag = 0;
    $redirect_url = $this->security->xss_clean($this->input->post('redirect_url'));

    $transaction_data['transaction_id'] = $this->security->xss_clean($this->input->post('transaction_id'));
    $reference_id = $this->security->xss_clean($this->input->post('reference_id'));
    $reference_type = $this->security->xss_clean($this->input->post('reference_type'));
    $transaction_details = $this->Account->select_account_transaction("ats.*", array("ats.transaction_id" => $transaction_data['transaction_id']), '', '', '', '', 'all', 'all','all')->row();

    $transaction_data['tr_type'] = $transaction_details->tr_type;
    // $transaction_data['reference_id'] = $reference_id;
    // $transaction_data['reference_type'] = $reference_type;

    $transaction_data['tr_description'] = ucwords(str_replace('_', ' ', $transaction_data['tr_type']));
    $transaction_data['tr_reference_no'] = $this->security->xss_clean($this->input->post('reference_no'));
    $transaction_data['tr_remarks'] = $this->security->xss_clean($this->input->post('tr_remarks'));
    $transaction_data['updated_date'] = date('Y-m-d H:i:s');
    $transaction_data['updated_by'] = $this->session->userdata('user_id');

    $file_error = 0;

    if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']["size"] > 0) {
      //          Check Allowed File Type
      // $file_type = $_FILES['uploaded_file']['type']; //returns the mimetype
      // $allowed = array("image/jpeg", "image/png");
      // if (!in_array($file_type, $allowed)) {
      //   $file_error = 1;
      // }
      //          Check Image Size (Only For Image Upload)
      // $imageinfo = getimagesize($_FILES['uploaded_file']['tmp_name']); //check image size
      // if ($imageinfo['mime'] != 'image/png' && $imageinfo['mime'] != 'image/jpeg') {
      //     $file_error = 1;
      // }
      //          Check Blacklist Extensions
      $blacklist = array(".php", ".phtml", ".php3", ".php4", ".html", ".htm", ".js");
      foreach ($blacklist as $item) {
        if (preg_match("/$item\$/i", $_FILES['uploaded_file']['name'])) {
          $file_error = 1;
        }
      }

      if ($file_error == 1) {
        $flash_data['flashdata_msg'] = 'Selected File Not allowed to Upload.';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'File Format Error !!';
      }

      //      File Upload
      $config['upload_path']   = 'uploads/transaction/';
      $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();
        $transaction_data['tr_file_attachment'] = $file_data['file_name'];
      }
    }

    if ($transaction_data['tr_type'] == 'client_payment_transaction') {
      $transaction_data['tr_other_data'] = $this->security->xss_clean($this->input->post('received_from'));
      $transaction_data['tr_credit_acc'] = $this->security->xss_clean($this->input->post('credit_acc'));
      $transaction_data['tr_debit_acc'] = 2; //Client Payment Receipts
      $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('received_amount'));
      $transaction_data['tr_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('received_date'))));
      $transaction_data['invoice_id'] = $this->security->xss_clean($this->input->post('invoice_id'));
      if ($transaction_data['invoice_id'] == 0) {
        //TAX
        $transaction_data['taxable_amount'] = $this->security->xss_clean($this->input->post('client_payment_taxable_amount'));
        $transaction_data['tax_percent'] = $this->security->xss_clean($this->input->post('client_payment_tax_percent'));
        $transaction_data['tax_amount'] = $this->security->xss_clean($this->input->post('client_payment_tax_amount'));
        $transaction_data['tax_inclusive'] = $this->security->xss_clean($this->input->post('tax_inclusive_edit'));
        if($this->input->post('work_id')){
          $transaction_data['reference_id'] = $this->security->xss_clean($this->input->post('work_id'));
        }
      } else {
        $transaction_data['reference_id'] = $this->Invoices->select_invoices("i.project_id",array("i.invoice_id"=>$transaction_data['invoice_id']))->row()->project_id;
        $transaction_data['taxable_amount'] = $this->security->xss_clean($this->input->post('received_amount'));
        $transaction_data['tax_percent'] = 0;
        $transaction_data['tax_amount'] = 0;
        $transaction_data['tax_inclusive'] = 0;
      }
    } elseif ($transaction_data['tr_type'] == 'income_receipt_transaction') {
      if($this->input->post('invoice_id')){
        $transaction_data['invoice_id'] = $this->security->xss_clean($this->input->post('invoice_id'));
      }
      $transaction_data['tr_work_id'] = $this->security->xss_clean($this->input->post('work'));
      $transaction_data['tr_description'] = $this->security->xss_clean($this->input->post('income_head'));
      $transaction_data['tr_credit_acc'] = $this->security->xss_clean($this->input->post('credit_acc'));
      $transaction_data['tr_debit_acc'] = 14; //Income Receipts
      $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('received_amount'));
      $transaction_data['tr_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('received_date'))));
    } elseif ($transaction_data['tr_type'] == 'loan_receipt_transaction') {
      $transaction_data['tr_credit_acc'] = $this->security->xss_clean($this->input->post('credit_acc'));
      $transaction_data['tr_debit_acc'] = 15; //Loan Receipts
      $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('received_amount'));
      $transaction_data['tr_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('received_date'))));
    } else {
      $transaction_data['reference_id'] = $reference_id;
      if ($reference_type == 'subcontract' && $transaction_data['tr_type'] == 'subcontract_advance_transaction' && $this->input->post('payment_move') && $this->input->post('payment_move') == '1') {
        // Check Selected Subcontrac Bill Balance
        // Change TR Type of Existing Payment
        $subcontract_bill_details = $this->Bills->select_bills("b.bill_balance_amount,b.bill_id", array("b.bill_id" => $this->input->post('move_bill_id')), '', '', '', 'all');
        if ($subcontract_bill_details->num_rows() == 1 && $subcontract_bill_details->row()->bill_balance_amount >= $this->input->post('paid_amount')) {
          $transaction_data['tr_type'] = 'subcontract_bill_transaction';
          $transaction_data['reference_id'] = $subcontract_bill_details->row()->bill_id;
          $transaction_data['reference_type'] = 'subcontract_bill';
          $transaction_data['tr_description'] = ucwords(str_replace('_', ' ', $transaction_data['tr_type']));
          $transaction_data['tr_remarks'] .= ' (Subcontract Advance Transaction)';
        } else {
          $flash_data['status'] = 0;
          $flash_data['flashdata_msg'] = 'Sorry.. Selected Bill Balance is Lesser Than Paid Amount. Please Check!';
          $flash_data['flashdata_type'] = 'error';
          $flash_data['alert_type'] = 'danger';
          $flash_data['flashdata_title'] = 'Bill Selected Error !!';
          $error_flag = 1;
        }
      }
      if ($transaction_data['tr_type'] == 'purchase_bill_transaction') {
        $transaction_data['tr_credit_acc'] = 5; //Supplier Payments
      } elseif ($transaction_data['tr_type'] == 'expense_bill_transaction' || $transaction_data['tr_type'] == 'subcontract_bill_transaction' || $transaction_data['tr_type'] == 'vehicle_bill_transaction') {
        $bill_details = $this->Bills->select_bills("b.bill_type,b.bill_credit_ac", array("b.bill_id" => $transaction_data['reference_id']), '', '', '', 'all')->row();
        $transaction_data['tr_credit_acc'] = $bill_details->bill_credit_ac;
      } elseif ($transaction_data['tr_type'] == 'subcontract_transaction') {
        $transaction_data['reference_type'] = "subcontract";
        $transaction_data['tr_type'] = "subcontract_advance_transaction";
        $transaction_data['tr_description'] = "Subcontract Advance Transaction";
      } elseif ($transaction_data['tr_type'] == 'salary_slip_transaction') {
        $transaction_data['tr_credit_acc'] = 10; //Salary Payments
      } elseif ($transaction_data['tr_type'] == 'loan_transaction') {
        $transaction_data['tr_credit_acc'] = 13; //Loan Payments
      } elseif ($transaction_data['tr_type'] == 'vehicle_work_slip_transaction') {
        $transaction_data['tr_credit_acc'] = 12; //Vehicle Payments
      } elseif ($transaction_data['tr_type'] == 'labour_insurance_fd_transaction') {
        $transaction_data['tr_credit_acc'] = 24; //Labour Payments
        $transaction_data['tr_other_data'] = $this->security->xss_clean($this->input->post('labour_payment_type_edit'));
      }

      if ($transaction_data['tr_type'] == 'salary_advance_transaction' || $transaction_data['tr_type'] == 'employee_bata_transaction') {
        $transaction_data['tr_work_id'] = $this->security->xss_clean($this->input->post('work_id'));
      }
      $transaction_data['tr_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('paid_date'))));
      if ($transaction_data['tr_type'] == 'user_payment_return_transaction') {
        $transaction_data['tr_credit_acc'] = $this->security->xss_clean($this->input->post('debit_acc'));
      } else {
        $transaction_data['tr_debit_acc'] = $this->security->xss_clean($this->input->post('debit_acc'));
      }
      $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('paid_amount'));
      $transaction_data['tr_mode'] = $this->security->xss_clean($this->input->post('payment_mode'));

      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'))));
      } else {
        $transaction_data['tr_reference_date'] = "";
      }
    }
    if ($error_flag == 0) {
      $transaction_result =  $this->Account->update_account_transaction($transaction_data);

      $flash_data['status'] = $transaction_result;
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = $transaction_data['tr_description'] . ' Details Updated Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';

        // Add User Activity
        $this->User->add_user_activity('Account Transaction', $transaction_data['transaction_id'], $transaction_data['tr_description'] . ' Updated');


        if ($transaction_data['tr_type'] == 'purchase_bill_transaction') {
          $this->bills_management->calculate_purchase_bill_total($transaction_data['reference_id']);
        } elseif ($transaction_data['tr_type'] == 'expense_bill_transaction' || $transaction_data['tr_type'] == 'subcontract_bill_transaction' || $transaction_data['tr_type'] == 'vehicle_bill_transaction') {
          $this->bills_management->calculate_bill_total($transaction_data['reference_id']);
        } elseif ($transaction_data['tr_type'] == 'salary_slip_transaction') {
          $this->bills_management->calculate_salary_slip_total($transaction_data['reference_id']);
        } elseif ($transaction_details->tr_type == 'salary_advance_transaction') {
          $this->bills_management->calculate_salary_slip_total('', $transaction_details->reference_id, $transaction_details->tr_other_data);
        } elseif ($transaction_data['tr_type'] == 'vehicle_work_slip_transaction') {
          $this->bills_management->calculate_vehicle_work_slip_total($transaction_data['reference_id']);
        } elseif (($transaction_data['tr_type'] == 'client_payment_transaction' || $transaction_data['tr_type'] == 'income_receipt_transaction') && isset($transaction_data['invoice_id'])) {
          $this->bills_management->calculate_invoice_payment_total($transaction_data['invoice_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 !!';
      }
    }

    echo json_encode($flash_data);
  }
  public function delete_transaction()
  {
    $redirect_url = $this->security->xss_clean($this->input->post('redirect_url'));

    $transaction_data['transaction_id'] = $this->security->xss_clean($this->input->post('transaction_id'));
    $transaction_data['delete_status'] = 1;
    // Select Detail
    $transaction_details = $this->Account->select_account_transaction("ats.*", array("ats.transaction_id" => $transaction_data['transaction_id']), '', '', '', '', $this->config->item('select_data_entry_approval'),$this->config->item('select_data_entry_approval'))->row();

    $transaction_result =  $this->Account->update_account_transaction($transaction_data);

    $flash_data['status'] = $transaction_result;
    if ($flash_data['status'] == 1) {

      $flash_data['flashdata_msg'] = $transaction_details->tr_description . ' Deleted Successfully!.';
      // Add User Activity
      $this->User->add_user_activity('Account Transaction', $transaction_data['transaction_id'], $transaction_details->tr_description . ' Deleted');

      if ($transaction_details->tr_type == 'purchase_bill_transaction') {
        $this->bills_management->calculate_purchase_bill_total($transaction_details->reference_id);
      } elseif ($transaction_details->tr_type == 'expense_bill_transaction' || $transaction_details->tr_type == 'subcontract_bill_transaction' || $transaction_details->tr_type == 'vehicle_bill_transaction') {
        $this->bills_management->calculate_bill_total($transaction_details->reference_id);
      } elseif ($transaction_details->tr_type == 'salary_slip_transaction') {
        $this->bills_management->calculate_salary_slip_total($transaction_details->reference_id);
      } elseif ($transaction_details->tr_type == 'salary_advance_transaction') {
        $this->bills_management->calculate_salary_slip_total('', $transaction_details->reference_id, $transaction_details->tr_other_data);
      } elseif ($transaction_details->tr_type == 'vehicle_work_slip_transaction') {
        $this->bills_management->calculate_vehicle_work_slip_total($transaction_details->reference_id);
      } elseif (($transaction_details->tr_type == 'client_payment_transaction' || $transaction_details->tr_type == 'income_receipt_transaction') && $transaction_details->invoice_id != 0) {
        $this->bills_management->calculate_invoice_payment_total($transaction_details->invoice_id);
      }elseif ($transaction_details->tr_type == 'sales_invoice_transaction') {
        $this->bills_management->calculate_sales_invoice_total($transaction_details->reference_id);
      }

      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }
  public function select_account_transactions($reference_type = '', $page_data_type = '', $param3 = "")
  {

    $select_columns = "";
    $json_data = array();
    $j = $sl_no = $total_bill_amount = $total_paid_amount = $total_balance_amount = 0;
    $data = array();
    if (isset($_POST['date']) && $_POST['date'] != '') {
      $date = array();
      $date = explode('-', $_POST['date']);
      $start_date = date('Y-m-d', strtotime($date[0]));
      $end_date = date('Y-m-d', strtotime($date[1]));
      $data["STR_TO_DATE(ats.tr_date,'%Y-%m-%d') <="] = $end_date;
      $data["STR_TO_DATE(ats.tr_date,'%Y-%m-%d') >="] = $start_date;
    }
    if (isset($_POST['user_id']) && $_POST['user_id'] != '' && $_POST['user_id'] != 'all') {
      // $data['ats.created_by'] = $_POST['user_id'];
      $account_heads_where['ah.acc_user_id'] = $_POST['user_id'];
      $account_heads_data	= $this->Account->select_account_heads("acc_head_id",$account_heads_where)->row();
      $this->db->where('(tr_credit_acc='.$account_heads_data->acc_head_id.' or tr_debit_acc='.$account_heads_data->acc_head_id.')');
    }
    if (isset($_POST['acc_head_id']) && $_POST['acc_head_id'] != '' && $_POST['acc_head_id'] != 'all') {
      $acc_head_id = $_POST['acc_head_id'];
      $account_heads_where['ah.acc_head_id'] = $_POST['acc_head_id'];
      $account_heads_data	= $this->Account->select_account_heads("acc_head_id,acc_user_id,acc_employee_id",$account_heads_where)->row();
      if ($reference_type == 'employee' && $account_heads_data->acc_employee_id!=0) {
        $this->db->where('(e.employee_id='.$account_heads_data->acc_employee_id.' or e2.employee_id='.$account_heads_data->acc_employee_id.' or tr_debit_acc='.$acc_head_id.')');
      }else{
        $this->db->where('(tr_credit_acc='.$acc_head_id.' or tr_debit_acc='.$acc_head_id.')');
      }
    }
    if ($this->config->item('user_data_access_view_all') != 1 && $reference_type == 'user_payment_receipt' && $reference_type == 'user_payment_return') {
      // $data['ats.created_by'] = $this->session->userdata('user_id');
      $account_heads_where['ah.acc_user_id'] = $_POST['user_id'];
      $account_heads_data	= $this->Account->select_account_heads("acc_head_id",$account_heads_where)->row();
      $this->db->where('(ats.created_by='.$this->session->userdata('user_id').' or tr_credit_acc='.$account_heads_data->acc_head_id.' or tr_debit_acc='.$account_heads_data->acc_head_id.')');
    }elseif ($this->config->item('user_data_access_view_all') != 1 ){
      $account_heads_where['ah.acc_user_id'] = $this->session->userdata('user_id');
      $account_heads_data	= $this->Account->select_account_heads("acc_head_id",$account_heads_where)->row();
      $this->db->where('(ats.created_by='.$this->session->userdata('user_id').' or tr_credit_acc='.$account_heads_data->acc_head_id.' or tr_debit_acc='.$account_heads_data->acc_head_id.')');
    }
    if ($reference_type == 'salary_slip' && $this->session->userdata('user_role') == 'general_manager' && $this->config->item('User_general_manager_hr_data_view_all') == 0) {
      $data['ats.created_by'] = $this->session->userdata('user_id');
    }
    if (isset($_POST['created_by']) && $_POST['created_by'] != '' && $_POST['created_by'] != 'all') {
      $data['ats.created_by'] = $_POST['created_by'];
    }
    if (isset($_POST['start_date']) && $_POST['start_date'] != '' && $_POST['start_date'] != 'all') {
      $data['ats.tr_date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if (isset($_POST['end_date']) && $_POST['end_date'] != '' && $_POST['end_date'] != 'all') {
      $data['ats.tr_date <='] = date('Y-m-d', strtotime($_POST['end_date']));
    }
    if ($reference_type == 'subcontract_bill' || $reference_type == 'expense_bill' || $reference_type == 'vehicle_bill') {
      if(isset($_POST['bill_supplier_id']) && $_POST['bill_supplier_id']!='' && $_POST['bill_supplier_id']!='all'){
        $data['b.bill_supplier_id'] = $_POST['bill_supplier_id'];
      }
      if (isset($_POST['bill_id']) && $_POST['bill_id'] != '' && $_POST['bill_id'] != 'all') {
        $data['b.bill_id'] = $_POST['bill_id'];
      }
      if (isset($_POST['purchase_id']) && $_POST['purchase_id'] != '' && $_POST['purchase_id'] != 'all') {
        $data['b.purchase_id'] = $_POST['purchase_id'];
      }
      if (isset($_POST['contract_id']) && $_POST['contract_id'] != '' && $_POST['contract_id'] != 'all') {
        $data['b.subcontract_id'] = $_POST['contract_id'];
      }
      if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
        $data['b.work_id'] = $_POST['work'];
      }
      if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
        $this->db->where_in('b.work_id',explode(',',$_POST['work_ids']));
      }
      if (isset($_POST['expense_head']) && $_POST['expense_head'] != '' && $_POST['expense_head'] != 'all') {
        $data['b.bill_credit_ac'] = $_POST['expense_head'];
      }
      if ($reference_type == 'subcontract_bill' && isset($_POST['work_type']) && $_POST['work_type'] != '' && $_POST['work_type'] != 'all') {
        $work_type = $_POST['work_type'];
        $this->db->where("FIND_IN_SET($work_type, sc.work_type_id)");
      }
      if ($this->session->userdata('user_role') == 'supervisor' && $reference_type == 'subcontract_bill') {
        //          Select Assigned Works Only
        $supervisor_id = $this->session->userdata('user_id');
        $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
      }
      $select_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,c.contractor_name";
    } elseif ($reference_type == 'subcontract_transactions') {
      // Subcontract Advance & Bill Payment
      if (isset($_POST['bill_id']) && $_POST['bill_id'] != '' && $_POST['bill_id'] != 'all') {
        $data['b.bill_id'] = $_POST['bill_id'];
      }
      if (isset($_POST['stage_id']) && $_POST['stage_id'] != '' && $_POST['stage_id'] != 'all') {
        $data['ats.tr_project_stage_id'] = $_POST['stage_id'];
      }
      if (isset($_POST['contract_id']) && $_POST['contract_id'] != '' && $_POST['contract_id'] != 'all') {
        $contract_id = $_POST['contract_id'];
        $this->db->where("((ats.reference_type='subcontract_bill' and b.subcontract_id=$contract_id) or (ats.reference_type='subcontract' and sc2.contract_id=$contract_id))");
      }
      if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
        $work_id = $_POST['work'];
        $this->db->where("((ats.reference_type='subcontract_bill' and b.work_id=$work_id) or (ats.reference_type='subcontract' and sc2.work_id=$work_id))");
      }
      if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
        $work_ids = $_POST['work_ids'];
        $this->db->where("((ats.reference_type='subcontract_bill' and b.work_id IN ('$work_ids')) or (ats.reference_type='subcontract' and sc2.work_id IN ('$work_ids')))");
      }
      if (isset($_POST['branch_id']) && $_POST['branch_id'] != '' && $_POST['branch_id'] != 'all') {
        $data['ats.branch_id'] = $_POST['branch_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) or FIND_IN_SET($supervisor_id, wc2.assigned_users))");
      }
      if ($reference_type == 'subcontract_bill' && isset($_POST['work_type']) && $_POST['work_type'] != '' && $_POST['work_type'] != 'all') {
        $work_type = $_POST['work_type'];
        $this->db->where("FIND_IN_SET($work_type, sc.work_type_id)");
      }
      if (isset($_POST['contractor']) && $_POST['contractor'] != '' && $_POST['contractor'] != 'all') {
        $contractor = $_POST['contractor'];
        $this->db->where("((ats.reference_type='subcontract_bill' and c.contractor_id=$contractor) or (ats.reference_type='subcontract' and c2.contractor_id=$contractor))");
      }
      $select_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,sc2.contract_id as contract_id_2,wc2.work_name as work_name_2,wc2.work_id as work_id_2,sc2.sub_work_name as sub_work_name_2,sc2.contractor as contractor_2,c.contractor_name,c2.contractor_name as contractor_name_2";
    } elseif ($reference_type == 'purchase_order') {

      if (isset($_POST['order_id']) && $_POST['order_id'] != '' && $_POST['order_id'] != 'all') {
        $data['po.order_id'] = $_POST['order_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['po.project_stage_id'] = $_POST['stage_id'];
      }
      if (isset($_POST['location_id']) && $_POST['location_id'] != '' && $_POST['location_id'] != 'all') {
        $data['sl.location_id'] = $_POST['location_id'];
      }
      if (isset($_POST['supplier']) && $_POST['supplier'] != '' && $_POST['supplier'] != 'all') {
        $data['po.supplier_id'] = $_POST['supplier'];
      }
      if ($param3 == 'bill_not_created') {
        // $data['po.purchase_bill_id'] = 0;
      }
      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)");
      }
      $select_columns = "po.purchase_bill_id,po.order_id,po.reference_no,s.supplier_name,wc.work_name,sl.work_id as location_work_id,sl.location_name,sl.work_id,sl.location_type,sl.location_id";
    } elseif ($reference_type == 'purchase_bill') {

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

      if (isset($_POST['purchase_id']) && $_POST['purchase_id'] != '' && $_POST['purchase_id'] != 'all') {
        $data['p.purchase_id'] = $_POST['purchase_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['ats.tr_project_stage_id'] = $_POST['stage_id'];
      }
      if (isset($_POST['location_id']) && $_POST['location_id'] != '' && $_POST['location_id'] != 'all') {
        $data['sl.location_id'] = $_POST['location_id'];
      }
      if (isset($_POST['supplier']) && $_POST['supplier'] != '' && $_POST['supplier'] != 'all') {
        $data['p.supplier_id'] = $_POST['supplier'];
      }
      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)");
      }
      $select_columns = "p.purchase_order_id,p.purchase_id,p.bill_invoice_no,s.supplier_name,wc.work_name,sl.work_id as location_work_id,sl.location_name,sl.work_id,sl.location_type,sl.location_id";
    } elseif ($reference_type == 'labour' || $reference_type == 'labour_insurance_fd') {

      if (isset($_POST['labour']) && $_POST['labour'] != '' && $_POST['labour'] != 'all') {
        $data['l.labour_id'] = $_POST['labour'];
      }
      if (isset($_POST['work_type']) && $_POST['work_type'] != '' && $_POST['work_type'] != 'all') {
        $data['l.work_type'] = $_POST['work_type'];
      }
      if (isset($_POST['labour_group_head']) && $_POST['labour_group_head'] != '' && $_POST['labour_group_head'] != 'all') {
        $data['l.labour_group'] = $this->Labour->select_labours("l.labour_group", array("l.labour_id" => $_POST['labour_group_head']))->row()->labour_group;
      }

      if (isset($_POST['start_date']) && $_POST['start_date'] != '' && $_POST['start_date'] != 'all') {
        $start_date = date('Y-m-d', strtotime($_POST['start_date']));
        $this->db->where("ats.tr_date >=", $start_date);
        $this->db->where("ats.tr_date !=", '0000-00-00');
      }
      if (isset($_POST['end_date']) && $_POST['end_date'] != '' && $_POST['end_date'] != 'all') {
        $end_date = date('Y-m-d', strtotime($_POST['end_date']));
        $this->db->where("ats.tr_date <=", $end_date);
        $this->db->where("ats.tr_date !=", '0000-00-00');
      }

      $select_columns = "l.labour_name,wt.type_name,l.labour_group,l.labour_id";
    } elseif ($reference_type == 'supplier') {

      if (isset($_POST['supplier_id']) && $_POST['supplier_id'] != '' && $_POST['supplier_id'] != 'all') {
        $data['s.supplier_id'] = $_POST['supplier_id'];
      }
      $select_columns = "s.supplier_name,s.supplier_id,s.supplier_type,s.supplier_address,s.supplier_phone";
    } elseif ($reference_type == 'loan') {

      if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
        $data['l.work_id'] = $_POST['work'];
      }
      if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
        $this->db->where_in('l.work_id',explode(',',$_POST['work_ids']));
      }
      if (isset($_POST['loan_provider']) && $_POST['loan_provider'] != '' && $_POST['loan_provider'] != 'all') {
        $data['l.provider_id'] = $_POST['loan_provider'];
      }
      if (isset($_POST['loan_type']) && $_POST['loan_type'] != '' && $_POST['loan_type'] != 'all') {
        $data['l.loan_type'] = $_POST['loan_type'];
      }
      $select_columns = "l.loan_type,l.loan_id,l.loan_title,l.description,lp.loan_provider_name,wc.work_name,l.work_id";
    } elseif ($reference_type == 'tool') {
      if (isset($_POST['type']) && $_POST['type'] != '' && $_POST['type'] != 'all') {
        $data['ats.reference_type'] = "tool_" . $_POST['type'];
      }
      if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
        $workid = $_POST['work'];
        $this->db->where("(((ats.reference_type='tool_rent' and tr.rented_to='$workid') or (ats.reference_type='tool_transfer' and tt.transfer_to='$workid')))");
      }
      if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
        $work_ids = $_POST['work_ids'];
        $this->db->where("(((ats.reference_type='tool_rent' and tr.rented_to IN('$work_ids')) or (ats.reference_type='tool_transfer' and tt.transfer_to IN('$work_ids'))))");
      }
      $select_columns = "t.tool_id,t.name,t.description,t.tool_type,tc.cat_name,wc.work_name as rented_to_location,tr.rented_from,t2.tool_id as tool_id_2,t2.name as name_2,t2.description as description_2,t2.tool_type as tool_type_2,tc2.cat_name as cat_name_2,wc2.work_name as transfer_to_location,tt.transfer_from,";
    } elseif ($reference_type == 'salary_slip') {
      if (isset($_POST['employee']) && $_POST['employee'] != '' && $_POST['employee'] != 'all') {
        $data['ss.employee_id'] = $_POST['employee'];
      }
      if (isset($_POST['start_month']) && $_POST['start_month'] != '') {
        $start_date = date('Y-m', strtotime($_POST['start_month']));
        $data["ss.month >="] = $start_date . "-01";
      }
      if (isset($_POST['end_month']) && $_POST['end_month'] != '') {
        $end_date = date('Y-m', strtotime($_POST['end_month']));
        $data["ss.month <="] = $end_date."-".date('t',strtotime($_POST['end_month']));
      }
      if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
        $data['ss.work_id'] = $_POST['work'];
      }
      if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
        $this->db->where_in('ss.work_id',explode(',',$_POST['work_ids']));
      }
      $select_columns = "ss.month,ss.salary_id,e.employee_name,e.employee_id,e.user_designation";
    } elseif ($reference_type == 'employee') {
      if (isset($_POST['date']) && $_POST['date'] != '') {
        $date = array();
        $date = explode('-', $_POST['date']);
        $start_date = date('Y-m-d', strtotime($date[0]));
        $end_date = date('Y-m-d', strtotime($date[1]));
        $data["STR_TO_DATE(ats.tr_date,'%Y-%m-%d') <="] = $end_date;
        $data["STR_TO_DATE(ats.tr_date,'%Y-%m-%d') >="] = $start_date;
      }
      if (isset($_POST['employee']) && $_POST['employee'] != '' && $_POST['employee'] != 'all') {
        $this->db->where("(ss.employee_id='" . $_POST['employee'] . "' or e2.employee_id='" . $_POST['employee'] . "')");
      }
      if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
        $this->db->where("((ats.tr_type='salary_slip_transaction' and ss.work_id='" . $_POST['work'] . "') or (ats.tr_type='salary_advance_transaction' and ats.tr_work_id='" . $_POST['work'] . "') or (ats.tr_type='employee_bata_transaction' and ats.tr_work_id='" . $_POST['work'] . "'))");
      }
      if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
        $work_ids = $_POST['work_ids'];
        $this->db->where("((ats.tr_type='salary_slip_transaction' and ss.work_id IN('$work_ids')) or (ats.tr_type='salary_advance_transaction' and ats.tr_work_id IN('$work_ids')) or (ats.tr_type='employee_bata_transaction' and ats.tr_work_id IN('$work_ids')))");
      }
      $select_columns = "ss.work_id,ss.month,ss.salary_id,e.employee_name,e.employee_id,e.user_designation,ats.tr_type,e2.employee_name as employee_name_2,e2.employee_id as employee_id_2,e2.user_designation as user_designation_2,wc.work_name as salary_project_name,wc2.work_name as expense_under_project";
    } elseif ($reference_type == 'vehicle_work_slip') {
      if (isset($_POST['vehicle_id']) && $_POST['vehicle_id'] != '' && $_POST['vehicle_id'] != 'all') {
        $data['vws.vehicle_id'] = $_POST['vehicle_id'];
      }
      if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
        $data['vws.vehicle_work_id'] = $_POST['work'];
      }
      if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
        $this->db->where_in('vws.vehicle_work_id',explode(',',$_POST['work_ids']));
      }
      if (isset($_POST['consignee']) && $_POST['consignee'] != '' && $_POST['consignee'] != 'all') {
        $data['v.consignee'] = $_POST['consignee'];
      }
      $select_columns = "v.id,v.vehicle_name,v.vehicle_no,vws.work_slip_id,vws.worked_date,vc.consignee_name";
    } elseif ($reference_type == 'vehicle_renewal' || $reference_type == 'vehicle_payment') {
      if (isset($_POST['vehicle_id']) && $_POST['vehicle_id'] != '' && $_POST['vehicle_id'] != 'all') {
        $data['v.id'] = $_POST['vehicle_id'];
      }
      if (isset($_POST['consignee']) && $_POST['consignee'] != '' && $_POST['consignee'] != 'all') {
        $data['v.consignee'] = $_POST['consignee'];
      }
      $select_columns = "v.*,vc.consignee_name";
    } elseif ($reference_type == 'user_payment_receipt') {
      if (isset($_POST['acc_head_id']) && $_POST['acc_head_id'] != '' && $_POST['acc_head_id'] != 'all') {
        $data['ats.reference_id'] = $_POST['acc_head_id'];
      }
      if (isset($_POST['user']) && $_POST['user'] != '' && $_POST['user'] != 'all') {
        $data['u3.user_id'] = $_POST['user'];
      }
      if (isset($_POST['employee']) && $_POST['employee'] != '' && $_POST['employee'] != 'all') {
        $data['e.employee_id'] = $_POST['employee'];
      }
      if ($this->session->userdata('user_role') == 'auditor' || $this->session->userdata('user_role') == 'admin' || $this->session->userdata('user_role') == 'admin' || $this->session->userdata('user_role') == 'accounts_manager' || ($this->session->userdata('user_role') == 'general_manager' && $this->config->item('User_general_manager_user_payments_enable') == 1)) {
      } else {
        $data['u3.user_id'] = $this->session->userdata('user_id');
      }
      $select_columns = "ah2.acc_head_id,u3.user_id,u3.user_alias,u3.user_role,ur.role_title,e.employee_id,e.employee_name,ed.department_name";
    } elseif ($reference_type == 'user_payment_return') {
      if (isset($_POST['acc_head_id']) && $_POST['acc_head_id'] != '' && $_POST['acc_head_id'] != 'all') {
        $data['ats.reference_id'] = $_POST['acc_head_id'];
      }
      if (isset($_POST['employee']) && $_POST['employee'] != '' && $_POST['employee'] != 'all') {
        $data['e2.employee_id'] = $_POST['employee'];
      }
      if (isset($_POST['user']) && $_POST['user'] != '' && $_POST['user'] != 'all') {
        $data['u4.user_id'] = $_POST['user'];
      }
      if ($this->session->userdata('user_role') == 'auditor' || $this->session->userdata('user_role') == 'admin' || $this->session->userdata('user_role') == 'admin' || $this->session->userdata('user_role') == 'accounts_manager' || ($this->session->userdata('user_role') == 'general_manager' && $this->config->item('User_general_manager_user_payments_enable') == 1)) {
      } else {
        $data['u4.user_id'] = $this->session->userdata('user_id');
      }
      $select_columns = "ah1.acc_head_id,u4.user_id,u4.user_alias,u4.user_role,ur.role_title,e2.employee_id,e2.employee_name,ed.department_name";
    } elseif ($reference_type == 'user_commission') {

      if (isset($_POST['work_id']) && $_POST['work_id'] != '' && $_POST['work_id'] != 'all') {
        $data['ats.tr_work_id'] = $_POST['work_id'];
      }
      if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
        $this->db->where_in('ats.tr_work_id',explode(',',$_POST['work_ids']));
      }
      if (isset($_POST['user']) && $_POST['user'] != '' && $_POST['user'] != 'all') {
        $data['u3.user_id'] = $_POST['user'];
      }
      if ($this->session->userdata('user_role') != 'admin' && $this->session->userdata('user_role') != 'madmin') {
        $data['u3.user_id'] = $this->session->userdata('user_id');
      }
      $select_columns = "u3.user_id,u3.user_alias,u3.user_role,ur.role_title,wc.work_name";
    } elseif ($reference_type == 'travel_allowance') {

      if (isset($_POST['user']) && $_POST['user'] != '' && $_POST['user'] != 'all') {
        $data['u3.user_id'] = $_POST['user'];
      }
      if ($this->session->userdata('user_role') != 'admin' && $this->session->userdata('user_role') != 'general_manager') {
        $data['u3.user_id'] = $this->session->userdata('user_id');
      }
      $select_columns = "u3.user_id,u3.user_alias,u3.user_role,ur.role_title,ta.*";
    }
    if ($reference_type == 'user_payment_receipt' || $reference_type == 'user_commission' || $reference_type == 'user_commission') {
      //   if(isset($_POST['acc_user_id']) && $_POST['acc_user_id']!='' && $_POST['acc_user_id']!='all'){
      //   $data['ah2.acc_user_id'] = $_POST['acc_user_id'];
      // }
    }else{
      if(isset($_POST['acc_user_id']) && $_POST['acc_user_id']!='' && $_POST['acc_user_id']!='all'){
        $data['ah1.acc_user_id'] = $_POST['acc_user_id'];
      }
    }
    if ($reference_type == 'subcontract_transactions') {
      $this->db->where("(ats.reference_type='subcontract_bill' or ats.reference_type='subcontract')");
      $this->db->where("(ats.tr_type='subcontract_bill_transaction' or ats.tr_type='subcontract_advance_transaction')");
    } elseif ($reference_type == 'employee') {
      $this->db->where("(ats.reference_type='salary_slip' or ats.reference_type='employee')");
    } elseif ($reference_type == 'user_payment_receipt' || $reference_type == 'user_payment_return') {
      $data['ats.reference_type'] = 'user_account_head';
      $data['ats.tr_type'] = $reference_type . "_transaction";
    } elseif ($reference_type == 'user_commission') {
      $data['ats.reference_type'] = 'user_account_head';
      $data['ats.tr_type'] = $reference_type . "_transaction";
    } elseif ($reference_type == 'supplier') {
      if ($param3 == 'all') {
        $this->db->where("(ats.tr_type='supplier_advance_transaction' or ats.tr_type='supplier_opbalance_transaction')");
      } else {
        $data['ats.tr_type'] = "supplier_advance_transaction";
      }
    } elseif ($reference_type == 'tool') {
      $data['ats.tr_type'] = "tool_payment_transaction";
    } elseif ($reference_type == 'vehicle_renewal' || $reference_type == 'vehicle_payment') {
      $data['ats.reference_type'] = 'vehicle';
      if($reference_type == 'vehicle_renewal'){
        $data['ats.tr_type'] = $reference_type . "_transaction";
      }else{
        $data['ats.tr_type'] = "vehicle_opbalance_transaction";
      }
    } elseif ($reference_type == 'labour_insurance_fd') {
      $data['ats.reference_type'] = 'labour';
      $data['ats.tr_type'] = $reference_type . "_transaction";
    } elseif ($reference_type == 'loan') {
      $data['ats.reference_type'] = 'loan';
      if (isset($_POST['loan_type']) && $_POST['loan_type'] == 'receivable') {
        $data['ats.tr_type'] = "loan_receipt_transaction";
      } elseif (isset($_POST['loan_type']) && $_POST['loan_type'] == 'payable') {
        $data['ats.tr_type'] = "loan_transaction";
      } else {
        $this->db->where("((l.loan_type='receivable' and ats.tr_type='loan_receipt_transaction') or (l.loan_type='payable' and ats.tr_type='loan_transaction'))");
      }
    } else {
      $data['ats.reference_type'] = $reference_type;
      $data['ats.tr_type'] = $reference_type . "_transaction";
    }
    $entry_approval = $entry_approval_2 = $join_table_entry_approval = 1;
    if ($this->config->item('User_enable_data_entry_approval') == 1) { //webapp users approval
      $entry_approval = $entry_approval_2 = 'all';
      $join_table_entry_approval = 'all';
    }
    if ($page_data_type == 'approval_entries') {
      $entry_approval = 'all';
      $data['u1.user_role >'] = 2;
      if (isset($_POST['approval_status']) && $_POST['approval_status'] != '' && $_POST['approval_status'] != 'all') {
        $entry_approval = $_POST['approval_status'];
        $join_table_entry_approval = 'all';
      }
    }
    if ($page_data_type == 'approval_entries_2_level') {
      $entry_approval_2 = 'all';
      $data['u1.user_role >'] = 2;
      $data['ats.tr_entry_approval_status'] =1;
      if (isset($_POST['approval_status']) && $_POST['approval_status'] != '' && $_POST['approval_status'] != 'all') {
        $entry_approval_2 = $_POST['approval_status'];
        $join_table_entry_approval = 'all';
      }
    }

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


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

      if ($reference_type == 'subcontract_bill' || $reference_type == 'expense_bill' || $reference_type == 'vehicle_bill') {
        $bill_type = $reference_type;
        $bill_id = $row->bill_id;
        $bill_id_link = '<a id="m_quick_sidebar_toggle" data-type="bill_profile" data-bill-type="' . $reference_type . '" data-id="' . $row->bill_id . '" href="javascript:;">#' . $row->bill_id . '</a>';
        $bill_no = "Bill No: " . $row->bill_no;
        $bill_no .= ", Bill ID #" . $row->reference_id;
        if ($row->bill_consignee_name != '') {
          $consignee = $row->bill_consignee_name;
        } elseif ($row->contractor_name != '') {
          $consignee = $row->contractor_name;
        } elseif ($reference_type == 'subcontract_bill') {
          $consignee = $row->contractor;
        } else {
          $consignee = '';
        }

        if ($row->work_id != 0) {
          $project = '<a href="' . base_url() . 'work/profile/' . $row->work_id . '">' . $row->work_name . '</a>';
        } else {
          $project = '';
        }
        $form_type = $reference_type;
        $transaction_type = $reference_type . "_transaction";
      } elseif ($reference_type == 'subcontract_transactions') {
        // Subcontract Advance & Bill Payment
        $bill_type = $row->reference_type;
        if ($bill_type == 'subcontract_bill') {
          $bill_id = $row->bill_id;
          $bill_id_link = '<a id="m_quick_sidebar_toggle" data-type="bill_profile" data-bill-type="' . $reference_type . '" data-id="' . $row->bill_id . '" href="javascript:;">#' . $row->bill_id . '</a>';
          $bill_no = "Bill No: " . $row->bill_no;
          if ($row->reference_type == 'subcontract_bill') {
            $bill_no .= ", Bill ID #" . $row->reference_id;
          }
          if ($row->bill_consignee_name != '') {
            $consignee = $row->bill_consignee_name;
          } elseif ($row->contractor_name != '') {
            $consignee = $row->contractor_name;
          } else {
            $consignee = '';
          }
          if ($row->work_id != 0) {
            $project = '<a href="' . base_url() . 'work/profile/' . $row->work_id . '">' . $row->work_name . '</a>';
          } else {
            $project = '';
          }
          $form_type = $bill_type;
          $transaction_type = $bill_type . "_transaction";
        } elseif ($bill_type == 'subcontract') {
          $bill_id = $row->contract_id_2;
          $bill_id_link = '';
          $bill_no = '';
          if ($row->reference_type == 'subcontract_bill') {
            $bill_no .= "Bill ID #" . $row->reference_id;
          }

          if ($row->contractor_name_2 != '') {
            $consignee = $row->contractor_name_2;
          } elseif ($row->contractor_2 != '') {
            $consignee = $row->contractor_2;
          } else {
            $consignee = $row->bill_consignee_name;
          }
          if ($row->work_id_2 != 0) {
            $project = '<a href="' . base_url() . 'work/profile/' . $row->work_id_2 . '">' . $row->work_name_2 . '</a>';
          } else {
            $project = '';
          }
          $form_type = 'subcontract_advance';
          $transaction_type = "subcontract_advance_transaction";
        }
        $tr_display_type = $reference_type;
      } elseif ($reference_type == 'purchase_order') {
        $bill_type = 'purchase_order';
        $bill_id = $row->order_id;
        $bill_id_link = '<a href="' . base_url() . 'purchase_order/profile/' . $row->order_id . '">#' . $row->order_id . '</a>';
        $bill_no = $row->reference_no;
        $consignee = $row->supplier_name;
        if ($row->location_type == 'work_site') {
          $project = '<a href="' . base_url() . 'work/profile/' . $row->location_work_id . '">' . $row->location_name . '<br/>[Work Site]</a>';
        } elseif ($row->location_type == 'ware_house') {
          $project = '<a href="' . base_url() . 'stock/locations/profile/' . $row->location_id . '">' . $row->location_name . '<br/>[Warehouse]</a>';
        }
        $form_type = $reference_type;
        $transaction_type = $reference_type . "_transaction";
      } elseif ($reference_type == 'purchase_bill') {
        $bill_type = 'purchase_bill';
        $bill_id = $row->purchase_id;
        $bill_id_link = '<a href="' . base_url() . 'purchases/profile/' . $row->purchase_id . '">#' . $row->purchase_id . '</a>';
        $bill_no = $row->bill_invoice_no;
        $consignee = $row->supplier_name;
        if ($row->location_type == 'work_site') {
          $project = '<a href="' . base_url() . 'work/profile/' . $row->location_work_id . '">' . $row->location_name . '<br/>[Work Site]</a>';
        } elseif ($row->location_type == 'ware_house') {
          $project = '<a href="' . base_url() . 'stock/locations/profile/' . $row->location_id . '">' . $row->location_name . '<br/>[Warehouse]</a>';
        }
        $form_type = $reference_type;
        $transaction_type = $reference_type . "_transaction";
      } elseif ($reference_type == 'labour' || $reference_type == 'labour_insurance_fd') {
        $bill_id = $row->labour_id;
        $bill_id_link = "";
        $bill_no = "";
        $project = '<a href="' . base_url() . 'labours/profile/' . $row->labour_id . '">' . $row->labour_name . '</a>';
        if ($reference_type == 'labour_insurance_fd') {
          $bill_type = 'labour_insurance_fd';
          $form_type = "insurance_fd";
          $consignee = ucwords($row->tr_other_data);
        } else {
          $bill_type = 'labour';
          $form_type = "labour_wage";
          $consignee = "";
        }
        $transaction_type = $reference_type . "_transaction";
      } elseif ($reference_type == 'loan') {
        $bill_type = 'loan';
        $bill_id = $row->loan_id;
        $bill_id_link = "";
        $bill_no = "";
        $consignee = "";
        // if($row->work_id!=0){
        //   $project = '<a href="' . base_url() . 'work/profile/' . $row->work_id . '">' . $row->work_name . '</a>';
        // }else{
        //   $project = "";
        // }
        $project = $row->loan_title;
        $form_type = "loan";
        $transaction_type = $reference_type . "_transaction";
      } elseif ($reference_type == 'tool') {
        $bill_type = $row->reference_type;
        $bill_id = $row->reference_id;
        $bill_id_link = "";
        $bill_no = "";
        $consignee = "";
        // if($row->work_id!=0){
        //   $project = '<a href="' . base_url() . 'work/profile/' . $row->work_id . '">' . $row->work_name . '</a>';
        // }else{
        //   $project = "";
        // }
        if ($row->reference_type == 'tool_transfer') {
          $project = ucfirst($row->name_2) . ' [' . $row->cat_name_2 . ']';
          $project .= "<br/>(Own)";
        } elseif ($row->reference_type == 'tool_rent') {
          $project = ucfirst($row->name) . ' [' . $row->cat_name . ']';
          $project .= "<br/>(Rent)";
        }
        $form_type = "tool";
        $transaction_type = "tool_payment_transaction";
      } elseif ($reference_type == 'supplier') {
        $bill_type = 'advance';
        $bill_id = $row->supplier_id;
        if ($row->tr_type == 'supplier_opbalance_transaction') {
          $bill_id_link = "Opening Balance Payment";
        } elseif ($row->tr_type == 'supplier_advance_transaction') {
          $bill_id_link = "Advance Payment";
        } else {
          $bill_id_link = "";
        }
        $bill_no = "";
        $consignee = $row->supplier_name;
        $project = "";
        $form_type = "";
        $transaction_type = $reference_type . "_transaction";
      } elseif ($reference_type == 'salary_slip') {
        $bill_type = 'salary_slip';
        $bill_id = $row->salary_id;
        $bill_id_link = "#" . $row->salary_id;
        $bill_no = date('M Y', strtotime($row->month));
        $consignee = "";
        // $project = '<a href="' . base_url() . 'employees/profile/' . $row->employee_id . '">' . $row->employee_name . '</a>';
        $project = $row->employee_name;
        $form_type = "salary_slip";
        $transaction_type = $reference_type . "_transaction";
      } elseif ($reference_type == 'employee') {
        $consignee = $expense_under = '';
        // $project = '<a href="' . base_url() . 'employees/profile/' . $row->employee_id . '">' . $row->employee_name . '</a>';
        if ($row->reference_type == 'salary_slip') {
          if ($row->work_id == 0) {
            $expense_under = 'Office Expense';
          } else {
            $expense_under = $row->salary_project_name;
          }
          $bill_no = date('M Y', strtotime($row->month));
          $project = $row->employee_name;
          $form_type = "salary_slip";
          $bill_type = 'salary_slip';
          $bill_id = $row->salary_id;
          $bill_id_link = "#" . $row->salary_id;
        } else {
          if ($row->tr_type == 'salary_advance_transaction' || $row->tr_type == 'employee_bata_transaction') {
            if ($row->tr_work_id == 0) {
              $expense_under = 'Office Expense';
            } else {
              $expense_under = $row->expense_under_project;
            }
          }
          if($row->tr_type=="salary_advance_transaction" || $row->tr_type == 'employee_bata_transaction'){
            $bill_no = date('M Y',strtotime($row->tr_other_data));
          }else{
            $bill_no = '';
          }
          $project = $row->employee_name_2;
          $form_type = "employee";
          $bill_type = 'employee';
          $bill_id = $row->reference_id;
          $bill_id_link = "";
        }
        $transaction_type = $reference_type . "_transaction";
      } elseif ($reference_type == 'vehicle_work_slip') {
        $bill_type = 'vehicle_work_slip';
        $bill_id = $row->work_slip_id;
        $bill_id_link = "#" . $row->work_slip_id;
        $bill_no = date('d-m-Y', strtotime($row->worked_date));
        $consignee = '';
        $project = '<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name . " : " . $row->vehicle_no . '</a>';
        $form_type = "vehicle_work_slip";
        $transaction_type = $reference_type . "_transaction";
      } elseif ($reference_type == 'vehicle_renewal' || $reference_type == 'vehicle_payment') {
        $bill_id = $row->id;
        if($reference_type == 'vehicle_renewal'){
          $bill_id_link = $row->tr_other_data;
          $bill_type = 'vehicle_renewal';
        }else{
          $bill_id_link = 'Towards OP Balance';
          $bill_type = 'vehicle_opbalance';
        }
        $bill_no = '';
        $consignee = $row->consignee_name;
        $project = '<a href="' . base_url() . 'vehicles/profile/' . $row->id . '">' . $row->vehicle_name . " : " . $row->vehicle_no . '</a>';
        if($reference_type == 'vehicle_payment'){
          $form_type = "vehicle_op_balance";
        }else{
          $form_type = "vehicle_renewal";
        }
        $transaction_type = $reference_type . "_transaction";
      } elseif ($reference_type == 'user_payment_receipt' || $reference_type == 'user_payment_return') {
        $bill_type = $reference_type;
        $bill_id = $row->reference_id;
        $bill_id_link = "";
        $bill_no = "";
        $consignee = "";
        // $project = '<a href="' . base_url() . 'employee/profile/' . $row->employee_id . '">' . $row->employee_name . '</a>';
        $project = $row->employee_name;
        $form_type = "user_payment";
        $transaction_type = $reference_type . "_transaction";
      } elseif ($reference_type == 'user_commission') {
        $bill_type = $reference_type;
        $bill_id = $row->user_id;
        $bill_id_link = "";
        $bill_no = "";
        $consignee = "";
        $project = '<a href="' . base_url() . 'user/profile/' . $row->user_id . '">' . $row->user_alias . '</a>';
        $form_type = "user_payment";
        $transaction_type = $reference_type . "_transaction";
      } elseif ($reference_type == 'travel_allowance') {
        $bill_type = $reference_type;
        $bill_id = $row->user_id;
        $bill_id_link = "";
        $bill_no = "";
        $consignee = "";
        $project = '<a href="' . base_url() . 'user/profile/' . $row->user_id . '">' . $row->user_alias . '</a>';
        $form_type = "travel_allowance";
        $transaction_type = $reference_type . "_transaction";
      }

      if ($this->session->userdata('user_role') == 'admin' || $this->session->userdata('user_role') == 'accounts_manager' ||  $this->session->userdata('user_role') == 'madmin' || $this->session->userdata('user_role') == 'general_manager' || ($this->session->userdata('user_role') == 'supervisor' && $this->session->userdata('user_id') == $row->created_by)) {
        // Editing Disabled for Purchase Bill Payment Copied From Purchase Order
        $transaction_edit = 0;
        if ($row->reference_type == 'purchase_bill' && $row->tr_type == 'purchase_bill_transaction' && $row->tr_payment_part == 0 && $row->purchase_order_id != 0) {
          // $transaction_edit = 0;
          $transaction_edit = 1;
        } else {
          $transaction_edit = 1;
        }
        if ($this->session->userdata('user_role') == 'accounts_manager') {
          $transaction_edit = 0;
        }
        if ($transaction_edit == 1 && ($this->config->item('User_enable_data_entry_approval') != 1 || $row->tr_entry_approval_status != 1 || $this->session->userdata('user_role') == 'admin')) {
          $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" data-bill-type="' . $bill_type . '" data-bill-id="' . $bill_id . '" data-tr-display-type="' . $tr_display_type . '" id="btn_edit_bill_payment" href="#bill_payment_edit_modal" data-id-column="' . $transaction_id_column . '"  data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-edit"></i>
          </a>';
          $btn_delete = '<a style="margin-left: 5px;margin-right: 5px" data-form-type="' . $form_type . '" data-tr-type="' . $transaction_type . '"  data-id-column="' . $transaction_id_column . '" id="btn_delete_transaction"  href="#transaction_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-trash"></i>
          </a>';
          if ($row->reference_type == 'loan' && $row->loan_type == 'receivable' && $row->tr_type == 'loan_receipt_transaction') {
            $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" data-bill-type="' . $bill_type . '" data-bill-id="' . $bill_id . '" data-tr-display-type="' . $tr_display_type . '" id="btn_edit_loan_receipt" href="#loan_receipt_edit_modal" data-id-column="' . $transaction_id_column . '"  data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
            <i class="la la-edit"></i>
            </a>';
          }
        }
        if ($row->reference_type == 'supplier') {
          $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="advance_payment_edit_btn" href="#advance_payment_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-edit"></i>
          </a>';
          $btn_delete = '<a style="margin-left: 5px;margin-right: 5px" id="btn_delete_advance_transaction"  href="#advance_transaction_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-trash"></i>
          </a>';
        }
        if ($row->tr_type == 'purchase_order_transaction' && $row->purchase_bill_id!=0) {
          // Disable Transaction Edit/Delete for Bill Created Order
          $btn_edit = $btn_delete = '';
        }
      }
      $reference_type_2 = $reference_type;
      if ($reference_type == 'subcontract_transactions') {
        $reference_type_2 = 'subcontract';
        if ($row->reference_type == 'subcontract_bill') {
          $bill_no .= '<br/>(Bill Payment)';
        } else {
          $bill_no .= '<br/>(Advance Payment)';
        }
      }

      $data_entry_approval_2_level_tr_types=array("purchase_bill_transaction","loan_receipt_transaction","expense_bill_transaction","loan_transaction");
      $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 && in_array($row->tr_type, $data_entry_approval_2_level_tr_types) && $row->tr_entry_approval_status_2 == 0) || ($this->config->item('User_enable_data_entry_approval_2_level')==1 && !in_array($row->tr_type, $data_entry_approval_2_level_tr_types))){
          $btn_approve = '<a style="margin-left: 5px;margin-right: 5px" data-type="' . $reference_type_2 . '_payment" data-approval-status="' . $row->tr_entry_approval_status . '" data-id="' . $row->transaction_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="' . $reference_type_2 . '_payment" data-approval-status="'.$row->tr_entry_approval_status_2.'" data-id="'.$row->transaction_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 && in_array($row->tr_type, $data_entry_approval_2_level_tr_types)){
          $level='1st Level ';
        }
        if ($row->tr_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->tr_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->tr_entry_approval_status == 1 && in_array($row->tr_type, $data_entry_approval_2_level_tr_types)){
          if ($row->tr_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->tr_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>";
          }
        }
      }

      $array[$j][] = $sl_no;
      $array[$j][] = $row->transaction_id;
      $array[$j][] = date('d-m-Y', strtotime($row->tr_date));
      $array[$j][] = $bill_id_link;
      $array[$j][] = $project;
      if ($reference_type == 'purchase_bill' || $reference_type == 'purchase_order' || $reference_type == 'supplier') {
        $array[$j][] = $consignee;
      } elseif ($reference_type == 'subcontract_bill') {
        $array[$j][] = '<a id="m_quick_sidebar_toggle" data-type="subcontract_profile" data-id="' . $row->contract_id . '" href="javascript:;">' . $row->sub_work_name . '</a>';
      }elseif ($reference_type == 'expense_bill') {
        $array[$j][] = $row->credit_account;
      } elseif ($reference_type == 'subcontract_transactions') {
        if ($row->reference_type == 'subcontract_bill') {
          $array[$j][] = '<a id="m_quick_sidebar_toggle" data-type="subcontract_profile" data-id="' . $row->contract_id . '" href="javascript:;">' . $row->sub_work_name . '</a>';
        } else {
          $array[$j][] = '<a id="m_quick_sidebar_toggle" data-type="subcontract_profile" data-id="' . $row->contract_id_2 . '" href="javascript:;">' . $row->sub_work_name_2 . '</a>';
        }
        // $array[$j][] = ($row->branch_id == 0) ? 'No Branch' : $this->Branches->select_branches('*', array('branch_id' => $row->branch_id))->row()->branch_name;
      } elseif ($reference_type == 'labour' || $reference_type == 'labour_insurance_fd') {
        $array[$j][] = $row->type_name;
      } elseif ($reference_type == 'salary_slip' || $reference_type == 'employee') {
        if ($row->reference_type == 'salary_slip') {
          $array[$j][] = $row->user_designation;
        } else {
          $array[$j][] = $row->user_designation_2;
        }
        if ($row->tr_type == "salary_slip_transaction") {
          $array[$j][] = "<span class='m-badge m-badge--info m-badge--wide'></i>Salary Slip</span>";
        } else if ($row->tr_type == "employee_opbalance_transaction") {
          $array[$j][] = "<span class='m-badge m-badge--success m-badge--wide'></i>Opening Balance</span>";
        } else if ($row->tr_type == "salary_advance_transaction") {
          $array[$j][] = "<span class='m-badge m-badge--warning m-badge--wide'></i>Advance Salary</span>";
        }else if ($row->tr_type == "employee_bata_transaction") {
          $array[$j][] = "<span class='m-badge m-badge--focus m-badge--wide'></i>Employee Bata</span>";
        } else {
          $array[$j][] = "";
        }
      } elseif ($reference_type == 'user_payment_receipt' || $reference_type == 'user_payment_return') {
        $department = $row->department_name;
        if ($row->role_title != '') {
          $department .= " - " . $row->role_title;
        }
        $array[$j][] = $department;
      } elseif ($reference_type == 'user_commission') {
        $array[$j][] = $row->role_title;
      } elseif ($reference_type == 'loan') {
        $array[$j][] = $row->loan_provider_name;
      } elseif ($reference_type == 'vehicle_work_slip' || $reference_type == 'vehicle_renewal' || $reference_type == 'vehicle_payment') {
        $array[$j][] = $row->consignee_name;
      } elseif ($reference_type == 'tool') {
        if ($row->reference_type == 'tool_transfer' && $row->transfer_from == 0) {
          $array[$j][] = 'Office';
        } elseif ($row->reference_type == 'tool_rent') {
          $array[$j][] = $row->rented_from;
        } else {
          $array[$j][] = '';
        }
      } else {
        $array[$j][] = "";
      }

      if ($reference_type == 'tool') {
        if ($row->reference_type == 'tool_transfer') {
          $array[$j][] = $row->transfer_to_location;
        } elseif ($row->reference_type == 'tool_rent') {
          $array[$j][] = $row->rented_to_location;
        } else {
          $array[$j][] = '';
        }
      } elseif ($reference_type == 'user_commission') {
        $array[$j][] = $row->work_name;
      } elseif ($reference_type == 'employee') {
        $array[$j][] = $expense_under;
      } else {
        $array[$j][] = "";
      }
      $array[$j][] = "";
      $array[$j][] = $bill_no;
      $array[$j][] = $consignee;
      $array[$j][] = number_format($row->tr_amount, $this->config->item('Currency_amount_decimals_2'), '.', '');
      if ($reference_type == 'user_payment_return' || ($reference_type == 'loan' && $row->loan_type == 'receivable')) {
        $array[$j][] = $row->credit_account;
      } else {
        $array[$j][] = $row->debit_account;
      }
      $array[$j][] = $row->tr_mode;
      $array[$j][] = $row->tr_reference_no;
      if ($row->tr_reference_date != '0000-00-00') {
        $array[$j][] = date('d-m-Y', strtotime($row->tr_reference_date));
      } else {
        $array[$j][] = '';
      }
      $array[$j][] = $row->tr_remarks;
      $array[$j][] = $row->created_user . $entry_approval_status;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][] = date('d-m-Y', strtotime($row->created_date));
      }else{
        $array[$j][] = '';
      }
      $array[$j][] = $btn_edit . $btn_delete . $btn_approve;
      $array[$j][] = $row->tr_debit_acc;
      $array[$j][] = $row->tr_credit_acc;
      $array[$j][] = $row->tr_work_id;
      $array[$j][] = $row->tr_type;
      $array[$j][] = $row->tr_entry_approval_status;
      $array[$j][] = $row->tr_entry_approval_status_2;

      $total_paid_amount += $row->tr_amount;

      $j++;
    endforeach;
    if ($result->num_rows() > 0) {
      $array[$j][] = '';
      $array[$j][] = '';
      if (isset($row->tr_type)) {
        $array[$j][] = '';
      }
      $array[$j][] = '';
      $array[$j][] = '';
      if ($reference_type == 'salary_slip' || $reference_type == 'employee') {
        $array[$j][] = '';
        $array[$j][] = '';
      }
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = "<strong>Total</strong>";
      $array[$j][] = "<strong>" . $this->config->item('Currency_currency_format') . " " . $this->config->item('currency_format')->formatCurrency($total_paid_amount, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "";
      $array[$j][] = '';
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $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_transfer($page_data_type=''){

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

    $data = array();
    $data['tr_type'] = 'account_transfer';
    if($this->session->userdata('user_role')!='admin' && $this->session->userdata('user_role')!='general_manager' && $this->session->userdata('user_role')!='accounts_manager') {
      $user_id = $this->session->userdata('user_id');
      $this->db->where("(ah1.acc_user_id='$user_id' or ah2.acc_user_id='$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['u1.user_role >'] =2;
      if(isset($_POST['approval_status']) && $_POST['approval_status']!='' && $_POST['approval_status']!='all'){
        $entry_approval = $_POST['approval_status'];
        $join_table_entry_approval = 'all';
      }
    }
    if (isset($_POST['acc_head_id']) && $_POST['acc_head_id'] != '' && $_POST['acc_head_id'] != 'all') {
      $acc_head_id = $_POST['acc_head_id'];
      $account_heads_where['ah.acc_head_id'] = $_POST['acc_head_id'];
      $account_heads_data	= $this->Account->select_account_heads("acc_head_id",$account_heads_where)->row();
      $this->db->where('(tr_credit_acc='.$acc_head_id.' or tr_debit_acc='.$acc_head_id.')');
    }
    if(isset($_POST['created_by']) && $_POST['created_by']!='' && $_POST['created_by']!='all'){
      $data['ats.created_by'] = $_POST['created_by'];
    }
    if (isset($_POST['start_date']) && $_POST['start_date'] != '' && $_POST['start_date'] != 'all') {
      $data['ats.tr_date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if (isset($_POST['end_date']) && $_POST['end_date'] != '' && $_POST['end_date'] != 'all') {
      $data['ats.tr_date <='] = date('Y-m-d', strtotime($_POST['end_date']));
    }
    $result = $this->Account->select_account_transfer("*,ah1.acc_head_name AS transfer_from,ah1.acc_head_id AS acc_from_id,ah2.acc_head_name AS transfer_to,ah2.acc_head_id AS acc_to_id,u1.user_alias AS created_by,ats.created_date AS t_created_date,u1.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();
    $sl_no = 0;
    foreach ($result_array as $row) :
      $sl_no++;
      $btn_view = $btn_edit = $btn_delete = '';
      if(($this->config->item('User_enable_data_entry_approval')!=1 || $row->tr_entry_approval_status!=1 || $this->session->userdata('user_role')=='admin')){
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="acc_transfer_edit_btn" href="#acc_transfer_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete = '<a style="margin-left: 5px;margin-right: 5px" id="acc_transfer_delete_btn"  href="#acc_transfer_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="account_transfer" data-approval-status="'.$row->tr_entry_approval_status.'" data-id="'.$row->transaction_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->tr_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->tr_entry_approval_status==2){
          $entry_approval_status="<br/><span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> Rejected</span>";
        }else{
          $entry_approval_status="<br/><span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> Pending</span>";
        }
      }

      $array[$j][]=$sl_no;
      $array[$j][]=$row->transaction_id;
      $array[$j][]=$row->transfer_from;
      $array[$j][]=$row->transfer_to;
      $array[$j][]=$row->tr_amount;
      $array[$j][]=date('d-m-Y',strtotime($row->tr_date));
      $array[$j][]=$row->tr_mode;
      $array[$j][]=$row->tr_remarks;
      $array[$j][]=$row->created_by.$entry_approval_status;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][]=date('d-m-Y',strtotime($row->t_created_date));
      }else{
        $array[$j][]='';
      }
      $array[$j][]=$btn_approve.$btn_view.$btn_edit.$btn_delete;
      $array[$j][]=$row->acc_from_id;
      $array[$j][]=$row->acc_to_id;
      $array[$j][]=$row->tr_entry_approval_status;


      $j++;
    endforeach;

    $json_data['data'] = $array;
    echo json_encode($json_data);  // send data as json format
  }
  public function create_transaction_transfer($param1 = "")
  {
    $redirect_url = $this->security->xss_clean($this->input->post('redirect_url'));
    $transaction_data['tr_type'] = $transaction_data['reference_type'] = 'account_transfer';
    $transaction_data['tr_remarks'] = $this->security->xss_clean($this->input->post('tr_remarks'));
    $transaction_data['created_date'] = date('Y-m-d H:i:s');
    $transaction_data['created_by'] = $this->session->userdata('user_id');
    $transaction_data['tr_debit_acc'] =  $this->security->xss_clean($this->input->post('debit_acc'));
    $transaction_data['tr_credit_acc'] = $this->security->xss_clean($this->input->post('credit_acc'));
    $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('paid_amount'));
    $transaction_data['tr_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('paid_date'))));
    $transaction_data['tr_mode'] = $this->security->xss_clean($this->input->post('payment_mode'));
    $transaction_data['tr_description'] = ucwords(str_replace('_',' ',$transaction_data['tr_type']));
    if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
      $transaction_data['tr_entry_approval_status'] = 0;
    }
    $transaction_result =  $this->Account->create_account_transaction($transaction_data);
    $flash_data['status'] = $transaction_result['status'];
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = $transaction_data['tr_description'] . ' Created Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);
  }
  public function update_transaction_transfer()
  {
    $transaction_data['transaction_id'] = $this->security->xss_clean($this->input->post('transaction_id'));
    $transaction_data['tr_debit_acc'] = $this->security->xss_clean($this->input->post('acc_from'));
    $transaction_data['tr_credit_acc'] = $this->security->xss_clean($this->input->post('acc_to'));
    $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('paid_amount'));
    $transaction_data['tr_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('paid_date'))));
    $transaction_data['tr_mode'] = $this->security->xss_clean($this->input->post('payment_mode'));
    $transaction_data['tr_remarks'] = $this->security->xss_clean($this->input->post('tr_remarks'));
    $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);
    $flash_data['status'] = $transaction_result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Account Transfer Details Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }
  public function delete_transaction_transfer($param1 = "")
  {
    $transaction_data['transaction_id'] = $this->security->xss_clean($this->input->post('transaction_id'));
    $transaction_data['delete_status'] = 1;
    $transaction_result =  $this->Account->update_account_transaction($transaction_data);
    $flash_data['status'] = $transaction_result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Account Transfer Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);
  }
  public function select_creditors_list()
  {

    $json_data = $array = array();
    $j = $sl_no = $credit_sum = $debit_sum = 0;
    $selected_project = $selected_project_ids = '';
    $data_suppliers = array();
    if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
      $data_suppliers['s.branch_id'] = $_POST['branch_id'];
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $selected_project = $_POST['work'];
    }
    if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
      $selected_project_ids = $_POST['work_ids'];
    }
    if($selected_project=='' && $selected_project_ids==''){
      $suppliers = $this->Supplier->select_supplier("*",$data_suppliers)->result();
      foreach ($suppliers as $row) {

        $opening_balance = $this->Account->select_account_heads("", array("acc_supplier_id" => $row->supplier_id))->row()->op_balance;
        $opening_balance_paid = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount", array("s.supplier_id" => $row->supplier_id, "ats.tr_type" => 'supplier_opbalance_transaction', "ats.reference_type" => 'supplier'), 'supplier')->row()->total_amount;
        $advance_paid = $this->supplier_management->calculate_advance_amount($row->supplier_id)['advance_paid'];
        $total_order_payment = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount", array("po.supplier_id" => $row->supplier_id, "ats.tr_type" => 'purchase_order_transaction', "ats.reference_type" => 'purchase_order', "po.delete_status" => 0), 'purchase_order')->row()->total_amount;
        $total_purchase_bill_payment = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount", array("p.supplier_id" => $row->supplier_id, "ats.tr_type" => 'purchase_bill_transaction', "ats.reference_type" => 'purchase_bill', "p.delete_status" => 0), 'purchase_bill')->row()->total_amount;
        $total_purchase_bill_amount = $this->Purchases->select_purchase("COALESCE(SUM(p.bill_payable_amount),0) as grand_total", array("p.supplier_id" => $row->supplier_id, "p.delete_status" => 0))->row()->grand_total;
        $total_purchase_bill_balance_amount = $this->Purchases->select_purchase("COALESCE(SUM(p.balance_amount),0) as total_purchase_balance", array("p.supplier_id" => $row->supplier_id, "p.delete_status" => 0))->row()->total_purchase_balance;
        $total_purchase_commission = $this->Purchases->select_purchase("COALESCE(SUM(p.bill_commission_amount),0) as total_amount", array("p.supplier_id" => $row->supplier_id, "p.delete_status" => 0))->row()->total_amount;
        $total_paid = $total_order_payment + $total_purchase_bill_payment + $opening_balance_paid + $advance_paid;
        $total_balance = round(($total_purchase_bill_amount - $total_paid + $opening_balance),$this->config->item('Currency_amount_decimals_2'));

        if ($total_balance != 0) {
          $sl_no++;
          $array[$j][] = $sl_no;
          $array[$j][]=($row->branch_id==0)?'No Branch':$this->Branches->select_branches('*',array('branch_id'=>$row->branch_id))->row()->branch_name;
          $array[$j][] = '<a href="' . base_url() . 'supplier/profile/' . $row->supplier_id . '">' . $row->supplier_name . '</a>';
          $array[$j][] = 'Material Supplier';
          if ($total_balance < 0) {
            $array[$j][] = $this->config->item('currency_format')->formatCurrency($total_balance,$this->config->item('Currency_currency_shortname'));
            $array[$j][] = '';
            $debit_sum += $total_balance;
          }else{
            $array[$j][] = '';
            $array[$j][] = $this->config->item('currency_format')->formatCurrency($total_balance,$this->config->item('Currency_currency_shortname'));
            $credit_sum += $total_balance;
          }
          $j++;
        }
      }
    }else{
      if($selected_project_ids!=''){
        $this->db->where_in('wc.work_id',explode(',',$selected_project_ids));
      }else{
        $purchase_bill_where['wc.work_id'] = $selected_project;
      }
      $purchase_bill_where['p.balance_amount !='] = 0;
      $pending_purchase_bills = $this->Purchases->select_purchase("p.*,wc.branch_id,s.supplier_id,s.supplier_name", $purchase_bill_where,1)->result();
      foreach ($pending_purchase_bills as $row) {
        $sl_no++;
        $array[$j][] = $sl_no;
        $array[$j][]=($row->branch_id==0)?'No Branch':$this->Branches->select_branches('*',array('branch_id'=>$row->branch_id))->row()->branch_name;
        $array[$j][] = '<a target="_blank" href="' . base_url() . 'purchases/profile/' . $row->purchase_id . '">#' . $row->purchase_id . ' Material Purchase Bill - ' . $row->supplier_name . '</a>';
        $array[$j][] = 'Material Supplier';
        if($row->balance_amount<0){
          $array[$j][] = $this->config->item('currency_format')->formatCurrency($row->balance_amount,$this->config->item('Currency_currency_shortname'));
          $array[$j][] = '';
          $debit_sum += $row->balance_amount;
        }else{
          $array[$j][] = '';
          $array[$j][] = $this->config->item('currency_format')->formatCurrency($row->balance_amount,$this->config->item('Currency_currency_shortname'));
          $credit_sum += $row->balance_amount;
        }
        $j++;
      }
    }

    $expense_bill_where['b.bill_type'] = 'expense';
    $expense_bill_where['b.bill_balance_amount !='] = 0;
    if($selected_project_ids!=''){
      $this->db->where_in('b.work_id',explode(',',$selected_project_ids));
    }elseif(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $expense_bill_where['b.work_id'] = $_POST['work'];
    }
    if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
      $expense_bill_where['b.branch_id'] = $_POST['branch_id'];
    }
    $expense_bills  = $this->Bills->select_bills("b.*,ah1.acc_head_name as expense_head_name,u.user_alias,wc.work_name", $expense_bill_where)->result();
    foreach ($expense_bills as $row) {
      $sl_no++;
      $array[$j][] = $sl_no;
      $array[$j][]=($row->branch_id==0)?'No Branch':$this->Branches->select_branches('*',array('branch_id'=>$row->branch_id))->row()->branch_name;
      $array[$j][] = '<a id="m_quick_sidebar_toggle" data-type="bill_profile" data-bill-type="expense_bill" data-id="' . $row->bill_id . '" href="javascript:;">#' . $row->bill_id . '</a> ' . $row->expense_head_name . " (" . $row->bill_consignee_name . ")";
      $array[$j][] = 'Expense Bill';
      if ($row->bill_balance_amount < 0) {
        $array[$j][] = $this->config->item('currency_format')->formatCurrency($row->bill_balance_amount,$this->config->item('Currency_currency_shortname'));
        $array[$j][] = '';
        $debit_sum += $row->bill_balance_amount;
      } else {
        $array[$j][] = '';
        $array[$j][] = $this->config->item('currency_format')->formatCurrency($row->bill_balance_amount,$this->config->item('Currency_currency_shortname'));
        $credit_sum += $row->bill_balance_amount;
      }
      $j++;
    }

    $subcontract_where = array();
    if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
      $subcontract_where['b.branch_id'] = $_POST['branch_id'];
    }
    if($selected_project_ids!=''){
      $this->db->where_in('sc.work_id',explode(',',$selected_project_ids));
    }elseif(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $subcontract_where['sc.work_id'] = $_POST['work'];
    }
    $subcontracts  = $this->Subcontracts->select_subcontract("sc.op_balance,wc.branch_id,sc.contract_id,sc.sub_work_name,c.contractor_name,wc.work_name,wc.work_id", $subcontract_where)->result();
    foreach ($subcontracts  as $row) {

      $bill_details = $this->Bills->select_bills("count(b.bill_id) as bill_count,COALESCE(SUM(bill_payable_amount),0) as bill_payable_amount,COALESCE(SUM(bill_total_paid),0) as bill_total_paid,COALESCE(SUM(bill_balance_amount),0) as bill_balance_amount,COALESCE(SUM(bill_tds_amount),0) as bill_tds_amount,COALESCE(SUM(bill_retention_amount),0) as bill_retention_amount", array("b.subcontract_id" => $row->contract_id, "b.bill_type" => 'subcontract'))->row();
      $bill_amount = $bill_details->bill_payable_amount;
      $bill_paid_amount = $bill_details->bill_total_paid;
      $advance_paid_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $row->contract_id, "ats.reference_type" => 'subcontract'), 'subcontract_advance')->row()->total_paid_amount;
      $total_paid = $row->op_balance + $bill_paid_amount + $advance_paid_amount;
      $balance_payable = $bill_amount - $total_paid;

      if($balance_payable!=0){
        $sl_no++;
        $array[$j][] = $sl_no;
        $array[$j][]=($row->branch_id==0)?'No Branch':$this->Branches->select_branches('*',array('branch_id'=>$row->branch_id))->row()->branch_name;
        $array[$j][] = $row->contractor_name . " (" . $row->sub_work_name . ") [Project: #". $row->work_id ." ". $row->work_name ."]";
        $array[$j][] = 'Subcontract Work';
        if ($balance_payable < 0) {
          $array[$j][] = $this->config->item('currency_format')->formatCurrency($balance_payable,$this->config->item('Currency_currency_shortname'));
          $array[$j][] = '';
          $debit_sum += $balance_payable;
        } else {
          $array[$j][] = '';
          $array[$j][] = $this->config->item('currency_format')->formatCurrency($balance_payable,$this->config->item('Currency_currency_shortname'));
          $credit_sum += $balance_payable;
        }
        $j++;
      }
    }
    if($selected_project==''){
      $labour_where = $labour_wage_data = $labour_payment_data = array();
      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))');
      }
      if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
        $labour_where['l.branch_id'] = $_POST['branch_id'];
      }
      $labours  = $this->Labour->select_labours("l.*,wt.type_name,u.user_alias", $labour_where)->result();
      foreach ($labours as $row) {

        $labour_wage_data = $labour_payment_data =  array();

        if ($this->config->item('Labour_group_member_payment') == 0 && $row->labour_type == 1 && $row->group_position == 1) {
          $labour_wage_data['l.labour_group'] = $row->labour_group;
        } else {
          $labour_wage_data['lw.labour_id'] = $row->labour_id;
        }

        $total_wage = round($this->Labour_wages->select_labour_wages("COALESCE(SUM(lw.total_wage),0) as total", $labour_wage_data)->row()->total, $this->config->item('Currency_amount_decimals_2'));

        $total_paid = $total_opening_wage_paid = $op_balance = 0;
        if ($this->config->item('Labour_group_member_payment') == 0 && $row->labour_type == 1 && $row->group_position == 1) {
          $labour_data_where['l.labour_group'] = $row->labour_group;
          $total_opening_balance = $this->Labour->select_labours_2("COALESCE(SUM(l.opening_balance),0) as total", $labour_data_where)->row()->total;
        } else {
          $total_opening_balance = $row->opening_balance;
        }

        if ($this->config->item('Labour_group_member_payment') == 0 && $row->labour_type == 1 && $row->group_position == 1) {
          $labour_payment_data['l.labour_group'] = $row->labour_group;
        } else {
          $labour_payment_data['l.labour_id'] = $row->labour_id;
        }

        $labour_payment_data['ats.tr_type'] = 'labour_transaction';
        $labour_payment_data['ats.reference_type'] = 'labour';
        $total_paid = round($this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount", $labour_payment_data, 'labour')->row()->total_amount,$this->config->item('Currency_amount_decimals_2'));

        $op_balance = round($total_opening_balance,$this->config->item('Currency_amount_decimals_2'));

        $total_wage_to_pay = $total_wage + $op_balance;
        $total_balance = round($total_wage_to_pay - $total_paid,$this->config->item('Currency_amount_decimals_2'));

        if ($total_balance != 0) {
          $sl_no++;
          $array[$j][] = $sl_no;
          $array[$j][]=($row->branch_id==0)?'No Branch':$this->Branches->select_branches('*',array('branch_id'=>$row->branch_id))->row()->branch_name;
          $array[$j][] = '<a href="' . base_url() . 'labours/profile/' . $row->labour_id . '">' . $row->labour_name . '</a>';
          $array[$j][] = 'Labour Wage';
          if ($total_balance < 0) {
            $array[$j][] = $this->config->item('currency_format')->formatCurrency($total_balance,$this->config->item('Currency_currency_shortname'));
            $array[$j][] = '';
            $debit_sum += $total_balance;
          } else {
            $array[$j][] = '';
            $array[$j][] = $this->config->item('currency_format')->formatCurrency($total_balance,$this->config->item('Currency_currency_shortname'));
            $credit_sum += $total_balance;
          }
          $j++;
        }
      }
    }

    $loan_where = array();

    if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
      $loan_where['l.branch_id'] = $_POST['branch_id'];
    }
    if($selected_project_ids!=''){
      $this->db->where_in('wc.work_id',explode(',',$selected_project_ids));
    }elseif(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $loan_where['l.work_id'] = $_POST['work'];
    }
    $loans  = $this->Loan->select_loan("l.*,u.user_alias as created_user,ah1.acc_head_name,wc.work_name,lp.loan_provider_name", $loan_where)->result();
    foreach ($loans as $row) {
      $loan_payment_data['l.loan_id'] = $row->loan_id;
      $loan_payment_data['ats.reference_type'] = 'loan';
      if ($row->loan_type == 'receivable') {
        $loan_payment_data['ats.tr_type'] = 'loan_receipt_transaction';
        $loan_purpose = 'Receivable Loan';
      } else {
        $loan_payment_data['ats.tr_type'] = 'loan_transaction';
        $loan_purpose = 'Payable Loan';
      }
      $paid_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount", $loan_payment_data, 'loan')->row()->total_amount;
      $balance_amount = $row->current_balance_payable - $paid_amount;
      if ($row->loan_type == 'payable') {
        if ($row->work_id == 0) {
          $loan_purpose .= ' ( For Whole Business )';
        } else {
          $loan_purpose .= ' ( For Project : ' . $row->work_name . ' )';
        }
      }

      if ($balance_amount != 0) {
        $sl_no++;
        $array[$j][] = $sl_no;
        $array[$j][]=($row->branch_id==0)?'No Branch':$this->Branches->select_branches('*',array('branch_id'=>$row->branch_id))->row()->branch_name;
        $array[$j][] = '<a href="' . base_url() . 'loans/provider/profile/' . $row->provider_id . '">' . $row->loan_provider_name . '</a>';
        $array[$j][] = $loan_purpose;
        if ($row->loan_type == 'receivable') {
          if ($balance_amount < 0) {
            $array[$j][] = '';
            $array[$j][] = $this->config->item('currency_format')->formatCurrency($balance_amount,$this->config->item('Currency_currency_shortname'));
            $credit_sum += $balance_amount;
          } else {
            $array[$j][] = $this->config->item('currency_format')->formatCurrency($balance_amount,$this->config->item('Currency_currency_shortname'));
            $array[$j][] = '';
            $debit_sum += $balance_amount;
          }
        } else {
          if ($balance_amount < 0) {
            $array[$j][] = $this->config->item('currency_format')->formatCurrency($balance_amount,$this->config->item('Currency_currency_shortname'));
            $array[$j][] = '';
            $debit_sum += $balance_amount;
          } else {
            $array[$j][] = '';
            $array[$j][] = $this->config->item('currency_format')->formatCurrency($balance_amount,$this->config->item('Currency_currency_shortname'));
            $credit_sum += $balance_amount;
          }
        }
        $j++;
      }
    }
    if(sizeof($array)>0){
      $array[$j][] = '';
      $array[$j][]='';
      $array[$j][] = '<strong>TOTAL</strong>';
      $array[$j][] = '';
      $array[$j][] = '<strong>'.$this->config->item('currency_format')->formatCurrency($debit_sum,$this->config->item('Currency_currency_shortname')).'</strong>';
      $array[$j][] = '<strong>'.$this->config->item('currency_format')->formatCurrency($credit_sum,$this->config->item('Currency_currency_shortname')).'</strong>';

    }

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



  public function create_security_deposit()
  {
    $data['project_id'] = $this->security->xss_clean($this->input->post('work_id'));
    $data['deposit_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('deposit_date'))));
    $data['security_deposit'] = $this->security->xss_clean($this->input->post('security_deposit'));
    $data['retention_money'] = $this->security->xss_clean($this->input->post('retention_money'));
    $data['ld_amount'] = $this->security->xss_clean($this->input->post('ld_amount'));
    $data['income_tax'] = $this->security->xss_clean($this->input->post('income_tax'));
    $data['gst_tds'] = $this->security->xss_clean($this->input->post('gst_tds'));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');
    $result = $this->Account->create_security_deposit($data);
    $flash_data['status'] = $result['status'];
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Security Deposit Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'info';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo (json_encode($flash_data));
  }
  public function update_security_deposit()
  {
    $data['deposit_id'] = $this->security->xss_clean($this->input->post('deposit_id'));
    $data['project_id'] = $this->security->xss_clean($this->input->post('work_id'));
    $data['deposit_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('deposit_date'))));
    $data['security_deposit'] = $this->security->xss_clean($this->input->post('security_deposit'));
    $data['retention_money'] = $this->security->xss_clean($this->input->post('retention_money'));
    $data['ld_amount'] = $this->security->xss_clean($this->input->post('ld_amount'));
    $data['income_tax'] = $this->security->xss_clean($this->input->post('income_tax'));
    $data['gst_tds'] = $this->security->xss_clean($this->input->post('gst_tds'));
    $result = $this->Account->update_security_deposit($data);
    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Security Deposit Details Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'info';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo (json_encode($flash_data));
  }
  public function delete_security_deposit()
  {
    $data['deposit_id'] = $this->security->xss_clean($this->input->post('deposit_id'));
    $data['delete_status'] = 1;
    $result = $this->Account->update_security_deposit($data);
    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Security Deposit Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'info';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo (json_encode($flash_data));
  }
  public function select_security_deposit($list_type = "")
  {

    $json_data = array();
    $j = 0;
    $sl_no = 0;
    $total_security_deposit = $total_retention_money = $total_ld_amount = $total_income_tax = $total_gst_tds = 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(sd.deposit_date,'%Y-%m-%d') <="] = $end_date;
      $data["STR_TO_DATE(sd.deposit_date,'%Y-%m-%d') >="] = $start_date;
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!=''){
      $data["sd.deposit_date >="]= date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!=''){
      $data["sd.deposit_date <="]= date('Y-m-d', strtotime($_POST['end_date']));
    }
    if (isset($_POST['clients']) && $_POST['clients'] != '' && $_POST['clients'] != 'all') {
      $data['c.client_id'] = $_POST['clients'];
    }
    if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
      $data['wc.work_id'] = $_POST['work'];
    }
    if(isset($_POST['work_ids']) && $_POST['work_ids']!='' && $_POST['work_ids']!='all'){
      $this->db->where_in('wc.work_id',explode(',',$_POST['work_ids']));
    }
    if (isset($_POST['branch_id']) && $_POST['branch_id'] != '' && $_POST['branch_id'] != 'all') {
      $data['wc.branch_id'] = $_POST['branch_id'];
    }

    $result  = $this->Account->select_security_deposit("sd.*,wc.work_name,u.user_alias,c.client_name,wc.branch_id", $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 ($this->session->userdata('user_role') == 'admin' || ($this->session->userdata('user_role') == 'supervisor' && $this->session->userdata('user_id') == $row->created_by)) {
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="security_deposit_edit_btn" href="#security_deposit_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete = '<a style="margin-left: 5px;margin-right: 5px" id="security_deposit_delete_btn" href="#security_deposit_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-trash"></i>
        </a>';
      } else {
        $btn_edit = '';
        $btn_delete = '';
      }

      $sl_no++;
      $array[$j][] = $sl_no;
      $array[$j][] = ($row->branch_id == 0) ? 'No Branch' : $this->Branches->select_branches('*', array('branch_id' => $row->branch_id))->row()->branch_name;
      $array[$j][] = $row->deposit_id;
      $array[$j][] = ($row->receipt_transaction_id != 0) ? "#" . $row->receipt_transaction_id : '';
      $array[$j][] = date('d-m-Y', strtotime($row->deposit_date));
      $array[$j][] = '<a href="' . base_url() . 'work/profile/' . $row->project_id . '">#' . $row->project_id . " " . $row->work_name . '</a>';
      $array[$j][] = $row->client_name;
      $array[$j][] = $row->security_deposit;
      $array[$j][] = $row->retention_money;
      $array[$j][] = $row->ld_amount;
      $array[$j][] = $row->income_tax;
      $array[$j][] = $row->gst_tds;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][] = '<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : ' . date('d-m-Y', strtotime($row->created_date)) . "</li><li>Created By : " . $row->user_alias . "</li>";
      }else{
        $array[$j][] = '<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : ' . $row->user_alias . '</li>';
      }
      $array[$j][] = $btn_edit . $btn_delete;
      $array[$j][] = $row->project_id;

      $total_security_deposit += $row->security_deposit;
      $total_retention_money += $row->retention_money;
      $total_ld_amount += $row->ld_amount;
      $total_income_tax += $row->income_tax;
      $total_gst_tds += $row->gst_tds;

      $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_security_deposit . "</strong>";
      $array[$j][] = "<strong>" . $total_retention_money . "</strong>";
      $array[$j][] = "<strong>" . $total_ld_amount . "</strong>";
      $array[$j][] = "<strong>" . $total_income_tax . "</strong>";
      $array[$j][] = "<strong>" . $total_gst_tds . "</strong>";
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
    }

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

  public function create_emd()
  {
    $data['project_id'] = $this->security->xss_clean($this->input->post('work_id'));
    $data['project_details'] = $this->security->xss_clean($this->input->post('project_details'));
    $data['emd_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('emd_date'))));
    $data['bg_no'] = $this->security->xss_clean($this->input->post('bg_no'));
    $data['emd_amount'] = $this->security->xss_clean($this->input->post('emd_amount'));
    $data['expiry_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('expiry_date'))));
    $data['next_renewal_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('renewal_date'))));
    $data['authority'] = $this->security->xss_clean($this->input->post('authority'));
    $data['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');
    $result = $this->Account->create_security_deposit_emd($data);
    $flash_data['status'] = $result['status'];
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'EMD Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'info';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo (json_encode($flash_data));
  }
  public function update_emd()
  {
    $data['emd_id'] = $this->security->xss_clean($this->input->post('emd_id'));
    $data['project_id'] = $this->security->xss_clean($this->input->post('work_id'));
    $data['project_details'] = $this->security->xss_clean($this->input->post('project_details'));
    $data['emd_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('emd_date'))));
    $data['bg_no'] = $this->security->xss_clean($this->input->post('bg_no'));
    $data['emd_amount'] = $this->security->xss_clean($this->input->post('emd_amount'));
    $data['expiry_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('expiry_date'))));
    $data['next_renewal_date'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('renewal_date'))));
    $data['authority'] = $this->security->xss_clean($this->input->post('authority'));
    $data['remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $data['updated_date'] = date('Y-m-d H:i:s');
    $data['updated_by'] = $this->session->userdata('user_id');
    $result = $this->Account->update_security_deposit_emd($data);
    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'EMD Details Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'info';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo (json_encode($flash_data));
  }
  public function delete_emd()
  {
    $data['emd_id'] = $this->security->xss_clean($this->input->post('emd_id'));
    $data['delete_status'] = 1;
    $result = $this->Account->update_security_deposit_emd($data);
    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'EMD Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'info';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo (json_encode($flash_data));
  }
  public function select_security_deposit_emd($list_type = "")
  {

    $json_data = array();
    $j = 0;
    $sl_no = 0;
    $total_emd = 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(sd.emd_date,'%Y-%m-%d') <="] = $end_date;
      $data["STR_TO_DATE(sd.emd_date,'%Y-%m-%d') >="] = $start_date;
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!=''){
      $data["sd.emd_date >="]= date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!=''){
      $data["sd.emd_date <="]= date('Y-m-d', strtotime($_POST['end_date']));
    }
    if (isset($_POST['clients']) && $_POST['clients'] != '' && $_POST['clients'] != 'all') {
      $data['c.client_id'] = $_POST['clients'];
    }
    if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
      $data['wc.work_id'] = $_POST['work'];
    }
    if (isset($_POST['branch_id']) && $_POST['branch_id'] != '' && $_POST['branch_id'] != 'all') {
      $data['wc.branch_id'] = $_POST['branch_id'];
    }

    $result  = $this->Account->select_security_deposit_emd("sd.*,wc.work_name,u.user_alias,c.client_name,wc.branch_id", $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 ($this->session->userdata('user_role') == 'admin' || ($this->session->userdata('user_role') == 'supervisor' && $this->session->userdata('user_id') == $row->created_by)) {
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="emd_edit_btn" href="#emd_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete = '<a style="margin-left: 5px;margin-right: 5px" id="emd_delete_btn" href="#emd_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-trash"></i>
        </a>';
      } else {
        $btn_edit = '';
        $btn_delete = '';
      }

      $sl_no++;
      $array[$j][] = $sl_no;
      $array[$j][] = ($row->branch_id == 0) ? 'No Branch' : $this->Branches->select_branches('*', array('branch_id' => $row->branch_id))->row()->branch_name;
      $array[$j][] = $row->emd_id;
      $array[$j][] = date('d-m-Y', strtotime($row->emd_date));
      $array[$j][] = $row->authority;
      $array[$j][] = '<a href="' . base_url() . 'work/profile/' . $row->project_id . '">#' . $row->project_id . " " . $row->work_name . '</a><br/>' . $row->project_details;
      $array[$j][] = $row->client_name;
      $array[$j][] = $row->bg_no;
      $array[$j][] = $row->emd_amount;
      $array[$j][] = date('d-m-Y', strtotime($row->expiry_date));
      $array[$j][] = date('d-m-Y', strtotime($row->next_renewal_date));
      $array[$j][] = $row->remarks;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][] = '<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : ' . date('d-m-Y', strtotime($row->created_date)) . "</li><li>Created By : " . $row->user_alias . "</li>";
      }else{
        $array[$j][] = '<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : ' . $row->user_alias . '</li>';
      }
      $array[$j][] = $btn_edit . $btn_delete;
      $array[$j][] = $row->project_id;
      $array[$j][] = $row->project_details;

      $total_emd += $row->emd_amount;

      $j++;
    endforeach;
    if ($result->num_rows() > 0) {
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = "<strong>Total</strong>";
      $array[$j][] = "<strong>" . $total_emd . "</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 create_asset()
  {
    $data['asset_name'] = $this->security->xss_clean($this->input->post('name'));
    $data['description'] = $this->security->xss_clean($this->input->post('description'));
    $data['quantity'] = $this->security->xss_clean($this->input->post('quantity'));
    $data['unit_rate'] = $this->security->xss_clean($this->input->post('unit_rate'));
    $data['total_amount'] = $this->security->xss_clean($this->input->post('total_amount'));
    if ($this->input->post('purchase_date') != '') {
      $data['purchased_on'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('purchase_date'))));
    }
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');
    $result = $this->Account->create_asset($data);
    $flash_data['status'] = $result['status'];
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Asset Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'info';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo (json_encode($flash_data));
  }
  public function update_asset()
  {
    $data['asset_id'] = $this->security->xss_clean($this->input->post('asset_id'));
    $data['asset_name'] = $this->security->xss_clean($this->input->post('name'));
    $data['description'] = $this->security->xss_clean($this->input->post('description'));
    $data['quantity'] = $this->security->xss_clean($this->input->post('quantity'));
    $data['unit_rate'] = $this->security->xss_clean($this->input->post('unit_rate'));
    $data['total_amount'] = $this->security->xss_clean($this->input->post('total_amount'));
    if ($this->input->post('purchase_date') != '') {
      $data['purchased_on'] = date('Y-m-d', strtotime($this->security->xss_clean($this->input->post('purchase_date'))));
    }
    $data['updated_date'] = date('Y-m-d H:i:s');
    $data['updated_by'] = $this->session->userdata('user_id');
    $result = $this->Account->update_asset($data);
    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Asset Details Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'info';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo (json_encode($flash_data));
  }
  public function delete_asset()
  {
    $data['asset_id'] = $this->security->xss_clean($this->input->post('asset_id'));
    $data['delete_status'] = 1;
    $result = $this->Account->update_asset($data);
    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Asset Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'info';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo (json_encode($flash_data));
  }
  public function select_assets($list_type = "")
  {

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

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

    $result  = $this->Account->select_assets("as.*,u.user_alias", $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 ($this->session->userdata('user_role') == 'admin' ||  $this->session->userdata('user_role') == 'general_manager' || $this->session->userdata('user_role') == 'auditor' || $this->session->userdata('user_role') == 'accounts_manager') {
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="asset_edit_btn" href="#asset_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete = '<a style="margin-left: 5px;margin-right: 5px" id="asset_delete_btn" href="#asset_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-trash"></i>
        </a>';
      } else {
        $btn_edit = '';
        $btn_delete = '';
      }

      $sl_no++;
      $array[$j][] = $sl_no;
      $array[$j][] = ($row->branch_id == 0) ? 'No Branch' : $this->Branches->select_branches('*', array('branch_id' => $row->branch_id))->row()->branch_name;
      $array[$j][] = $row->asset_id;
      $array[$j][] = $row->asset_name;
      $array[$j][] = $row->description;
      $array[$j][] = $row->quantity;
      $array[$j][] = $row->unit_rate;
      $array[$j][] = $row->total_amount;
      if ($row->purchased_on != '0000-00-00') {
        $array[$j][] = date('d-m-Y', strtotime($row->purchased_on));
      } else {
        $array[$j][] = '';
      }
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][] = '<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : ' . date('d-m-Y', strtotime($row->created_date)) . "</li><li>Created By : " . $row->user_alias . "</li>";
      }else{
        $array[$j][] = '<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : ' . $row->user_alias . '</li>';
      }
      $array[$j][] = $btn_edit . $btn_delete;

      $total_amount += $row->total_amount;

      $j++;
    endforeach;
    if ($result->num_rows() > 0) {
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = "<strong>Total</strong>";
      $array[$j][] = "<strong>" . $total_amount . "</strong>";
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
    }

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