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

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

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

    $this->load->model('User_model', 'User');
    $this->load->model('Work_model', 'Work');
    $this->load->model('Client_model', 'Client');
    $this->load->model('Supplier_model', 'Supplier');
    $this->load->model('Subcontracts_model', 'Subcontracts');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Bills_model', 'Bills');
    $this->load->model('Labour_model', 'Labour');
    $this->load->model('Branches_model', 'Branches');
    $this->load->library('Bills_management', 'bills_management');
    $this->load->library('Projects_management', 'projects_management');
    $this->load->library('Stock_management', 'stock_management');

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

    //        File Directory
    $this->page_data['directory'] = "subcontracts";

    $this->page_data['work_types'] = $this->Work->select_work_types()->result();
    $user_accounts_where = "ur.role_name='supervisor' or ur.role_name='general_manager'";
    $this->page_data['user_accounts'] = $this->Account->select_account_heads("",$user_accounts_where,"user")->result();
    if($this->config->item('Labour_group_member_payment')==0){
      $this->db->where('(l.labour_type=0 or (l.labour_type=1 and group_position=1))');
    }
    $this->page_data['labours_2'] = $this->Labour->select_labours()->result();
    $this->page_data['contractors'] = $this->Subcontracts->select_contractors("*")->result();
    $this->page_data['billing_address'] = $this->Settings->select_billing_address("")->result();
  }
  public function index()
  {
    $this->view();
  }

  public function view()
  {
    $this->page_data['work_types'] = $this->Work->select_work_types()->result();
    $this->page_data['page_name'] = 'subcontracts_view';
    if ($this->session->userdata('user_role') == 'supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->load->view('Index', $this->page_data);
  }
  public function print($id='',$type='work_order')
  {
    $this->page_data['type'] = $type;
    $this->page_data['page_name'] = 'subcontracts_print_'.$this->config->item('Subcontract_work_order_template');
    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    if($id!=''){
      $this->page_data['subcontract_data'] = $this->Subcontracts->select_subcontract("sc.*,c.*,u.user_alias,wc.work_name,wc.work_location,wc.reference_no as project_reference_no",array("sc.contract_id"=>$id));
      if($this->page_data['subcontract_data']->num_rows()==1){
        $this->page_data['subcontract_data'] = $this->page_data['subcontract_data']->row();
        $this->page_data['work_items'] = $this->Subcontracts->select_subcontract_work_items("scwi.*,wt.type_name,mu.unit_name",array("sc.contract_id"=>$id));

        $this->page_data['no_of_bills'] = $this->Bills->select_bills("b.bill_id", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->num_rows();
        $this->page_data['deduction_amount'] = $this->Subcontracts->select_subcontract_deductions("COALESCE(SUM(amount),0) as total_amount", array("sd.subcontract_id" => $this->page_data['subcontract_data']->contract_id))->row()->total_amount;
        $this->page_data['bill_amount'] = $this->Bills->select_bills("COALESCE(SUM(bill_payable_amount),0) as total_amount", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->row()->total_amount;
        $this->page_data['bill_paid_amount'] = $this->Bills->select_bills("COALESCE(SUM(bill_total_paid),0) as total_amount", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->row()->total_amount;
        $this->page_data['advance_paid_amount'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $this->page_data['subcontract_data']->contract_id, "ats.reference_type" => 'subcontract'), 'subcontract_advance')->row()->total_paid_amount;
        $this->page_data['bill_balance_amount'] = $this->Bills->select_bills("COALESCE(SUM(bill_balance_amount),0) as total_amount", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->row()->total_amount;
        $this->page_data['bill_tds_amount'] = $this->Bills->select_bills("COALESCE(SUM(bill_tds_amount),0) as total_amount", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->row()->total_amount;
        $this->page_data['bill_retention_amount'] = $this->Bills->select_bills("COALESCE(SUM(bill_retention_amount),0) as total_amount", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->row()->total_amount;
        $this->page_data['bills'] = $this->Bills->select_bills("b.*,u.user_alias as created_user", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->result();
        $this->page_data['budget_balance'] = $this->page_data['subcontract_data']->payable_amount - ($this->page_data['bill_paid_amount'] + $this->page_data['advance_paid_amount']);
        $this->page_data['total_paid'] = $this->page_data['advance_paid_amount']+$this->page_data['subcontract_data']->op_balance+$this->page_data['bill_paid_amount'];

        $this->load->view('Index', $this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }
  public function profile($id="")
  {
    if($id!="") {
      $this->page_data['subcontract_data'] = $this->Subcontracts->select_subcontract("sc.*,u.user_alias,wc.work_name,c.*", array("sc.contract_id" => $id));
      if($this->page_data['subcontract_data']->num_rows()==1){
        $this->page_data['subcontract_data'] = $this->page_data['subcontract_data']->row();
        $this->page_data['work_items'] = $this->Subcontracts->select_subcontract_work_items("scwi.*,wt.type_name,mu.unit_name", array("sc.contract_id" => $id));
        foreach ($this->page_data['work_items']->result() as $key => $value) {
          $acheived_qty = $unit_rate = 0;
          if($this->page_data['subcontract_data']->contract_type=='unit_rate'){
            $unit_rate = $value->unit_rate;
          }
          $this->db->where("b.bill_items like '%".$value->item_id."%'");
          $bills_data = $this->Bills->select_bills("b.bill_id,b.bill_items", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->result();
          foreach ($bills_data as $key2 => $value2) {
            $bill_items = unserialize($value2->bill_items);
            foreach ($bill_items as $key3 => $value3) {
              if($value3['item_id']==$value->item_id && $value3['item_type']=='subcontract_work_item'){
                $acheived_qty += $value3['qty'];
                if($this->page_data['subcontract_data']->contract_type!='unit_rate'){
                  $unit_rate = $value3['unit_rate'];
                }
              }
            }
          }
          $value->acheived_qty = $acheived_qty;
          $value->unit_rate_bill = $unit_rate;
        }

        $this->page_data['deduction_amount'] = $this->Subcontracts->select_subcontract_deductions("COALESCE(SUM(amount),0) as total_amount", array("sd.subcontract_id" => $this->page_data['subcontract_data']->contract_id))->row()->total_amount;
        $this->page_data['no_of_bills'] = $this->Bills->select_bills("b.bill_id", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->num_rows();
        $this->page_data['bill_amount'] = $this->Bills->select_bills("COALESCE(SUM(bill_payable_amount),0) as total_amount", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->row()->total_amount;
        $this->page_data['bill_paid_amount'] = $this->Bills->select_bills("COALESCE(SUM(bill_total_paid),0) as total_amount", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->row()->total_amount;
        $this->page_data['advance_paid_amount'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $this->page_data['subcontract_data']->contract_id, "ats.reference_type" => 'subcontract'), 'subcontract_advance')->row()->total_paid_amount;
        $this->page_data['bill_balance_amount'] = $this->Bills->select_bills("COALESCE(SUM(bill_balance_amount),0) as total_amount", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->row()->total_amount;
        $this->page_data['bill_tds_amount'] = $this->Bills->select_bills("COALESCE(SUM(bill_tds_amount),0) as total_amount", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->row()->total_amount;
        $this->page_data['bill_retention_amount'] = $this->Bills->select_bills("COALESCE(SUM(bill_retention_amount),0) as total_amount", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->row()->total_amount;
        $this->page_data['bills'] = $this->Bills->select_bills("b.*,u.user_alias as created_user", array("b.subcontract_id" => $this->page_data['subcontract_data']->contract_id, "b.bill_type" => 'subcontract'))->result();
        $this->page_data['budget_balance'] = $this->page_data['subcontract_data']->payable_amount - ($this->page_data['bill_paid_amount'] + $this->page_data['advance_paid_amount']);
        $this->page_data['total_paid'] = $this->page_data['advance_paid_amount']+$this->page_data['subcontract_data']->op_balance+$this->page_data['bill_paid_amount'];

        $this->page_data['page_name'] = 'subcontract_profile';
        $this->load->view('Index', $this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }
  public function contractors($type='',$id='')
  {
    if($type=='profile' && $id!=""){
      $this->page_data['contractor_data'] = $this->Subcontracts->select_contractors("*", array("contractor_id" => $id));
      if($this->page_data['contractor_data']->num_rows()==1){
        $this->page_data['contractor_data'] = $this->page_data['contractor_data']->row();
        $this->page_data['page_name'] = 'contractor_profile';
        $this->load->view('Index', $this->page_data);
      }else{
        show_404();
      }
    }else{
      $this->page_data['page_name'] = 'contractors_view';
      $this->load->view('Index', $this->page_data);
    }
  }
  public function material_issue($view='view',$id='')
  {
    $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, wc.assigned_users)");
      $data['wc.assigned_users'] = $supervisor_id;
    }
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations("", $data)->result();
    $this->page_data['stock_locations_warehouse'] = $this->Stock->select_stock_locations("", array('sl.work_id' => '0'))->result();
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->page_data['materials'] = $this->Material->select_material()->result();
    if($view=='add'){
      $this->page_data['page_name'] = 'material_issue_add';
      $this->load->view('Index', $this->page_data);
    }elseif($view=='return'){
      $this->page_data['page_name'] = 'material_issue_return';
      $this->load->view('Index', $this->page_data);
    }else{
      if($id!=''){
        $this->page_data['bill_data'] = $this->Subcontracts->select_material_issue_bill("smb.*,sl.work_id as from_work_id,sl.location_name as from_loc_name,u1.user_alias as created_user,wc.work_location as from_loc_address,c.contractor_name,c.contractor_id,c.phone as contractor_phone,c.contractor_address,u2.user_alias as supervisor_name,u2.phone_no as supervisor_phone", array("smb.bill_id" => $id));
        if ($this->page_data['bill_data']->num_rows() == 1) {
          $this->page_data['bill_data'] = $this->page_data['bill_data']->row();
          $this->page_data['bill_items'] = $this->Subcontracts->select_material_issue_items("smi.*,m.material_name,mu.unit_name,m.material_specification,m.item_code,sr.unit_price,sr.total_balance_qty", array("smi.bill_id" => $id))->result();
          $this->page_data['return_items'] = $this->Subcontracts->select_material_return("smr.*,smi.*,m.material_name,mu.unit_name,m.material_specification,m.item_code,sr.unit_price,sr.total_balance_qty", array("smi.bill_id" => $id))->result();
          if($view=='edit'){
            $this->page_data['page_name'] = 'material_issue_edit';
          }else{
            $this->page_data['page_name'] = 'material_issue_bill';
          }

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

  public function add()
  {
    $this->page_data['work_id'] = "";
    if (isset($_GET['work']) && $_GET['work'] != '') {
      $this->page_data['work_id'] = $_GET['work'];
    }
    $this->page_data['work_types'] = $this->Work->select_work_types()->result();
    $this->page_data['page_name'] = 'subcontracts_add';
    if ($this->session->userdata('user_role') == 'supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    $this->load->view('Index', $this->page_data);
  }
  public function edit($id = '')
  {
    $this->page_data['page_name'] = 'subcontracts_edit';
    if ($this->session->userdata('user_role') == 'supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    if ($id!='') {
      $this->page_data['contract_data'] = $this->Subcontracts->select_subcontract("sc.*,u.user_alias,wc.work_name,c.*", array("sc.contract_id" => $id));
      if ($this->page_data['contract_data']->num_rows() == 1) {
        $this->page_data['contract_data'] = $this->page_data['contract_data']->row();
        $this->page_data['work_items'] = $this->Subcontracts->select_subcontract_work_items("scwi.*,wt.type_name,mu.unit_name", array("sc.contract_id" => $id));
        $this->load->view('Index', $this->page_data);
      } else {
        show_404();
      }
    } else {
      show_404();
    }
  }
  public function labour_attendance($subcontract_id='')
  {
    $this->page_data['subcontract_id'] = $subcontract_id;

    $this->page_data['subcontracts']  = $this->Subcontracts->select_subcontract("sc.*,u.user_alias,wc.work_name,c.*")->result();
    $this->page_data['page_name'] = 'subcontract_labour_attendance';
    $this->load->view('Index', $this->page_data);
  }
  public function payments()
  {
    $this->page_data['work_types'] = $this->Work->select_work_types()->result();
    $this->page_data['page_name'] = 'subcontract_payments';
    if ($this->session->userdata('user_role') == 'supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->load->view('Index', $this->page_data);
  }
  public function add_bill($id="")
  {
    if($id!="") {
      $this->page_data['subcontract_data'] = $this->Subcontracts->select_subcontract("sc.*,u.user_alias,wc.work_name,c.*", array("sc.contract_id" => $id));
      if($this->page_data['subcontract_data']->num_rows()==1){
        $this->page_data['subcontract_data'] = $this->page_data['subcontract_data']->row();
        $this->page_data['bill_types'] = $this->Subcontracts->select_subcontract_bill_types()->result();
        $this->page_data['work_items'] = $this->Subcontracts->select_subcontract_work_items("scwi.*,wt.type_name,mu.unit_name", array("sc.contract_id" => $id));
        $this->page_data['subcontract_labours'] = $this->Subcontracts->select_labours("sl.*,sc.*,sc.phone as contractor_phone,wt.type_name as type_name,u.user_alias",array("sl.contractor_id"=>$this->page_data['subcontract_data']->contractor),'','',"","","")->result();

        $this->page_data['page_name'] = 'subcontract_bill_add';
        $this->load->view('Index', $this->page_data);
      }else{
        show_404();
      }
    }else{
      show_404();
    }
  }
  public function payment_schedule()
  {
    $this->page_data['page_name'] = 'subcontract_payments_schedule';
    $this->page_data['contractors'] = $this->Subcontracts->select_contractors()->result();
    $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['work_types'] = $this->Work->select_work_types()->result();

    $this->page_data['contract_data'] = $this->Subcontracts->select_subcontract("sc.*,u.user_alias,wc.work_name")->result();

    $this->page_data['selected_start_date'] = $this->page_data['selected_end_date'] = "";
    if (isset($_GET['start_date']) && $_GET['start_date'] != '') {
      $this->page_data['selected_start_date'] = $_GET['start_date'];
    }
    if (isset($_GET['end_date']) && $_GET['end_date'] != '') {
      $this->page_data['selected_end_date'] = $_GET['end_date'];
    }


    $this->page_data['clients'] = $this->Client->select_client("")->result();
    $this->load->view('Index', $this->page_data);
  }

  public function labours()
  {
    $this->page_data['work_types'] = $this->Work->select_work_types()->result();
    $this->page_data['page_name'] = 'subcontract_labours';
    if ($this->session->userdata('user_role') == 'supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
    $this->load->view('Index', $this->page_data);
  }

  public function create()
  {
    $redirect_url = $this->security->xss_clean($this->input->post('redirect_url'));
    $data2['sub_work_name'] = $this->security->xss_clean($this->input->post('sub_work_name'));
    $data2['contractor'] = $this->security->xss_clean($this->input->post('contractor'));
    $data2['contract_type'] = $this->security->xss_clean($this->input->post('contract_type'));
    $data2['description'] = $this->security->xss_clean($this->input->post('description'));
    $data2['reference_no'] = $this->security->xss_clean($this->input->post('reference_no'));
    $data2['retention_amount'] = $this->security->xss_clean($this->input->post('retention_amount'));
    $data2['retention_percent'] = $this->security->xss_clean($this->input->post('retention_percent'));
    $data2['payable_amount'] = $this->security->xss_clean($this->input->post('payable_amount'));
    $data2['billing_address'] = $this->security->xss_clean($this->input->post('billing_address'));
    $data2['billing_address_id'] = $this->security->xss_clean($this->input->post('billing_address_id'));
    if($this->input->post('date')!=''){
      $data2['subcontract_date'] = date('Y-m-d',strtotime($this->input->post('date')));
    }
    $data2['work_id'] = $flash_data['work_id'] = $this->security->xss_clean($this->input->post('work_id'));
    $data2['created_date'] = date('Y-m-d H:i:s');
    $data2['created_by'] = $this->session->userdata('user_id');

    $data2['project_stage_id'] = $this->projects_management->get_project_stage_id($data2['work_id']);

    //terms and conditions
    $terms_array=$newArrayterms=array();
    if($this->input->post('terms')){
      $terms_array = $this->input->post('terms');
      $terms_array_length = sizeof($terms_array);
      foreach (array_keys($terms_array) as $fieldKey) {
        foreach ($terms_array[$fieldKey] as $key=>$value) {
          $newArrayterms[$key][$fieldKey] = $value;
        }
      }
      $i = 0;
      foreach ($newArrayterms as $row) {
        $terms_new[$i]['title'] = $row['title'];
        $terms_new[$i]['description'] = $row['description'];
        $i++;
      }
      $data2['terms_and_conditions'] = serialize($terms_new);
    }else{
      $data2['terms_and_conditions'] = '';
    }

    $result2 =  $this->Subcontracts->create_subcontract($data2);
    $flash_data['status'] = $result2['status'];
    if ($result2['status'] == 1) {
      $data3['subcontract_id'] = $flash_data['subcontract_id'] = $subcontract_data['contract_id'] =  $result2['insert_id'];
      $data3['created_date'] = date('Y-m-d H:i:s');
      $data3['created_by'] = $this->session->userdata('user_id');
      $subcontract_data['work_type_id'] = "";
      $subcontract_data['total_budget'] = 0;
      $subcontract_data['op_balance'] = $this->security->xss_clean($this->input->post('opening_balance'));
      $work_types = array();
      // Add Work Items
      $work_array = $newArraywork = array();
      if ($this->input->post('work')) {
        $work_array = $this->input->post('work');
      }
      $work_array_length = sizeof($work_array);
      //      Convert to New Formatted Array
      foreach (array_keys($work_array) as $fieldKey) {
        foreach ($work_array[$fieldKey] as $key => $value) {
          $newArraywork[$key][$fieldKey] = $value;
        }
      }
      foreach ($newArraywork as $row) {
        $data3['work_type'] = $row['work_type'];
        $work_types[] = $row['work_type'];
        if($data2['contract_type']=='unit_rate'){
          $data3['measure_unit'] = $row['unit'];
          $data3['unit_rate'] = $row['unit_rate'];
          $data3['qty'] = $row['quantity'];
          $data3['tax_percent'] = $row['tax_percentage'];
        }else{
          unset($data3['measure_unit']);
          unset($data3['unit_rate']);
          unset($data3['qty']);
        }
        $data3['work_details'] = $row['work_description'];
        $data3['est_amount'] = $row['est_amount'];

        $subcontract_data['total_budget']+=$row['est_amount'];
        $data3['remarks'] = $row['remarks'];
        $result3 =  $this->Subcontracts->create_subcontract_work_item($data3);
      }
      // Update Subcontract
      $subcontract_data['work_type_id'] = implode(",", $work_types);
      $result =  $this->Subcontracts->update_subcontract($subcontract_data);

      $flash_data['flashdata_msg'] = 'Subcontract Work Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
      $flash_data['contract_id'] = $result2['insert_id'];
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];

    echo json_encode($flash_data);
  }
  public function update()
  {
    $redirect_url = $this->security->xss_clean($this->input->post('redirect_url'));
    $data2['contract_id'] = $this->security->xss_clean($this->input->post('contract_id'));
    $data2['sub_work_name'] = $this->security->xss_clean($this->input->post('sub_work_name'));
    $data2['contractor'] = $this->security->xss_clean($this->input->post('contractor'));
    $data2['contract_type'] = $this->security->xss_clean($this->input->post('contract_type'));
    $data2['description'] = $this->security->xss_clean($this->input->post('description'));
    $data2['reference_no'] = $this->security->xss_clean($this->input->post('reference_no'));
    $data2['retention_amount'] = $this->security->xss_clean($this->input->post('retention_amount'));
    $data2['retention_percent'] = $this->security->xss_clean($this->input->post('retention_percent'));
    $data2['payable_amount'] = $this->security->xss_clean($this->input->post('payable_amount'));
    $data2['billing_address'] = $this->security->xss_clean($this->input->post('billing_address'));
    $data2['billing_address_id'] = $this->security->xss_clean($this->input->post('billing_address_id'));
    if($this->input->post('date')!=''){
      $data2['subcontract_date'] = date('Y-m-d',strtotime($this->input->post('date')));
    }
    $data2['work_id'] = $flash_data['work_id'] = $this->security->xss_clean($this->input->post('work_id'));
    $data2['updated_date'] = date('Y-m-d H:i:s');
    $data2['updated_by'] = $this->session->userdata('user_id');

    //terms and conditions
    $terms_array=$newArrayterms=array();
    if($this->input->post('terms')){
      $terms_array = $this->input->post('terms');
      $terms_array_length = sizeof($terms_array);
      foreach (array_keys($terms_array) as $fieldKey) {
        foreach ($terms_array[$fieldKey] as $key=>$value) {
          $newArrayterms[$key][$fieldKey] = $value;
        }
      }
      $i = 0;
      foreach ($newArrayterms as $row) {
        $terms_new[$i]['title'] = $row['title'];
        $terms_new[$i]['description'] = $row['description'];
        $i++;
      }
      $data2['terms_and_conditions'] = serialize($terms_new);
    }else{
      $data2['terms_and_conditions'] = '';
    }

    $result2 =  $this->Subcontracts->update_subcontract($data2);
    $flash_data['status'] = $result2;
    if ($result2 == 1) {
      $flash_data['subcontract_id'] = $subcontract_data['contract_id'] =  $data2['contract_id'];

      $subcontract_data['work_type_id'] = "";
      $subcontract_data['total_budget'] = 0;
      $subcontract_data['op_balance'] = $this->security->xss_clean($this->input->post('opening_balance'));

      $work_types = array();
      // Add Work Items
      $work_array = $newArraywork = array();
      if ($this->input->post('work')) {
        $work_array = $this->input->post('work');
      }
      $work_array_length = sizeof($work_array);
      //      Convert to New Formatted Array
      foreach (array_keys($work_array) as $fieldKey) {
        foreach ($work_array[$fieldKey] as $key => $value) {
          $newArraywork[$key][$fieldKey] = $value;
        }
      }
      foreach ($newArraywork as $row) {
        $data3 = array();
        $data3['work_type'] = $row['work_type'];
        $work_types[] = $row['work_type'];
        if($data2['contract_type']=='unit_rate'){
          $data3['measure_unit'] = $row['unit'];
          $data3['unit_rate'] = $row['unit_rate'];
          $data3['qty'] = $row['quantity'];
          $data3['tax_percent'] = $row['tax_percentage'];
        }else{
          unset($data3['measure_unit']);
          unset($data3['unit_rate']);
          unset($data3['qty']);
        }
        $data3['work_details'] = $row['work_description'];
        $data3['est_amount'] = $row['est_amount'];
        $subcontract_data['total_budget'] += $row['est_amount'];
        $data3['remarks'] = $row['remarks'];
        if (isset($row['item_id']) && $row['item_id'] != '') {
          // Update Existing Data
          $data3['item_id'] = $row['item_id'];
          $data3['updated_date'] = date('Y-m-d H:i:s');
          $data3['updated_by'] = $this->session->userdata('user_id');
          $result3 =  $this->Subcontracts->update_subcontract_work_item($data3);
        } else {
          // Create New Data
          $data3['subcontract_id'] = $data2['contract_id'];
          $data3['created_date'] = date('Y-m-d H:i:s');
          $data3['created_by'] = $this->session->userdata('user_id');
          $result3 =  $this->Subcontracts->create_subcontract_work_item($data3);
        }
      }
      // Update Subcontract
      $subcontract_data['work_type_id'] = implode(",", $work_types);
      $result =  $this->Subcontracts->update_subcontract($subcontract_data);

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

      $flash_data['flashdata_msg'] = 'Subcontract Work Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];

    echo json_encode($flash_data);
  }
  public function delete()
  {
    $redirect_url = $this->security->xss_clean($this->input->post('redirect_url'));
    $data2['contract_id'] = $this->security->xss_clean($this->input->post('contract_id'));
    $data2['delete_status'] = 1;
    $result2 = $this->Subcontracts->update_subcontract($data2);

    $flash_data['status'] = $result2;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Subcontract Work Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }
  public function approve()
  {
    $data2['contract_id'] = $this->security->xss_clean($this->input->post('subcontract_id'));
    $data2['contract_approval_status'] = $this->security->xss_clean($this->input->post('subcontract_approval_status'));
    $result2 = $this->Subcontracts->update_subcontract($data2);

    $flash_data['status'] = $result2;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Subcontract Approval 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 select_subcontracts()
  {

    $json_data = array();
    $j = 0;
    $sl_no = 0;
    $total_op_balance_paid = $total_advance_paid = $total_no_of_bills = $total_paid_amount = $total_balance_payable = $total_no_of_bills = $total_bill_amount = $total_tds_amount = $total_retention_amount = $total_bill_paid_amount = $total_bill_balance_amount = $total_budget = $total_budget_balance = 0;
    $data = array();
    if (isset($_POST['contractor']) && $_POST['contractor'] != '' && $_POST['contractor'] != 'all') {
      $data['sc.contractor'] = $_POST['contractor'];
    }
    if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
      $data['wc.work_id'] = $_POST['work'];
    }
    if (isset($_POST['work_id']) && $_POST['work_id'] != '' && $_POST['work_id'] != 'all') {
      $data['wc.work_id'] = $_POST['work_id'];
    }
    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['stage_id']) && $_POST['stage_id'] != '' && $_POST['stage_id'] != 'all') {
      $data['sc.project_stage_id'] = $_POST['stage_id'];
    }
    if (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['subcontractname']) && $_POST['subcontractname'] != '' && $_POST['subcontractname'] != 'all') {
      $data['sc.sub_work_name'] = $_POST['subcontractname'];
    }
    if (isset($_POST['start_date']) && $_POST['start_date'] != '' && $_POST['start_date'] != 'all') {
      $data['sc.created_date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if (isset($_POST['end_date']) && $_POST['end_date'] != '' && $_POST['end_date'] != 'all') {
      $data['sc.created_date <='] = date('Y-m-d', strtotime($_POST['end_date']));
    }
    if ($this->session->userdata('user_role') == 'supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    }
    if (isset($_POST['user_id']) && $_POST['user_id'] != '' && $_POST['user_id'] != 'all') {
      $data['sc.created_by'] = $_POST['user_id'];
    }
    if ($this->session->userdata('user_role') != 'qs_manager' && $this->session->userdata('user_role') != 'qs' && $this->session->userdata('user_role') != 'general_manager' &&  $this->session->userdata('user_role') != 'auditor' && $this->config->item('user_data_access_view_all') != 1) {
      $data['sc.created_by'] = $this->session->userdata('user_id');
    }
    if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
      $data['wc.branch_id'] = $_POST['branch_id'];
    }
    $result  = $this->Subcontracts->select_subcontract("sc.*,u.user_alias,wc.work_name,c.*,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 = $select_array = array();

    foreach ($result_array as $row) :
      $sl_no++;
      $id = $row->work_id;
      $btn_edit = $btn_delete = $btn_add_bill = '';
      if ($this->session->userdata('user_role') == 'admin' || $this->session->userdata('user_role') == 'general_manager' || $this->session->userdata('user_role') == 'qs_manager' || $this->session->userdata('user_id')==$row->created_by) {
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px"  href="' . base_url() . 'subcontracts/edit/' . $row->contract_id . '"  class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete = '<a style="margin-left: 5px;margin-right: 5px" id="subcontract_delete_btn" href="#subcontract_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-trash"></i>
        </a>';
      }

      if($this->session->userdata('user_role') != 'auditor' || $this->session->userdata('user_data_permission')['adding']==1){
        $btn_add_bill = '<a style="margin-left: 5px;margin-right: 5px" target="_blank" href="'.base_url().'subcontracts/add_bill/'.$row->contract_id.'"  class="btn btn-focus m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="fa fa-plus"></i>
        </a>';
      }
      $btn_subcontract_approval = $subcontract_approval_status = '';
      if($this->config->item('Mobile_App_subcontract_entry_approval')==1){
        if($row->contract_approval_status==1){
          $subcontract_approval_status='<br/><span class="m-badge m-badge--success m-badge--wide">Approved</span>';
        }elseif($row->contract_approval_status==2){
          $subcontract_approval_status='<br/><span class="m-badge m-badge--danger m-badge--wide">Rejected</span>';
        }else{
          $subcontract_approval_status='<br/><span class="m-badge m-badge--warning m-badge--wide">Pending</span>';
        }
        $btn_subcontract_approval = '<a style="margin-left: 5px;margin-right: 5px" data-approval-status="'.$row->contract_approval_status.'"  id="btn_approve_subcontract" href="#subcontract_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>';
      }

      $contract_type = "";
      if ($row->contract_type == 'fixed_rate') {
        $contract_type = "<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Fixed Rate</span>";
      } else {
        $contract_type = "<span class='m-badge m-badge--info m-badge--wide'><i class='fa fa-ellipsis-h'></i> Unit Rate</span>";
      }
      $work_types = "<ul style='padding-left: 25px;margin-bottom: 0'>";
      $work_types_array = explode(",", $row->work_type_names);
      foreach ($work_types_array as $key => $value) {
        $work_types .= "<li>" . $value . "</li>";
      }
      $work_types .= "</ul>";


      $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();
      $no_of_bills = $bill_details->bill_count;
      $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;
      $bill_balance_amount = $bill_details->bill_balance_amount;
      $bill_tds_amount = $bill_details->bill_tds_amount;
      $bill_retention_amount = $bill_details->bill_retention_amount;
      $total_paid = $row->op_balance + $bill_paid_amount + $advance_paid_amount;
      $balance_payable = $bill_amount - $total_paid;

      $contractor = $row->contractor_name;

      $btn_print='<a data-contract-id="'.$row->contract_id.'" style="margin-left: 5px;margin-right: 5px" id="btn_print_subcontract"  class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
      <i class="fa fa-print"></i>
      </a>';

      // $description = strip_tags($row->description);
      // $description = substr($description,0,100);
      $description = '';

      $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().'subcontracts/profile/'.$row->contract_id.'">#' . $row->contract_id . '</a>';
      $array[$j][] = '<a href="' . base_url() . 'work/profile/' . $id . '">' . $row->work_name . '</a>';
      $array[$j][] = $work_types;
      $array[$j][] = $contract_type;
      $select_array[$j]['sub_work_name'] = $array[$j][] = '<a href="'.base_url().'subcontracts/profile/'.$row->contract_id.'">' . $row->sub_work_name . '</a>';
      $select_array[$j]['contractor'] = $array[$j][] = $contractor;
      $array[$j][] = $description;
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($row->total_budget, $this->config->item('Currency_currency_shortname'));
      $array[$j][] = $no_of_bills;
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($bill_amount, $this->config->item('Currency_currency_shortname'));
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($bill_paid_amount, $this->config->item('Currency_currency_shortname'));
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($bill_balance_amount, $this->config->item('Currency_currency_shortname'));
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($row->op_balance, $this->config->item('Currency_currency_shortname'));
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($advance_paid_amount, $this->config->item('Currency_currency_shortname'));
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($row->op_balance + $bill_paid_amount + $advance_paid_amount, $this->config->item('Currency_currency_shortname'));
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($balance_payable, $this->config->item('Currency_currency_shortname'));
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($bill_tds_amount, $this->config->item('Currency_currency_shortname'));
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($bill_retention_amount, $this->config->item('Currency_currency_shortname'));
      if ($row->total_budget > 0) {
        $array[$j][] = $this->config->item('currency_format')->formatCurrency(($row->total_budget - $bill_tds_amount - ($row->op_balance + $bill_paid_amount + $advance_paid_amount)), $this->config->item('Currency_currency_shortname'));
      } else {
        $array[$j][] = $this->config->item('currency_format')->formatCurrency(0, $this->config->item('Currency_currency_shortname'));
      }
      $array[$j][] = $row->user_alias.$subcontract_approval_status;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][] = date('d-m-Y', strtotime($row->created_date));
      }else{
        $array[$j][] = '';
      }
      $array[$j][] = $btn_add_bill . $btn_edit .$btn_print. $btn_delete.$btn_subcontract_approval;
      $array[$j][] = $row->work_type_id;
      $array[$j][] = $row->work_id;
      $select_array[$j]['contract_id'] = $array[$j][] = $row->contract_id;

      $total_no_of_bills += $no_of_bills;
      $total_tds_amount += $bill_tds_amount;
      $total_retention_amount += $bill_retention_amount;
      $total_bill_amount += $bill_amount;
      $total_bill_paid_amount += $bill_paid_amount + $advance_paid_amount;
      $total_bill_balance_amount += $bill_balance_amount;
      $total_budget += $row->total_budget;
      $total_budget_balance += ($row->total_budget - $total_paid);
      $total_balance_payable += $balance_payable;
      $total_paid_amount += $total_paid;
      $total_op_balance_paid += $row->op_balance;
      $total_advance_paid += $advance_paid_amount;

      $j++;
    endforeach;
    if ($result->num_rows() > 0) {
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = "";
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = "<strong>Total</strong>";
      $array[$j][] = "<strong>" . $this->config->item('currency_format')->formatCurrency($total_budget, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" .$total_no_of_bills."</strong>";
      $array[$j][] = "<strong>" . $this->config->item('currency_format')->formatCurrency($total_bill_amount, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" . $this->config->item('currency_format')->formatCurrency($total_bill_paid_amount, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" . $this->config->item('currency_format')->formatCurrency($total_bill_balance_amount, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" . $this->config->item('currency_format')->formatCurrency($total_op_balance_paid, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" . $this->config->item('currency_format')->formatCurrency($total_advance_paid, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" . $this->config->item('currency_format')->formatCurrency($total_paid_amount, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" . $this->config->item('currency_format')->formatCurrency($total_balance_payable, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" . $this->config->item('currency_format')->formatCurrency($total_tds_amount, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" . $this->config->item('currency_format')->formatCurrency($total_retention_amount, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" . $this->config->item('currency_format')->formatCurrency($total_budget_balance, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
    }

    $json_data['data'] = $array;

    if (isset($_POST['list_type']) && $_POST['list_type'] == 'select2_options') {
      $json_data = $select_array;
    }
    echo json_encode($json_data);  // send data as json format
  }
  public function select_subcontract_bills($page_data_type = '')
  {

    $json_data = array();
    $j = $sl_no = $total_other_deduction = $total_retention_amount = $total_tds_amount = $total_tax_amount = $total_bill_amount = $total_paid_amount = $total_balance_amount = $total_tax1_amount=$total_tax2_amount=$total_tax3_amount=0;
    $data = array();
    if (isset($_POST['date']) && $_POST['date'] != '') {
      $date = array();
      $date = explode('-', $_POST['date']);
      $start_date = date('Y-m-d', strtotime($date[0]));
      $end_date = date('Y-m-d', strtotime($date[1]));
      $data["STR_TO_DATE(b.bill_date,'%Y-%m-%d') <="] = $end_date;
      $data["STR_TO_DATE(b.bill_date,'%Y-%m-%d') >="] = $start_date;
    }
    if (isset($_POST['contract_id']) && $_POST['contract_id'] != '' && $_POST['contract_id'] != 'all') {
      $data['b.subcontract_id'] = $_POST['contract_id'];
    }
    if (isset($_POST['contractor']) && $_POST['contractor'] != '' && $_POST['contractor'] != 'all') {
      $data['c.contractor_id'] = $_POST['contractor'];
    }
    if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
      $data['b.work_id'] = $_POST['work'];
    }
    if (isset($_POST['user_id']) && $_POST['user_id'] != '' && $_POST['user_id'] != 'all') {
      $data['b.created_by'] = $_POST['user_id'];
    }
    if (isset($_POST['start_date']) && $_POST['start_date'] != '' && $_POST['start_date'] != 'all') {
      $data['b.bill_date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if (isset($_POST['end_date']) && $_POST['end_date'] != '' && $_POST['end_date'] != 'all') {
      $data['b.bill_date <='] = date('Y-m-d', strtotime($_POST['end_date']));
    }
    if(isset($_POST['payment_status']) && $_POST['payment_status']!='' && $_POST['payment_status']!='all'){
      $data['b.bill_payment_status'] = $_POST['payment_status'];
    }
    if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
      $data['wc.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)");
    }
    if ($this->session->userdata('user_role') != 'auditor' && $this->config->item('user_data_access_view_all') != 1) {
      $data['b.created_by'] = $this->session->userdata('user_id');
    }
    $entry_approval = 1;
    if($this->config->item('User_enable_data_entry_approval')==1){//webapp users approval
      $entry_approval = 'all';
    }
    if($page_data_type=='approval_entries'){
      $entry_approval = 'all';
      $data['u.user_role >'] =2;
      if(isset($_POST['approval_status']) && $_POST['approval_status']!='' && $_POST['approval_status']!='all'){
        $entry_approval = $_POST['approval_status'];
      }
    }

    $data['b.bill_type'] = 'subcontract';
    $result  = $this->Bills->select_bills("b.*,c.contractor_name,ah1.acc_head_name as credtit_account,u.user_alias,wc.work_name,sc.contractor,sc.sub_work_name,sc.contract_id,tt.tax_percentage,tt.tax1_percent,tt.tax2_percent,tt.tax3_percent,u.user_role as created_user_role_id,wc.branch_id", $data,'','','',$entry_approval);
    $result_array = $result->result();

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

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

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

      if ($row->bill_payment_status == 1) {
        $bill_payment_status = "<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Paid</span>";
      } elseif ($row->bill_payment_status == 2) {
        $bill_payment_status = "<span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-ellipsis-h'></i> Partially Paid</span>";
      } else {
        $bill_payment_status = "<span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-times-circle'></i> Not Paid</span>";
      }
      $bill_attachment = $bill_attachment_url = $bill_attachment_btn = "";
      if ($row->bill_attachment != '') {
        $bill_attachment = $row->bill_attachment;
        $bill_attachment_url =  base_url() . "uploads/bills/" . $bill_attachment;
        $bill_attachment_btn = '<a target="_blank" href="' . $bill_attachment_url . '">View Attachment</a>';
      }
      $bill_taxable_amount = $row->bill_gross_amount;
      $row->bill_tax1_amount = round($row->bill_gross_amount*$row->tax1_percent/100,$this->config->item('Currency_amount_decimals_2'));
      $row->bill_tax2_amount = round($row->bill_gross_amount*$row->tax2_percent/100,$this->config->item('Currency_amount_decimals_2'));
      $row->bill_tax3_amount = round($row->bill_gross_amount*$row->tax3_percent/100,$this->config->item('Currency_amount_decimals_2'));
      $consignee = $row->bill_consignee_name;
      if($row->bill_consignee_name==''){
        $consignee = $row->contractor_name;
      }

      $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="subcontract_bill" data-id="' . $row->bill_id . '" href="javascript:;">#' . $row->bill_id . '</a>';
      $array[$j][] = date('d-m-Y', strtotime($row->bill_date));
      $array[$j][] = '<a href="' . base_url() . 'work/profile/' . $id . '">' . $row->work_name . '</a>';
      $array[$j][] = $row->sub_work_name;
      $array[$j][] = "";
      $array[$j][] = $row->contractor_name;
      $array[$j][] = $row->bill_no;
      $array[$j][] = $consignee;
      $array[$j][] = number_format($row->bill_gross_amount, $this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=$row->tax_percentage."%";
      $array[$j][]=number_format($row->bill_tax_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=$row->tax1_percent;
      $array[$j][]=number_format($row->bill_tax1_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=$row->tax2_percent;
      $array[$j][]=number_format($row->bill_tax2_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=$row->tax3_percent;
      $array[$j][]=number_format($row->bill_tax3_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][] = number_format($row->bill_tds_amount, $this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][] = number_format($row->bill_retention_percent, $this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][] = number_format($row->bill_retention_amount, $this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][] = number_format($row->other_deductions, $this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][] = number_format($row->bill_payable_amount, $this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][] = number_format($row->bill_total_paid, $this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][] = number_format($row->bill_balance_amount, $this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][] = $bill_payment_status;
      $array[$j][] = $row->bill_description;
      $array[$j][] = $bill_attachment_btn;
      $array[$j][] = $row->subcontract_labours_no;
      $array[$j][] = $row->bill_remarks;
      $array[$j][] = $row->user_alias.$entry_approval_status;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][] = date('d-m-Y', strtotime($row->created_date));
      }else{
        $array[$j][] = '';
      }
      $array[$j][] = $btn_add_payment . $btn_edit . $btn_delete.$btn_approve;
      $array[$j][] = $row->bill_id;
      $array[$j][] = $row->contract_id;
      $array[$j][] = $bill_attachment;
      $array[$j][] = $row->bill_tax_percent;
      $array[$j][] = $row->entry_approval_status;

      $total_tds_amount += $row->bill_tds_amount;
      $total_retention_amount += $row->bill_retention_amount;
      $total_other_deduction += $row->other_deductions;
      $total_tax_amount += $row->bill_tax_amount;
      $total_tax1_amount+=$row->bill_tax1_amount;
      $total_tax2_amount+=$row->bill_tax2_amount;
      $total_tax3_amount+=$row->bill_tax3_amount;
      $total_bill_amount += $row->bill_payable_amount;
      $total_paid_amount += $row->bill_total_paid;
      $total_balance_amount += $row->bill_balance_amount;

      $j++;
    endforeach;
    if ($result->num_rows() > 0) {
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = "<strong>Total</strong>";
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][]='';
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_tax_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]='';
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_tax1_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]='';
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_tax2_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][]='';
      $array[$j][]="<strong>".$this->config->item('Currency_currency_format')." ".$this->config->item('currency_format')->formatCurrency($total_tax3_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][] = "<strong>" . $this->config->item('Currency_currency_format') . " " . $this->config->item('currency_format')->formatCurrency($total_tds_amount, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "";
      $array[$j][] = "<strong>" . $this->config->item('Currency_currency_format') . " " . $this->config->item('currency_format')->formatCurrency($total_retention_amount, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" . $this->config->item('Currency_currency_format') . " " . $this->config->item('currency_format')->formatCurrency($total_other_deduction, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" . $this->config->item('Currency_currency_format') . " " . $this->config->item('currency_format')->formatCurrency($total_bill_amount, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" . $this->config->item('Currency_currency_format') . " " . $this->config->item('currency_format')->formatCurrency($total_paid_amount, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "<strong>" . $this->config->item('Currency_currency_format') . " " . $this->config->item('currency_format')->formatCurrency($total_balance_amount, $this->config->item('Currency_currency_shortname')) . "</strong>";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
      $array[$j][] = "";
    }

    $json_data['data'] = $array;
    echo json_encode($json_data);  // send data as json format
  }
  public function select_subcontracts_list(){
    $data = array();
    if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
      $data['wc.work_id'] = $_POST['work'];
    }
    if (isset($_POST['contractor']) && $_POST['contractor'] != '' && $_POST['contractor'] != 'all') {
      $data['sc.contractor'] = $_POST['contractor'];
    }
    $result = $this->Subcontracts->select_subcontract("sc.*,u.user_alias,wc.work_name,c.*,wc.branch_id,c.phone as contractor_phone", $data);
    if($result->num_rows()>0) {
      echo json_encode(array("count" => $result->num_rows(),"data" => $result->result()));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }

  public function select_subcontract_bills_2($list_type = '')
  {

    $json_data = array();
    $j = $sl_no = $total_bill_amount = $total_paid_amount = $total_balance_amount = 0;
    $data = array();
    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['user_id']) && $_POST['user_id'] != '' && $_POST['user_id'] != 'all') {
      $data['b.created_by'] = $_POST['user_id'];
    }
    if ($this->session->userdata('user_role') == 'supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    }
    if ($this->session->userdata('user_role') != 'auditor' && $this->config->item('user_data_access_view_all') != 1) {
      $data['b.created_by'] = $this->session->userdata('user_id');
    }
    $data['b.bill_type'] = 'subcontract';
    $data['b.bill_balance_amount >'] = 0;
    $result  = $this->Bills->select_bills("b.*,c.contractor_name,ah1.acc_head_name as credtit_account,u.user_alias,wc.work_name,sc.contractor,sc.sub_work_name,sc.contract_id,", $data);
    $result_array = $result->result();

    $array = array();

    foreach ($result_array as $row) :
      $sl_no++;

      $array['bill_id'][$j] = $row->bill_id;
      $array['bill_no'][$j] = $row->bill_no;
      $array['payable_amount'][$j] = $this->config->item('currency_format')->formatCurrency($row->bill_payable_amount, $this->config->item('Currency_currency_shortname'));
      $array['balance_amount'][$j] = $this->config->item('currency_format')->formatCurrency($row->bill_balance_amount, $this->config->item('Currency_currency_shortname'));
      $array['bill_date'][$j] = date('d-m-Y', strtotime($row->bill_date));

      $j++;
    endforeach;
    $array['count'] = $result->num_rows();
    echo json_encode($array);  // send data as json format
  }
  public function select_subcontract_payments_by_type($list_type = "")
  {

    $json_data = array();
    $j = 0;
    $sl_no = 0;
    $total_paid_amount = $total_budget_amount = 0;
    $data1 = array();
    if (isset($_POST['work_type']) && $_POST['work_type'] != '' && $_POST['work_type'] != 'all') {
      $data1['type_id'] = $_POST['work_type'];
    }
    $result  = $this->Work->select_work_types("", $data1);
    $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++;
    //   $data3 = $data2 = array();
    //   if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
    //     $data3['sc.work_id'] = $data2['sc.work_id'] = $_POST['work'];
    //   }
    //   if ($this->session->userdata('user_role') != 'admin') {
    //     $data2['sc.created_by'] = $this->session->userdata('user_id');
    //   }
    //
    //   if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
    //     $data2['wc.branch_id'] = $_POST['branch_id'];
    //   }
    //
    //
    //   $this->db->where("FIND_IN_SET($row->type_id, sc.work_type_id)");
    //   $subcontract_results  = $this->Subcontracts->select_subcontract("COALESCE(SUM(total_budget),0) as total_budget_amount,sc.contract_id,sc.work_id,work_name", $data2);
    //
    //   $array[$j][] = $sl_no;
    //   if ($list_type == 'all') {
    //     if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
    //       $work_details = $this->Work->select_work("work_name", array("work_id" => $_POST['work']));
    //       $array[$j][] = '<a href="' . base_url() . 'work/profile/' . $_POST['work'] . '">' . $work_details->row()->work_name . '</a>';
    //     } else {
    //       $array[$j][] = "";
    //     }
    //   }
    //   $array[$j][] = $row->type_name;
    //   $total_budget_amount = $paid_amount = 0;
    //   // Select Paid Amount
    //   $transaction_where = 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]));
    //     $transaction_where["STR_TO_DATE(ats.tr_date,'%Y-%m-%d') <="] = $end_date;
    //     $transaction_where["STR_TO_DATE(ats.tr_date,'%Y-%m-%d') >="] = $start_date;
    //   }
    //   if ($this->session->userdata('user_role') != 'auditor' && $this->session->userdata('user_role') != 'admin') {
    //     $transaction_where['ats.created_by']  = $this->session->userdata('user_id');
    //   }
    //   foreach ($subcontract_results->result() as $key => $value) {
    //
    //     $total_budget_amount += $value->total_budget_amount;
    //
    //     $this->db->where("((ats.tr_type='subcontract_bill_transaction' and sc.contract_id=" . $value->contract_id . ") or (ats.tr_type='subcontract_advance_transaction' and sc2.contract_id=" . $value->contract_id . "))");
    //     $this->db->where("(ats.reference_type='subcontract_bill' or ats.reference_type='subcontract')");
    //     $paid_amount += $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", $transaction_where, 'subcontract_transactions')->row()->total_paid_amount;
    //   }
    //   $array[$j][] = $total_budget_amount;
    //   $array[$j][] = $paid_amount;
    //   $j++;
    //
    // endforeach;

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

    $json_data = array();
    $j = 0;
    $sl_no = 0;
    $total_labour_wage = $total_no_of_days = 0;
    $data = array();
    if (isset($_POST['date']) && $_POST['date'] != '') {
      $date = array();
      $date = explode('-', $_POST['date']);
      $start_date = date('Y-m-d', strtotime($date[0]));
      $end_date = date('Y-m-d', strtotime($date[1]));
      $data["STR_TO_DATE(b.bill_date,'%Y-%m-%d') <="] = $end_date;
      $data["STR_TO_DATE(b.bill_date,'%Y-%m-%d') >="] = $start_date;
    }
    if (isset($_POST['contract_id']) && $_POST['contract_id'] != '' && $_POST['contract_id'] != 'all') {
      $data['b.subcontract_id'] = $_POST['contract_id'];
    }
    if (isset($_POST['contractor']) && $_POST['contractor'] != '' && $_POST['contractor'] != 'all') {
      $data['c.contractor_id'] = $_POST['contractor'];
    }
    if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
      $data['b.work_id'] = $_POST['work'];
    }
    if ($this->session->userdata('user_role') == 'supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    }
    if (isset($_POST['user_id']) && $_POST['user_id'] != '' && $_POST['user_id'] != 'all') {
      $data['sc.created_by'] = $_POST['user_id'];
    }
    if ($this->session->userdata('user_role') != 'qs_manager' && $this->session->userdata('user_role') != 'qs' && $this->session->userdata('user_role') != 'general_manager' &&  $this->session->userdata('user_role') != 'auditor' && $this->config->item('user_data_access_view_all') != 1) {
      $data['sc.created_by'] = $this->session->userdata('user_id');
    }
    if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
      $data['wc.branch_id'] = $_POST['branch_id'];
    }
    $result  = $this->Subcontracts->select_subcontract_labour_wage("slw.*,sl.daily_wage,sl.labour_contact,sl.labour_name,sl.skill_type,wt.type_name,wc.work_name,wc.work_id,b.bill_id,b.bill_date,c.contractor_name", $data);
    $result_array = $result->result();

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

    foreach ($result_array as $row) :
      $sl_no++;

      $array[$j][] = $sl_no;
      $array[$j][] = '<a id="m_quick_sidebar_toggle" data-type="bill_profile" data-bill-type="subcontract_bill" data-id="' . $row->bill_id . '" href="javascript:;">#' . $row->bill_id . '</a>';
      $array[$j][] = date('d-m-Y', strtotime($row->bill_date));
      $array[$j][] = '<a href="' . base_url() . 'work/profile/' .$row->work_id. '">' . $row->work_name . '</a>';
      $array[$j][] = $row->contractor_name;
      $array[$j][] = $row->labour_name;
      $array[$j][] = $row->skill_type;
      $array[$j][] = $row->labour_contact;
      $array[$j][] = $row->daily_wage;
      $array[$j][] = $row->no_of_days;
      $array[$j][] = number_format($row->no_of_days*$row->daily_wage, $this->config->item('Currency_amount_decimals_2'),'.','');
      $total_labour_wage += $row->no_of_days*$row->daily_wage;
      $total_no_of_days += $row->no_of_days;


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

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

    $json_data = array();
    $j = 0;
    $sl_no = 0;
    $profile_data = "";
    $total_no_of_bills = $total_bill_amount = $total_bill_paid_amount = $total_bill_balance_amount = $total_budget = $total_budget_balance = 0;
    $data = array();
    if (isset($_POST['contract_id']) && $_POST['contract_id'] != '' && $_POST['contract_id'] != 'all') {
      $data['sc.contract_id'] = $_POST['contract_id'];
    }
    $result  = $this->Subcontracts->select_subcontract("sc.*,u.user_alias,wc.work_name,c.contractor_name", $data);
    if ($result->num_rows() == 1) {
      $row = $result->row();

      if ($row->contract_type == 'fixed_rate') {
        $contract_type = "<span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Fixed Rate</span>";
      } else {
        $contract_type = "<span class='m-badge m-badge--info m-badge--wide'><i class='fa fa-ellipsis-h'></i> Unit Rate</span>";
      }
      $no_of_bills = $this->Bills->select_bills("b.bill_id", array("b.subcontract_id" => $row->contract_id, "b.bill_type" => 'subcontract'))->num_rows();
      $bill_amount = $this->Bills->select_bills("COALESCE(SUM(bill_payable_amount),0) as total_amount", array("b.subcontract_id" => $row->contract_id, "b.bill_type" => 'subcontract'))->row()->total_amount;
      $bill_paid_amount = $this->Bills->select_bills("COALESCE(SUM(bill_total_paid),0) as total_amount", array("b.subcontract_id" => $row->contract_id, "b.bill_type" => 'subcontract'))->row()->total_amount;
      $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;
      $bill_balance_amount = $this->Bills->select_bills("COALESCE(SUM(bill_balance_amount),0) as total_amount", array("b.subcontract_id" => $row->contract_id, "b.bill_type" => 'subcontract'))->row()->total_amount;
      $bills = $this->Bills->select_bills("b.*,u.user_alias as created_user", array("b.subcontract_id" => $row->contract_id, "b.bill_type" => 'subcontract'))->result();
      $budget_balance = $row->total_budget - ($bill_paid_amount + $advance_paid_amount);
      $work_items = $this->Subcontracts->select_subcontract_work_items("scwi.*,wt.type_name,mu.unit_name", array("sc.contract_id" => $row->contract_id))->result();

      $contractor = $row->contractor_name;

      $profile_data = '<div class="m-portlet m-portlet--tabs">
      <div class="m-portlet__head" style="background-color: white !important;border-bottom: 1px solid #ebedf2 !important;">
      <div class="m-portlet__head-tools">
      <ul class="nav nav-tabs m-tabs-line m-tabs-line--primary m-tabs-line--2x" role="tablist">
      <li class="nav-item m-tabs__item">
      <a class="nav-link m-tabs__link active show quick_sidebar_tab_subcontract_profile_overview quick_sidebar_tabs" data-table-no="" data-toggle="tab" href="#m_tabs_6_1" role="tab" aria-selected="false">
      <i class="fa fa-industry"></i> Overview
      </a>
      </li>
      <li class="nav-item m-tabs__item">
      <a class="nav-link m-tabs__link quick_sidebar_tab_subcontract_profile_bills quick_sidebar_tabs" data-table-no="subcontract_table1" data-toggle="tab" href="#m_tabs_6_2" role="tab" aria-selected="false">
      <i class="fa fa-clipboard-list"></i> Bills
      </a>
      </li>
      <li class="nav-item m-tabs__item">
      <a class="nav-link m-tabs__link quick_sidebar_tab_subcontract_profile_payments quick_sidebar_tabs" data-table-no="subcontract_table2" data-toggle="tab" href="#m_tabs_6_3" role="tab" aria-selected="true">
      <i class="fa fa-wallet"></i> Payments
      </a>
      </li>
      </ul>
      </div>
      </div>
      <div class="m-portlet__body">
      <div class="tab-content">
      <div class="tab-pane active show quick_sidebar_tab_subcontract_profile_overview" id="m_tabs_6_1" role="tabpanel">
      <div style="background: white;border: 4px solid #f7f7fa;padding: 20px;margin: 0px;padding-bottom: 0px">
      <div class="m-section" style="margin: 0px 0 10px 0;">
      <h3 class="m-section__heading" style="padding: 0px;margin: 0px;padding-bottom: 15px">Subcontract Details</h3>
      <div class="row" >
      <div class="col-lg-4" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Subcontract ID
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input type="text" readonly value="#' . $row->contract_id . '"  class="form-control m-input m-input--pill m-input--air" aria-describedby="basic-addon1">
      <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-tag"></i></span></span>
      </div>
      </div>
      </div>
      <div class="col-lg-4">
      <div class="form-group m-form__group" >
      <label for="user_name">
      Subwork Name
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input  readonly value="' . $row->sub_work_name . '"  type="text" name="bill_date" class="form-control m-input m-input--pill m-input--air " >
      <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-tag"></i></span></span>
      </div>
      </div>
      </div>
      <div class="col-lg-4" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Contractor
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input readonly value="' . $contractor . '" type="text" class="form-control m-input m-input--pill m-input--air" aria-describedby="basic-addon1">
      <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-user"></i></span></span>
      </div>
      </div>
      </div>
      </div>
      <div class="row">
      <div class="col-lg-6" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Project
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input readonly value="' . $row->work_name . '" type="text" class="form-control m-input m-input--pill m-input--air" aria-describedby="basic-addon1">
      <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-tag"></i></span></span>
      </div>
      </div>
      </div>
      <div class="col-lg-6">
      <div class="form-group m-form__group">
      <label for="user_name">
      Description
      </label>
      <textarea readonly disabled class="form-control  m-input m-input--pill m-input--air"  aria-describedby="basic-addon1" rows="2">' . $row->description . '</textarea>
      </div>
      </div>
      </div>
      <div class="row" >
      <div class="col-lg-3" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Est. Budget
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input type="text" readonly value="' . $row->total_budget . '"  class="form-control m-input m-input--pill m-input--air" aria-describedby="basic-addon1">
      <span class="m-input-icon__icon m-input-icon__icon--right"><span>' . $this->config->item('Currency_currency_format') . '</span></span>
      </div>
      </div>
      </div>
      <div class="col-lg-3">
      <div class="form-group m-form__group" >
      <label for="user_name">
      No. of Bills Received
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input  readonly value="' . $no_of_bills . '"  type="text" name="bill_date" class="form-control m-input m-input--pill m-input--air " >
      <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-tag"></i></span></span>
      </div>
      </div>
      </div>
      <div class="col-lg-3" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Total Bill Amount
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input readonly value="' . $bill_amount . '" type="text" class="form-control m-input m-input--pill m-input--air" aria-describedby="basic-addon1">
      <span class="m-input-icon__icon m-input-icon__icon--right"><span>' . $this->config->item('Currency_currency_format') . '</span></span>
      </div>
      </div>
      </div>
      <div class="col-lg-3" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Total Paid on Bill
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input readonly value="' . ($bill_paid_amount) . '" type="text" class="form-control m-input m-input--pill m-input--air" aria-describedby="basic-addon1">
      <span class="m-input-icon__icon m-input-icon__icon--right"><span>' . $this->config->item('Currency_currency_format') . '</span></span>
      </div>
      </div>
      </div>
      </div>
      <div class="row" >
      <div class="col-lg-3" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Contract Type
      </label>
      <div class="m-input-icon m-input-icon--right">
      ' . $contract_type . '
      </div>
      </div>
      </div>
      <div class="col-lg-3" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Total Advance Paid
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input readonly value="' . ($advance_paid_amount) . '" type="text" class="form-control m-input m-input--pill m-input--air" aria-describedby="basic-addon1">
      <span class="m-input-icon__icon m-input-icon__icon--right"><span>' . $this->config->item('Currency_currency_format') . '</span></span>
      </div>
      </div>
      </div>
      <div class="col-lg-3" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Balance to Bills
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input type="text" readonly value="' . $bill_balance_amount . '"  class="form-control m-input m-input--pill m-input--air" aria-describedby="basic-addon1">
      <span class="m-input-icon__icon m-input-icon__icon--right"><span>' . $this->config->item('Currency_currency_format') . '</span></span>
      </div>
      </div>
      </div>
      <div class="col-lg-3" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Balance to Budget
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input type="text" readonly value="' . $budget_balance . '"  class="form-control m-input m-input--pill m-input--air" aria-describedby="basic-addon1">
      <span class="m-input-icon__icon m-input-icon__icon--right"><span>' . $this->config->item('Currency_currency_format') . '</span></span>
      </div>
      </div>
      </div>
      </div>
      </div>
      </div>
      <br/>
      <div style="background: white;border: 4px solid #f7f7fa;padding: 20px;margin: 0px;padding-bottom: 0px">
      <div class="m-section" style="margin: 0px 0 10px 0;">
      <h3 class="m-section__heading" style="padding: 0px;margin: 0px;padding-bottom: 15px">Work Items</h3>
      <table class="table table-striped m-table m-table--head-bg-brand">
      <thead>
      <tr>
      <th>Sl No</th>
      <th>Work Type</th>';
      if ($row->contract_type == 'unit_rate') {
        $profile_data .= '<th>Measure Unit</th>
        <th>Unit Rate</th>
        <th>Quantity</th>';
      }
      $profile_data .= '<th>Est Amount</th>
      <th>Remarks</th>
      </tr>
      </thead>
      <tbody>';
      $item_sl_no = 1;
      foreach ($work_items as $key => $value) {
        $profile_data .= '<tr>
        <td>' . $item_sl_no . '</td>
        <td>' . $value->type_name . '</td>';
        if ($row->contract_type == 'unit_rate') {
          $profile_data .= '<td>' . $value->unit_name . '</td>
          <td>' . $value->unit_rate . '</td>
          <td>' . $value->qty . '</td>';
        }
        $profile_data .= '<td>' . $value->est_amount . '</td>
        <td>' . $value->remarks . '</td>
        </tr>';
        $item_sl_no++;
      }
      $profile_data .= '</tbody>
      </table>
      </div>
      </div>
      </div>
      <div class="tab-pane quick_sidebar_tab_subcontract_profile_bills" id="m_tabs_6_2" role="tabpanel">
      <table width="100%" class="table m-table nowrap table-header-fixed table-striped table-bordered table-hover table-header-fixed" id="subcontract_bills_view_table">
      <thead>
      <tr class="">
      <th>Sl No</th>
      <th>Bill ID</th>
      <th>Bill Date</th>
      <th>Project</th>
      <th>Subwork Name</th>
      <th>Work Type</th>
      <th>Contractor</th>
      <th>Bill No</th>
      <th>Consignee</th>
      <th>Gross Amount</th>
      <th>' . $this->config->item('Tax_tax_name') . ' Amt</th>
      <th>TDS</th>
      <th>Payable Amount</th>
      <th>Total Paid</th>
      <th>Balance</th>
      <th>Status</th>
      <th>Description</th>
      <th>Attachment</th>
      <th>No of Labours</th>
      <th>Remarks</th>
      <th>Created By</th>
      <th>Created Date</th>
      <th>Actions</th>
      <th>Bill ID</th>
      <th>Contract ID</th>
      <th>Attachment</th>
      <th>Tax Percent</th>
      </tr>
      </thead>
      <tbody>
      </tbody>
      </table>
      </div>
      <div class="tab-pane quick_sidebar_tab_subcontract_profile_payments" id="m_tabs_6_3" role="tabpanel">
      <table width="100%" class="table m-table nowrap table-header-fixed table-striped table-bordered table-hover table-header-fixed" id="subcontract_payments_view_table">
      <thead>
      <tr class="">
      <th>Sl No</th>
      <th>ID</th>
      <th>Paid Date</th>
      <th>Bill ID</th>
      <th>Project</th>
      <th>Subwork Name</th>
      <th>Work Type</th>
      <th>Contractor</th>
      <th>Bill No</th>
      <th>Consignee</th>
      <th>Paid Amount</th>
      <th>Debit Acc</th>
      <th>Payment Mode</th>
      <th>TR Ref No</th>
      <th>TR Ref Date</th>
      <th>Remarks</th>
      <th>Created By</th>
      <th>Created Date</th>
      <th>Actions</th>
      <th>Debit Acc</th>
      </tr>
      </thead>
      <tbody>
      </tbody>
      </table>
      </div>
      </div>
      </div>
      </div>';
    }

    echo json_encode(array("profile_data" => $profile_data));  // send data as json format
  }

  public function create_deduction()
  {
    // $redirect_url = $this->security->xss_clean($this->input->post('redirect_url'));
    $data['subcontract_id'] = $this->security->xss_clean($this->input->post('contract_id'));
    $data['date'] = date('Y-m-d',strtotime($this->input->post('deduction_date')));
    $data['description'] = $this->security->xss_clean($this->input->post('description'));
    $data['amount'] = $this->security->xss_clean($this->input->post('amount'));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');
    $result = $this->Subcontracts->create_subcontract_deduction($data);

    $flash_data['status'] = $result['status'];
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Subcontract Deduction Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }
  public function update_deduction()
  {
    // $redirect_url = $this->security->xss_clean($this->input->post('redirect_url'));
    $data['id'] = $this->security->xss_clean($this->input->post('deduction_id'));
    $data['date'] = date('Y-m-d',strtotime($this->input->post('deduction_date')));
    $data['description'] = $this->security->xss_clean($this->input->post('description'));
    $data['amount'] = $this->security->xss_clean($this->input->post('amount'));
    $result = $this->Subcontracts->update_subcontract_deductions($data);

    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Subcontract Deduction 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_deduction()
  {
    // $redirect_url = $this->security->xss_clean($this->input->post('redirect_url'));
    $data['id'] = $this->security->xss_clean($this->input->post('deduction_id'));
    $data['delete_status'] = 1;
    $result = $this->Subcontracts->update_subcontract_deductions($data);

    $flash_data['status'] = $result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Subcontract Deduction Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }
  public function select_subcontract_deductions()
  {

    $json_data = array();
    $j = 0;
    $sl_no = 0;
    $total_labour_wage = $total_no_of_days = 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.date,'%Y-%m-%d') <="] = $end_date;
      $data["STR_TO_DATE(sd.date,'%Y-%m-%d') >="] = $start_date;
    }
    if (isset($_POST['contract_id']) && $_POST['contract_id'] != '' && $_POST['contract_id'] != 'all') {
      $data['sd.subcontract_id'] = $_POST['contract_id'];
    }
    // if (isset($_POST['contractor']) && $_POST['contractor'] != '' && $_POST['contractor'] != 'all') {
    //   $data['c.contractor_id'] = $_POST['contractor'];
    // }
    // if (isset($_POST['work']) && $_POST['work'] != '' && $_POST['work'] != 'all') {
    //   $data['sc.work_id'] = $_POST['work'];
    // }
    // if ($this->session->userdata('user_role') == 'supervisor') {
    //   //          Select Assigned Works Only
    //   $supervisor_id = $this->session->userdata('user_id');
    //   $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    // }
    // if (isset($_POST['user_id']) && $_POST['user_id'] != '' && $_POST['user_id'] != 'all') {
    //   $data['sc.created_by'] = $_POST['user_id'];
    // }
    // if ($this->session->userdata('user_role') != 'qs_manager' && $this->session->userdata('user_role') != 'qs' && $this->session->userdata('user_role') != 'general_manager' &&  $this->session->userdata('user_role') != 'auditor' && $this->config->item('user_data_access_view_all') != 1) {
    //   $data['sc.created_by'] = $this->session->userdata('user_id');
    // }
    $result  = $this->Subcontracts->select_subcontract_deductions("sd.*", $data);
    $result_array = $result->result();

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

    foreach ($result_array as $row) :
      $sl_no++;

      $btn_edit = $btn_delete = '';
      if ($this->session->userdata('user_role') == 'admin' || $this->session->userdata('user_role') == 'general_manager' || $this->session->userdata('user_role') == 'qs_manager' || $this->session->userdata('user_id')==$row->created_by) {
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px"  id="subcontract_deduction_edit_btn" href="#subcontract_deductions_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="subcontract_deduction_delete_btn" href="#subcontract_deductions_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-trash"></i>
        </a>';
      }

      $array[$j][] = $row->id;
      $array[$j][] = $sl_no;
      $array[$j][] = date('d-m-Y', strtotime($row->date));
      $array[$j][] = $row->amount;
      $array[$j][] = $row->description;
      $array[$j][] = $btn_edit.$btn_delete;

      $total_amount+=$row->amount;
      $j++;
    endforeach;
    if ($result->num_rows() > 0) {
      $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_amount,$this->config->item('Currency_currency_shortname'))."</strong>";
      $array[$j][] = '';
      $array[$j][] = '';
    }
    $json_data['data'] = $array;
    echo json_encode($json_data);  // send data as json format
  }

  // labours
  public function select_labour(){

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

    $data=array();
    $data['sl.delete_status'] = 0;
    if(isset($_POST['contractor']) && $_POST['contractor']!='' && $_POST['contractor']!='all'){
      $data['sl.contractor_id'] = $_POST['contractor'];
    }
    if($this->session->userdata('user_role') != 'auditor' && $this->config->item('user_data_access_view_all')!=1){
      $data['sl.created_by'] = $this->session->userdata('user_id');
    }

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

    $result = $this->Subcontracts->select_labours("sl.*,sc.*,sc.phone as contractor_phone,wt.type_name as type_name,u.user_alias,sc.branch_id",$data,'','',"","","");
    $result_array=$result->result();
    $array=array();

    foreach($result_array as $row):

      $btn_edit='';
      if($this->session->userdata('user_role')!='auditor'){
        $btn_edit='<a style="margin-left: 5px;margin-right: 5px" id="labour_edit_btn" href="#labour_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='';
      if($this->session->userdata('user_role')=='admin' || ($this->session->userdata('user_role')!='admin' && $this->session->userdata('user_id')==$row->created_by)) {
        $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="labour_delete_btn" href="#labour_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->photo!=''){
        $image = base_url()."uploads/labours/".$row->photo;
      }else{
        $image = base_url()."uploads/labours/default.png";
      }

      if($row->skill_type=='skilled'){
        $skill_type = "<span class='m-badge m-badge--success m-badge--wide'>Skilled</span>";
      }else{
        $skill_type = "<span class='m-badge m-badge--warning m-badge--wide'>Unskilled</span>";
      }


      $labour_name = '<div class="d-flex align-items-center">
      <div class="symbol symbol-60 symbol-xxl-100 mr-3 align-self-start align-self-xxl-center">
      <div class="symbol-label" style="background-image:url('.$image.')"></div>
      <i class="symbol-badge bg-success"></i>
      </div>
      <div>
      <span class="font-weight-bolder font-size-h5 text-dark-75 text-hover-primary">' . $row->labour_name . '</span><br>
      '.$skill_type.'
      </div>
      </div>';

      if($row->fixed_wage==1){
        $fixed_wage = "Yes";
      }else{
        $fixed_wage = "No";
      }

      $contact = $row->labour_contact;
      if($row->labour_contact_2!=''){
        $contact.=',<br/>'.$row->labour_contact_2;
      }

      $projects = '';
      $contractor_name = '
      <div>
      <span class="font-weight-bolder font-size-h5 text-dark-75 text-hover-primary"><a href="'.base_url().'Subcontracts/contractors/profile/'.$row->contractor_id.'"> ' . $row->contractor_name . '</a></span><br>
      '.$row->contractor_phone.'
      </div>
      </div>';

      $array[$j][]=$row->labour_id;
      $array[$j][]=($row->branch_id==0)?'No Branch':$this->Branches->select_branches('*',array('branch_id'=>$row->branch_id))->row()->branch_name;
      $array[$j][]=$contractor_name;
      $array[$j][]=$labour_name;
      $array[$j][]=$contact;
      $array[$j][]=$row->type_name;
      $array[$j][]=$fixed_wage;
      $array[$j][]=number_format($row->daily_wage,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=number_format($row->opening_balance,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][]=$row->aadhar_no;
      $array[$j][]=nl2br($row->address);
      $array[$j][]=$row->user_alias;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][]=date('d-m-Y',strtotime($row->created_date));
      }else{
        $array[$j][]='';
      }
      $array[$j][]=$btn_edit.$btn_delete;
      $array[$j][]=$row->work_type;
      $array[$j][]=$row->fixed_wage;
      $array[$j][]=$row->labour_name;
      $array[$j][]='$projects';
      $array[$j][]=$row->photo;
      $array[$j][]=$row->contractor_id;
      $array[$j][]=$row->skill_type;

      $j++;
    endforeach;

    $json_data['data']=$array;
    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    echo json_encode($json_data);  // send data as json format
  }
  public function select_subcontract_labours(){
    $data = array();
    if(isset($_POST['labour_id']) && $_POST['labour_id']!=""){
      $data['labour_id'] = $_POST['labour_id'];
    }
    if(isset($_POST['work_type']) && $_POST['work_type']!="" && $_POST['work_type']!="all"){
      $data['work_type'] = $_POST['work_type'];
    }
    if(isset($_POST['contract_id']) && $_POST['contract_id']!=""){
      $subcontract_where['contract_id'] = $_POST['contract_id'];
      $subcontract_data = $this->Subcontracts->select_subcontract("sc.*,u.user_alias,wc.work_name,c.*", $subcontract_where);
      if($subcontract_data->num_rows()==1){
        $data['sl.contractor_id'] = $subcontract_data->row()->contractor;
      }
    }
    $result	= $this->Subcontracts->select_labours("sl.*,sc.*,sc.phone as contractor_phone,wt.type_name as type_name,u.user_alias",$data,'','',"","","");
    if($result->num_rows()>0) {
      echo json_encode(array("count" => $result->num_rows(),"data"=>$result->result()));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }
  public function create_labour()
  {
    $data2['labour_name'] = $this->security->xss_clean($this->input->post('name'));
    $data2['labour_type'] = $this->security->xss_clean($this->input->post('labour_type'));

    $count = $this->Subcontracts->select_labours("",$data2)->num_rows();

    $data2['contractor_id'] = $this->security->xss_clean($this->input->post('contractor'));
    $data2['skill_type'] = $this->security->xss_clean($this->input->post('skill_type'));
    $data2['labour_contact'] = $this->security->xss_clean($this->input->post('contact_no'));
    $data2['fixed_wage'] = $this->security->xss_clean($this->input->post('fixed_wage'));
    $data2['work_type'] = $this->security->xss_clean($this->input->post('work_type'));
    $data2['daily_wage'] = $this->security->xss_clean($this->input->post('daily_wage'));
    $data2['opening_balance'] = $this->security->xss_clean($this->input->post('op_balance'));
    $data2['address'] = $this->security->xss_clean($this->input->post('address'));
    $data2['aadhar_no'] = $this->security->xss_clean($this->input->post('aadhar_no'));
    $data2['labour_contact_2'] = $this->security->xss_clean($this->input->post('contact_no_2'));
    $data2['created_date'] = date('Y-m-d H:i:s');
    $data2['created_by'] = $this->session->userdata('user_id');
    $file_error = 0;
    if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']["size"] > 0) {
      //      File Upload
      $config['upload_path']   = 'uploads/labours/';
      $config['allowed_types'] = 'jpg|jpeg|png';
      $config['max_size']      = 3000;
      $config['encrypt_name']    = TRUE;
      $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();
        $data2['photo'] = $file_data['file_name'];
        $this->resizeImage("labours",$file_data['file_name']);
      }
    }
    if($file_error==0){
      if($count==0) {
        $result2 = $this->Subcontracts->create_labour($data2);
        $flash_data['status'] = $result2['status'];
        if ($result2['status'] == 1) {
          $flash_data['flashdata_msg'] = 'Labour Added Successfully!.';
          $flash_data['message'] = 'Labour Added Successfully!.';
          $flash_data['flashdata_type'] = 'success';
          $flash_data['alert_type'] = 'success';
          $flash_data['flashdata_title'] = 'Success !';

        } else {
          $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
          $flash_data['message'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
          $flash_data['flashdata_type'] = 'error';
          $flash_data['alert_type'] = 'danger';
          $flash_data['flashdata_title'] = 'Error !!';
        }
      }else{
        $flash_data['status'] = 0;
        $flash_data['flashdata_msg'] = 'Sorry.. Labour with Same Name Already Exist!';
        $flash_data['message'] = 'Sorry.. Labour with Same Name Already Exist!';
        $flash_data['flashdata_type'] = 'warning';
        $flash_data['alert_type'] = 'warning';
        $flash_data['flashdata_title'] = 'Duplication !!';
      }
    }

    echo(json_encode($flash_data));
  }
  public function update_labour()
  {
    $data2['labour_id'] = $this->security->xss_clean($this->input->post('labour_id'));
    $data2['labour_name'] = $this->security->xss_clean($this->input->post('name'));

    $data2['contractor_id'] = $this->security->xss_clean($this->input->post('contractor'));
    $data2['skill_type'] = $this->security->xss_clean($this->input->post('skill_type_edit'));

    // $data2['labour_type'] = $this->security->xss_clean($this->input->post('labour_type_edit'));
    $data2['fixed_wage'] = $this->security->xss_clean($this->input->post('fixed_wage_edit'));
    $data2['labour_contact'] = $this->security->xss_clean($this->input->post('contact_no'));
    $data2['work_type'] = $this->security->xss_clean($this->input->post('work_type'));
    $data2['daily_wage'] = $this->security->xss_clean($this->input->post('daily_wage'));
    if($data2['fixed_wage']==0){
      $data2['daily_wage'] = 0;
    }
    $data2['opening_balance'] = $this->security->xss_clean($this->input->post('op_balance'));
    $data2['address'] = $this->security->xss_clean($this->input->post('address'));
    $data2['aadhar_no'] = $this->security->xss_clean($this->input->post('aadhar_no'));
    $data2['labour_contact_2'] = $this->security->xss_clean($this->input->post('contact_no_2'));
    $data2['updated_date'] = date('Y-m-d H:i:s');
    $data2['updated_by'] = $this->session->userdata('user_id');
    $file_error = 0;
    if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']["size"] > 0) {
      //      File Upload
      $config['upload_path']   = 'uploads/labours/';
      $config['allowed_types'] = 'jpg|jpeg|png';
      $config['max_size']      = 3000;
      $config['encrypt_name']    = TRUE;
      $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();
        $data2['photo'] = $file_data['file_name'];
        $this->resizeImage("labours",$file_data['file_name']);
      }
    }
    if($file_error==0){
      $count = $this->Subcontracts->select_labours("",array("labour_id !="=>$data2['labour_id'],"labour_name"=>$data2['labour_name']))->num_rows();
      if($count==0) {
        $result2 = $this->Subcontracts->update_labour($data2);
        $flash_data['status'] = $result2;
        if ($result2 == 1) {
          $flash_data['flashdata_msg'] = 'Labour Details Updated Successfully!.';
          $flash_data['flashdata_type'] = 'success';
          $flash_data['alert_type'] = 'success';
          $flash_data['flashdata_title'] = 'Success !';

        } else {
          $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
          $flash_data['flashdata_type'] = 'error';
          $flash_data['alert_type'] = 'danger';
          $flash_data['flashdata_title'] = 'Error !!';
        }
      }else{
        $flash_data['status'] = 0;
        $flash_data['flashdata_msg'] = 'Sorry.. Labour with Same Name Already Exist!';
        $flash_data['flashdata_type'] = 'warning';
        $flash_data['alert_type'] = 'warning';
        $flash_data['flashdata_title'] = 'Duplication !!';
      }
    }
    echo(json_encode($flash_data));
  }
  public function delete_labour()
  {
    $data2['labour_id'] = $this->security->xss_clean($this->input->post('labour_id'));
    $data2['delete_status'] = 1;
    $result2 = $this->Subcontracts->update_labour($data2);
    $flash_data['status'] = $result2;
    if ($result2 == 1) {
      $flash_data['flashdata_msg'] = 'Labour Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';

    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }

    echo(json_encode($flash_data));
  }

  public function select_labour_attendance(){

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

    $data=array();
    $data['sl.delete_status'] = 0;
    if(isset($_POST['contractor']) && $_POST['contractor']!='' && $_POST['contractor']!='all'){
      $data['sl.contractor_id'] = $_POST['contractor'];
    }
    if(isset($_POST['subcontract']) && $_POST['subcontract']!='' && $_POST['subcontract']!='all'){
      $data['sla.subcontract_id'] = $_POST['subcontract'];
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!=''){
      $data["sla.date >="]= date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!=''){
      $data["sla.date <="]= date('Y-m-d', strtotime($_POST['end_date']));
    }
    if($this->session->userdata('user_role') != 'auditor' && $this->config->item('user_data_access_view_all')!=1){
      $data['sla.created_by'] = $this->session->userdata('user_id');
    }
    if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
      $data['scr.branch_id'] = $_POST['branch_id'];
    }
    $result = $this->Subcontracts->select_subcontract_labour_attendance("sla.*,scr.contractor_name,u.user_alias,sl.skill_type,sl.labour_name,wt.type_name,sc.sub_work_name,sc.contract_id,wc.work_id,wc.work_name,scr.branch_id",$data);
    $result_array=$result->result();
    $array=array();
    $total_wage = 0;
    foreach($result_array as $row):

      $btn_delete='';
      if($this->session->userdata('user_role')=='admin' || ($this->session->userdata('user_role')!='admin' && $this->session->userdata('user_id')==$row->created_by)) {
        $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="btn_delete_attendance" href="#labour_attendance_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->skill_type=='skilled'){
        $skill_type = "<span class='m-badge m-badge--success m-badge--wide'>Skilled</span>";
      }else{
        $skill_type = "<span class='m-badge m-badge--warning m-badge--wide'>Unskilled</span>";
      }


      $array[$j][]=$row->attendance_id;
      $array[$j][]=($row->branch_id==0)?'No Branch':$this->Branches->select_branches('*',array('branch_id'=>$row->branch_id))->row()->branch_name;
      $array[$j][]=date('d-m-Y',strtotime($row->date));
      $array[$j][]=$row->labour_name."<br/>".$skill_type;
      $array[$j][]=$row->total_wage;
      $array[$j][]=$row->type_name;
      $array[$j][]=$row->contractor_name;
      $array[$j][] = '<a href="'.base_url().'subcontracts/profile/'.$row->contract_id.'">#' . $row->contract_id . ' ' . $row->sub_work_name . '</a>';
      $array[$j][] = '<a href="' . base_url() . 'work/profile/' . $row->work_id . '">' . $row->work_name . '</a>';
      $array[$j][]=$row->user_alias;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][]=date('d-m-Y',strtotime($row->created_date));
      }else{
        $array[$j][]='';
      }
      $array[$j][]=$btn_delete;

      $total_wage+=$row->total_wage;

      $j++;
    endforeach;

    if(sizeof($array)>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]="<strong>".$total_wage."</strong>";
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
    }

    $json_data['data']=$array;
    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    echo json_encode($json_data);  // send data as json format
  }
  public function select_labour_attendance_summary(){

    $json_data=array();
    $j=0;
    $date_period = '';
    $data_labour=$data_attendance=array();
    $data['sl.delete_status'] = 0;
    if(isset($_POST['contractor']) && $_POST['contractor']!='' && $_POST['contractor']!='all'){
      $data_labour['sl.contractor_id'] = $_POST['contractor'];
    }
    if(isset($_POST['subcontract']) && $_POST['subcontract']!='' && $_POST['subcontract']!='all'){
      $data_attendance['sla.subcontract_id'] = $_POST['subcontract'];
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!=''){
      $data_attendance["sla.date >="]= date('Y-m-d', strtotime($_POST['start_date']));
      $date_period .= $_POST['start_date'];
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!=''){
      $data_attendance["sla.date <="]= date('Y-m-d', strtotime($_POST['end_date']));
      $date_period .= " To ".$_POST['end_date'];
    }
    if($this->session->userdata('user_role') != 'auditor' && $this->config->item('user_data_access_view_all')!=1){
      $data_attendance['sla.created_by'] = $this->session->userdata('user_id');
    }
    if(isset($_POST['branch_id']) && $_POST['branch_id']!='' && $_POST['branch_id']!='all'){
      $data_labour['scr.branch_id'] = $_POST['branch_id'];
    }
    $result = $this->Subcontracts->select_labours("",$data_labour);
    $result_array=$result->result();
    $array=array();
    $total_wage = $slno = 0;
    foreach($result_array as $row):
      $slno++;
      $data_attendance['sla.labour_id'] = $row->labour_id;
      $wage = $this->Subcontracts->select_subcontract_labour_attendance("COALESCE(SUM(sla.total_wage),0) as total,wc.work_name,wc.work_id,sc.contract_id,sc.sub_work_name",$data_attendance)->row();

      if($row->skill_type=='skilled'){
        $skill_type = "<span class='m-badge m-badge--success m-badge--wide'>Skilled</span>";
      }else{
        $skill_type = "<span class='m-badge m-badge--warning m-badge--wide'>Unskilled</span>";
      }


      $array[$j][]=$slno;
      $array[$j][]=($row->branch_id==0)?'No Branch':$this->Branches->select_branches('*',array('branch_id'=>$row->branch_id))->row()->branch_name;
      if($date_period!=''){
        $array[$j][]=$date_period;
      }else{
        $array[$j][]='All';
      }
      $array[$j][]=$row->labour_name."<br/>".$skill_type;
      $array[$j][]=$row->type_name;
      $array[$j][]=$row->contractor_name;
      if(isset($_POST['subcontract']) && $_POST['subcontract']!='' && $_POST['subcontract']!='all'){
        $array[$j][] = '<a href="'.base_url().'subcontracts/profile/'.$wage->contract_id.'">#' . $wage->contract_id . ' ' . $wage->sub_work_name . '</a>';
        $array[$j][] = '<a href="' . base_url() . 'work/profile/' . $wage->work_id . '">' . $wage->work_name . '</a>';
      }else{
        $array[$j][]='All';
        $array[$j][]='All';
      }
      $array[$j][]=$wage->total;

      $total_wage+=$wage->total;

      $j++;
    endforeach;

    if(sizeof($array)>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>".$total_wage."</strong>";
    }

    $json_data['data']=$array;
    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    echo json_encode($json_data);  // send data as json format
  }
  public function create_labour_attendance()
  {

    $data2['date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('work_date'))));
    $data2['remarks'] = $this->security->xss_clean($this->input->post('remarks'));

    $data2['subcontract_id'] = $this->security->xss_clean($this->input->post('subcontract'));
    $data2['created_date'] = date('Y-m-d H:i:s');
    $data2['created_by'] = $this->session->userdata('user_id');

    $wage_duplication=$wage_success=$transaction_success=0;
    //      Add Team Members
    $wage_slip_array=$newArraywageslip=array();
    if($this->input->post('wage_slip')){
      $wage_slip_array = $this->input->post('wage_slip');
    }
    $wage_slip_array_length = sizeof($wage_slip_array);
    //      Convert to New Formatted Array
    foreach (array_keys($wage_slip_array) as $fieldKey) {
      foreach ($wage_slip_array[$fieldKey] as $key=>$value) {
        $newArraywageslip[$key][$fieldKey] = $value;
      }
    }
    foreach ($newArraywageslip as $row) {
      $data3 = array();
      $status = 0;
      $data3['sla.date'] = $data2['date'];
      $data2['labour_id'] = $data3['sla.labour_id'] = $row['labour_id'];
      $data2['total_wage'] = $row['total_wage'];
      if(isset($row['work_status']) && $row['work_status']=='on'){
        $data2['subcontract_id'] = $data3['sla.subcontract_id'] = $data2['subcontract_id'];
        if($this->config->item('Labour_wage_slip_allow_multiple_day_by_site')==1){
          $count=0;
        }else{
          $count = $this->Subcontracts->select_subcontract_labour_attendance("",$data3)->num_rows();
        }

        if($count==0) {
          $result2 = $this->Subcontracts->create_subcontract_labour_attendance($data2);
          $status = $result2['status'];
          if ($result2['status'] == 1) {
            $wage_success++;
          }
        }else{
          $wage_duplication++;
        }
      }else{
        $status = 1;
      }
    }

    if ($wage_success>0) {
      $flash_data['flashdata_msg'] = $wage_success.' Labour Attendance Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
      if($wage_duplication>0){
        $flash_data['flashdata_msg'] .= $wage_duplication.' Labour Attendance Not Added Because of Attendance on Same Date & Subcontract Already Exist!';
        $flash_data['flashdata_type'] = 'warning';
        $flash_data['alert_type'] = 'warning';
        $flash_data['flashdata_title'] = 'Success, Duplications Found!';
      }
    }else{
      if($wage_duplication>0){
        $flash_data['flashdata_msg'] = $wage_duplication.' Labour Attendance Not Added Because of Attendance on Same Date & Work Already Exist!';
        $flash_data['flashdata_type'] = 'warning';
        $flash_data['alert_type'] = 'warning';
        $flash_data['flashdata_title'] = 'Success, Duplications Found!';
      }else{
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['message'] = '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'];

    $this->session->set_flashdata($flash_data);
    redirect(base_url(). 'subcontracts/labour_attendance','refresh');
  }
  public function delete_labour_attendance()
  {
    $data_where['attendance_id'] = $this->security->xss_clean($this->input->post('attendance_id'));
    $data['delete_status'] = 1;
    $result2 = $this->Subcontracts->update_subcontract_labour_attendance($data,$data_where);
    $flash_data['status'] = $result2;
    if ($result2 == 1) {
      $flash_data['flashdata_msg'] = 'Labour Attendance Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';

    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }

    echo(json_encode($flash_data));
  }

  public function resizeImage($directory,$filename)
  {
    $source_path = FCPATH.'/uploads/'.$directory."/". $filename;
    $target_path = FCPATH.'/uploads/'.$directory."/";
    $config_manip = array(
      'image_library' => 'gd2',
      'source_image' => $source_path,
      'new_image' => $target_path,
      'maintain_ratio' => TRUE,
      // 'quality' => '60%',
      'width' => 150,
      'height' => 200,
    );

    $this->load->library('image_lib', $config_manip);
    if (!$this->image_lib->resize()) {
      echo $this->image_lib->display_errors();
    }
    $this->image_lib->clear();
  }

  public function create_contractor()
  {
    $data['phone']=$contractor_where['phone']=$this->security->xss_clean($this->input->post('mobile_number'));
    $count = $this->Subcontracts->select_contractors("",$contractor_where)->num_rows();
    if($count == 0) {
      $data['contractor_name'] = $this->security->xss_clean($this->input->post('contractor_name'));
      $data['contractor_address'] = $this->security->xss_clean($this->input->post('address'));
      $data['bank_account_no'] = $this->security->xss_clean($this->input->post('bank_account_no'));
      $data['bank_ifsc'] = $this->security->xss_clean($this->input->post('bank_ifsc'));
      $data['bank_branch'] = $this->security->xss_clean($this->input->post('bank_branch'));
      $data['bank_name'] = $this->security->xss_clean($this->input->post('bank_name'));
      $data['pan_no'] = $this->security->xss_clean($this->input->post('pan_no'));
      $data['tax_no'] = $this->security->xss_clean($this->input->post('tax_no'));
      $data['aadhar_no'] = $this->security->xss_clean($this->input->post('aadhar_no'));
      $data['contact_person'] = $this->security->xss_clean($this->input->post('contact_person'));
      $result = $this->Subcontracts->create_contractor($data);

      $flash_data['status'] = $result['status'];
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Contractor Added Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      }else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else {
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. A Contractor with Same mobile number Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Duplication !!';
    }
    echo(json_encode($flash_data));
  }
  public function update_contractor()
  {
    $data['phone'] = $contractor_where['phone'] = $this->security->xss_clean($this->input->post('mobile_number'));
    $data['contractor_id'] = $contractor_where['contractor_id !='] = $this->security->xss_clean($this->input->post('contractor_id'));
    $count = $this->Subcontracts->select_contractors("",$contractor_where)->num_rows();
    if($count == 0) {
      $data['contractor_name'] = $this->security->xss_clean($this->input->post('contractor_name'));
      $data['contractor_address'] = $this->security->xss_clean($this->input->post('address'));
      $data['bank_account_no'] = $this->security->xss_clean($this->input->post('bank_account_no'));
      $data['bank_ifsc'] = $this->security->xss_clean($this->input->post('bank_ifsc'));
      $data['bank_branch'] = $this->security->xss_clean($this->input->post('bank_branch'));
      $data['bank_name'] = $this->security->xss_clean($this->input->post('bank_name'));
      $data['pan_no'] = $this->security->xss_clean($this->input->post('pan_no'));
      $data['tax_no'] = $this->security->xss_clean($this->input->post('tax_no'));
      $data['aadhar_no'] = $this->security->xss_clean($this->input->post('aadhar_no'));
      $data['contact_person'] = $this->security->xss_clean($this->input->post('contact_person'));
      $result = $this->Subcontracts->update_contractor($data);

      $flash_data['status'] = $result;
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Contractor Updated Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      }else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else {
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. A contractor with Same mobile number Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Customer Duplication !!';
    }
    echo(json_encode($flash_data));
  }
  public function select_contractors()
  {
    $json_data=array();
    $j=0;
    $sl_no=0;
    $data=array();

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

    $result = $this->Subcontracts->select_contractors("",$data);
    $result_array=$result->result();

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

    foreach($result_array as $row):

      $btn_edit = $btn_delete = '';

      if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager' || $this->session->userdata('user_role')=='accounts_manager'){

        $btn_edit='<a style="margin-left: 5px;margin-right: 5px" id="contractor_edit_btn" href="#contractor_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="contractor_delete_btn" href="#contractor_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
        <i class="la la-trash"></i>
        </a>';

      }

      $sl_no++;


      $array[$j][] = $row->contractor_id;
      $array[$j][] = $sl_no;
      $array[$j][] = ($row->branch_id==0)?'No Branch':$this->Branches->select_branches('*',array('branch_id'=>$row->branch_id))->row()->branch_name;
      $array[$j][] = '<a href="'.base_url().'Subcontracts/contractors/profile/'.$row->contractor_id.'">'.$row->contractor_name.'</a>';
      $array[$j][] = $row->phone;
      $array[$j][] = $row->contact_person;
      $array[$j][] = $row->tax_no;
      $array[$j][] = $row->pan_no;
      $array[$j][] = $row->aadhar_no;
      $array[$j][] = $row->bank_account_no;
      $array[$j][] = $row->bank_ifsc;
      $array[$j][] = $row->bank_name;
      $array[$j][] = $row->bank_branch;
      $array[$j][] = $row->contractor_address;
      $array[$j][] = $btn_edit.$btn_delete;
      $j++;
    endforeach;

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function delete_contractor()
  {
    $data['contractor_id']=$this->security->xss_clean($this->input->post('contractor_id'));
    $data['delete_status']=1;
    $result = $this->Subcontracts->update_contractor($data);
    $flash_data['status'] = $result;
    if ($result == 1 ) {
      $flash_data['flashdata_msg'] = 'Contractor Deleted Successfully!';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !!';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo(json_encode($flash_data));
  }
  public function select_contractors_list(){
    $data['delete_status'] = 0;
    if(isset($_POST['id']) && $_POST['id']!=""){
      $data['contractor_id'] = $_POST['id'];
    }
    $result = $this->Subcontracts->select_contractors("",$data);
    if($result->num_rows()>0) {
      foreach ($result->result() as $row):
        $id[] = $row->contractor_id;
        $name[] = $row->contractor_name;
        $phone[]  = $row->phone;
      endforeach;
      echo json_encode(array("count" => $result->num_rows(),"id" => $id,"name" => $name,"phone" => $phone));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }

  public function create_material_issue()
  {
    $bill_data['from_location_id'] = $this->security->xss_clean($this->input->post('location_form'));
    $bill_data['subcontract_id'] = $this->security->xss_clean($this->input->post('subcontract'));
    $bill_data['vehicle_no'] = $this->security->xss_clean($this->input->post('vehicle_no'));
    $bill_data['vehicle_driver_phone'] = $this->security->xss_clean($this->input->post('driver_phone'));
    $bill_data['supervisor'] = $this->security->xss_clean($this->input->post('supervisor'));
    $bill_data['bill_remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $bill_data['bill_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('issue_date'))));
    $bill_data['created_date'] = date('Y-m-d H:i:s');
    $bill_data['created_by'] = $this->session->userdata('user_id');
    $bill_result = $this->Subcontracts->create_material_issue_bill($bill_data);

    $data['bill_id'] = $bill_result['insert_id'];
    // Cart Items
    $items_array = $newArrayItems = array();
    if ($this->input->post('item')) {
      $items_array = $this->input->post('item');
    }
    $items_array_length = sizeof($items_array);
    //      Convert to New Formatted Array
    foreach (array_keys($items_array) as $fieldKey) {
      foreach ($items_array[$fieldKey] as $key => $value) {
        $newArrayItems[$key][$fieldKey] = $value;
      }
    }
    foreach ($newArrayItems as $row) {
      $stock_ids = $row['stock_id'];

      $this->db->where('sr.stock_id IN (' . $stock_ids . ')');
      $stock_details = $this->Stock->select_stock_register("sr.purchase_supplier_id,sr.unit_price,sr.material_id,sr.unit", "")->row();
      if($this->config->item('Stock_stock_register_material_based_only')!=1){
        $data2['purchase_supplier_id'] = $stock_details->purchase_supplier_id;
        $data2['unit_price'] = $stock_details->unit_price;
      }
      $data2['material_id'] = $stock_details->material_id;
      $data2['unit_id']  = $stock_details->unit;
      $total_stock_issued_qty = $row['quantity'];
      // Get Stock ID From Stock Register for this Material
      $this->db->where('sr.stock_id IN (' . $stock_ids . ')');
      if($this->config->item('Stock_stock_register_material_based_only')!=1){
        $stock_register = $this->Stock->select_stock_register("sr.*", array("sr.location_id" => $bill_data['from_location_id'], "sr.material_id" => $data2['material_id'], "sr.unit" => $data2['unit_id'], "sr.purchase_supplier_id" => $data2['purchase_supplier_id'], "sr.unit_price like" => $data2['unit_price'], "sr.total_balance_qty >" => 0));
      }else{
        $stock_register = $this->Stock->select_stock_register("sr.*", array("sr.location_id" => $bill_data['from_location_id'], "sr.material_id" => $data2['material_id'], "sr.unit" => $data2['unit_id'], "sr.total_balance_qty >" => 0));
      }
      $remaining_qty = $total_stock_issued_qty;
      foreach ($stock_register->result() as $key => $value) {
        if ($remaining_qty > 0) {
          $available_stock_item_qty = $value->total_balance_qty;
          if ($remaining_qty > $available_stock_item_qty) {
            $data['quantity']  = $available_stock_item_qty;
          } else {
            $data['quantity']  = $remaining_qty;
          }
          $remaining_qty = $remaining_qty - $data['quantity'];
          $data['stock_id'] = $value->stock_id;
          $data['make_spec'] = $row['description'];
          $data['item_remarks'] = $row['remarks'];

          // Update Stock Consumption
          $result = $this->Subcontracts->create_material_issue_items($data);
          //  Update Stock Register
          $this->stock_management->calculate_stock_balance($data['stock_id']);
        }
      }
    }
    if (isset($result) && $result['status'] == 1 && isset($bill_result) && $bill_result['status'] == 1) {
      $flash_data['status'] = $result['status'];
      $flash_data['bill_id'] = $bill_result['insert_id'];
      $flash_data['flashdata_msg'] = 'Material Issue Saved Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }
  public function update_material_issue()
  {
    $bill_where_data['bill_id'] = $this->security->xss_clean($this->input->post('bill_id'));
    $bill_details = $this->Subcontracts->select_material_issue_bill("smb.*",$bill_where_data)->row();
    $bill_items = $this->Subcontracts->select_material_issue_items("smi.*", array("smi.bill_id"=>$bill_where_data['bill_id']))->result();
    $bill_data['subcontract_id'] = $this->security->xss_clean($this->input->post('subcontract'));
    $bill_data['vehicle_no'] = $this->security->xss_clean($this->input->post('vehicle_no'));
    $bill_data['vehicle_driver_phone'] = $this->security->xss_clean($this->input->post('driver_phone'));
    $bill_data['supervisor'] = $this->security->xss_clean($this->input->post('supervisor'));
    $bill_data['bill_remarks'] = $this->security->xss_clean($this->input->post('remarks'));
    $bill_data['bill_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('issue_date'))));
    $bill_data['updated_date'] = date('Y-m-d H:i:s');
    $bill_data['updated_by'] = $this->session->userdata('user_id');
    $bill_result = $this->Subcontracts->update_material_issue_bill($bill_where_data,$bill_data);

    // Cart Items
    $items_array = $newArrayItems = array();
    if ($this->input->post('item')) {
      $items_array = $this->input->post('item');
    }
    $items_array_length = sizeof($items_array);
    //      Convert to New Formatted Array
    foreach (array_keys($items_array) as $fieldKey) {
      foreach ($items_array[$fieldKey] as $key => $value) {
        $newArrayItems[$key][$fieldKey] = $value;
      }
    }
    $existing_item_ids = array();
    foreach ($newArrayItems as $row) {
      if(isset($row['item_type']) && $row['item_type']=='exist'){
        // Update Stock Consumption
        $existing_item_ids[] = $row['item_id'];
        $item_where['item_id'] = $row['item_id'];
        $item_data['quantity'] = $row['quantity'];
        $item_data['make_spec'] = $row['description'];
        $item_data['item_remarks'] = $row['remarks'];
        $result = $this->Subcontracts->update_material_issue_items($item_where,$item_data);
        //  Update Stock Register
        $this->stock_management->calculate_stock_balance($row['stock_id']);
      }else{
        $stock_ids = $row['stock_id'];

        $this->db->where('sr.stock_id IN (' . $stock_ids . ')');
        $stock_details = $this->Stock->select_stock_register("sr.purchase_supplier_id,sr.unit_price,sr.material_id,sr.unit", "")->row();
        if($this->config->item('Stock_stock_register_material_based_only')!=1){
          $data2['purchase_supplier_id'] = $stock_details->purchase_supplier_id;
          $data2['unit_price'] = $stock_details->unit_price;
        }
        $data2['material_id'] = $stock_details->material_id;
        $data2['unit_id']  = $stock_details->unit;
        $total_stock_issued_qty = $row['quantity'];
        // Get Stock ID From Stock Register for this Material
        $this->db->where('sr.stock_id IN (' . $stock_ids . ')');
        if($this->config->item('Stock_stock_register_material_based_only')!=1){
          $stock_register = $this->Stock->select_stock_register("sr.*", array("sr.location_id" => $bill_details->from_location_id, "sr.material_id" => $data2['material_id'], "sr.unit" => $data2['unit_id'], "sr.purchase_supplier_id" => $data2['purchase_supplier_id'], "sr.unit_price like" => $data2['unit_price'], "sr.total_balance_qty >" => 0));
        }else{
          $stock_register = $this->Stock->select_stock_register("sr.*", array("sr.location_id" => $bill_details->from_location_id, "sr.material_id" => $data2['material_id'], "sr.unit" => $data2['unit_id'], "sr.total_balance_qty >" => 0));
        }
        $remaining_qty = $total_stock_issued_qty;
        foreach ($stock_register->result() as $key => $value) {
          if ($remaining_qty > 0) {
            $available_stock_item_qty = $value->total_balance_qty;
            if ($remaining_qty > $available_stock_item_qty) {
              $data['quantity']  = $available_stock_item_qty;
            } else {
              $data['quantity']  = $remaining_qty;
            }
            $remaining_qty = $remaining_qty - $data['quantity'];
            $data['stock_id'] = $value->stock_id;
            $data['make_spec'] = $row['description'];
            $data['item_remarks'] = $row['remarks'];
            $data['bill_id'] = $bill_where_data['bill_id'];

            // Update Stock Consumption
            $result = $this->Subcontracts->create_material_issue_items($data);
            //  Update Stock Register
            $this->stock_management->calculate_stock_balance($data['stock_id']);
          }
        }
      }
    }
    // Check Items Deleted
    foreach ($bill_items as $key => $value) {
      if (!in_array($value->item_id, $existing_item_ids))
      {
        $item_where['item_id'] = $value->item_id;
        $item_data['delete_status'] = 1;
        $result = $this->Subcontracts->update_material_issue_items($item_where,$item_data);
        //  Update Stock Register
        $this->stock_management->calculate_stock_balance($value->stock_id);
      }
    }
    if (isset($bill_result) && $bill_result == 1) {
      $flash_data['status'] = $bill_result;
      $flash_data['bill_id'] = $bill_where_data['bill_id'];
      $flash_data['flashdata_msg'] = 'Material Issue Bill Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }
  public function delete_material_issue($redirect='')
  {
    $data['smb.bill_id'] = $update_data_where['bill_id'] = $this->security->xss_clean($this->input->post('bill_id'));
    $bill_data = $this->Subcontracts->select_material_issue_bill("smb.*,sl.work_id as from_work_id,sl.location_name as from_loc_name,u1.user_alias as created_user,wc.work_location as from_loc_address,c.contractor_name,c.contractor_id,c.phone as contractor_phone,c.contractor_address,u2.user_alias as supervisor_name,u2.phone_no as supervisor_phone", $data);
    if ($bill_data->num_rows() == 1) {
      $bill_data = $bill_data->row();
      $update_data['delete_status'] = 1;
      $bill_items = $this->Subcontracts->select_material_issue_items("smi.*", $data)->result();
      $result = $this->Subcontracts->update_material_issue_bill($update_data_where,$update_data);
      foreach ($bill_items as $key => $value) {
        // Update Stock Register
        $this->stock_management->calculate_stock_balance($value->stock_id);
      }
      if ($result == 1) {
        $flash_data['status'] = $result;
        $flash_data['flashdata_msg'] = 'Bill Deleted Saved Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      } else {
        $flash_data['status'] = 0;
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else {
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    if($redirect=='redirect'){
      $this->session->set_flashdata($flash_data);
      redirect(base_url().'subcontracts/material_issue', 'refresh');
    }else{
      echo json_encode($flash_data);
    }

  }
  public function create_material_return()
  {
    $stock_slnos = $this->input->post('stock_slnos');

    $data['returned_date'] = date('Y-m-d', strtotime($this->input->post('returned_date')));
    $data['created_date'] = date('Y-m-d H:i:s');
    $data['created_by'] = $this->session->userdata('user_id');
    $data['return_remarks'] = $this->input->post('remarks');

    $issued_items_where['smb.subcontract_id'] = $this->input->post('subcontract');
    $issued_items_where['smb.from_location_id'] = $this->input->post('location_form');
    $issued_items  = $this->Subcontracts->select_material_issue_items("smi.*",$issued_items_where)->result();
    foreach ($issued_items as $key => $value) {
      if ($this->input->post('qty_' . $value->item_id) && $this->input->post('qty_' . $value->item_id)>0) {
        $data['issue_item_id'] = $value->item_id;
        $data['returned_qty'] = $this->input->post('qty_' . $value->item_id);
        $result = $this->Subcontracts->create_material_return($data);
        //  Update Stock Register
        $result2 = $this->stock_management->calculate_stock_balance($value->stock_id);
      }
    }
    if (isset($result) && $result['status'] == 1) {
      $flash_data['status'] = $result['status'];
      $flash_data['flashdata_msg'] = 'Material Issue Return Saved Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['status'] = 0;
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }
  public function select_material_issue_items($page_data_type = "",$page='')
  {

    $json_data = array();
    $j = 0;
    $sl_no = 0;
    $data = $array = array();
    if(isset($_POST['location_from']) && $_POST['location_from']!='' && $_POST['location_from']!='all'){
      $data['smb.from_location_id'] = $_POST['location_from'];
    }
    if(isset($_POST['subcontract']) && $_POST['subcontract']!='' && $_POST['subcontract']!='all'){
      $data['smb.subcontract_id'] = $_POST['subcontract'];
    }
    if(isset($_POST['work_id']) && $_POST['work_id']!='' && $_POST['work_id']!='all'){
      $data['sl.work_id'] = $_POST['work_id'];
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['smb.created_by'] = $_POST['user_id'];
    }
    if($this->session->userdata('user_role')!='admin' && $this->config->item('user_data_access_view_all')!=1){
      $data['smb.created_by'] = $this->session->userdata('user_role');
    }
    if (isset($_POST['material_id']) && $_POST['material_id'] != '' && $_POST['material_id'] != 'all') {
      $data['sr.material_id'] = $_POST['material_id'];
    }

    $entry_approval = 1;
    if ($page_data_type == 'approval_entries') {
      $entry_approval = 'all';
      $data['u.user_role >'] = 2;
      if (isset($_POST['approval_status']) && $_POST['approval_status'] != '' && $_POST['approval_status'] != 'all') {
        $entry_approval = $_POST['approval_status'];
      }
    }
    // Select All Available Materials in Stock
    $result  = $this->Subcontracts->select_material_issue_items("smi.*,m.material_name,mu.unit_name,smb.*,sl.work_id as from_work_id,sl.work_id,sl.location_name as from_loc_name,u1.user_alias as created_user,wc.work_location as from_loc_address,c.contractor_name,c.contractor_id,c.phone as contractor_phone,c.contractor_address,u2.user_alias as supervisor_name,u2.phone_no as supervisor_phone", $data, '', $entry_approval);
    $total_amount = 0;
    foreach ($result->result() as $row) :


      $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="stock_transfer" data-approval-status="' . $row->entry_approval_status . '" data-id="' . $row->transfer_id . '" id="btn_data_entry_approval" href="#data_entry_approve_modal" data-toggle="modal" class="btn btn-sm btn-warning m-btn m-btn--icon  m-btn--pill m-btn--air">
        <i class="la la-check-circle"></i> / <i class="la la-times-circle"></i>
        </a>';
      }
      if ($page_data_type == 'approval_entries' && $this->config->item('Mobile_App_enable_data_entry_approval') == 1) {
        if ($row->entry_approval_status == 1) {
          $entry_approval_status = "<br/><span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Approved</span>";
        } elseif ($row->entry_approval_status == 2) {
          $entry_approval_status = "<br/><span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> Rejected</span>";
        } else {
          $entry_approval_status = "<br/><span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> Pending</span>";
        }
      }

      $returned_qty = $this->Subcontracts->select_material_return("COALESCE(SUM(smr.returned_qty),0) as total", array("smr.issue_item_id"=>$row->item_id))->row()->total;

      $sl_no++;
      $array[$j][] = $sl_no;
      $array[$j][] = $row->item_id;
      $array[$j][]='<a href="'.base_url().'subcontracts/material_issue/view/'.$row->bill_id.'">'."#".$row->bill_id.'</a>';
      $array[$j][]=date('d-m-Y',strtotime($row->bill_date));
      $array[$j][]='<a href="'.base_url().'work/profile/'.$row->work_id.'">'.$row->from_loc_name.'</a>';
      $array[$j][]="#".$row->contractor_id."-".$row->contractor_name."<br/>".$row->contractor_phone;
      $array[$j][] = $row->material_name;
      $array[$j][] = $row->make_spec;
      $array[$j][] = $row->unit_name;
      $array[$j][] = $row->quantity;
      $array[$j][] = $returned_qty;
      $array[$j][] = $row->quantity-$returned_qty;
      $array[$j][] = $row->item_remarks;
      $array[$j][] = $row->supervisor_name."<br/>".$row->supervisor_phone;
      $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_approve;
      if($page=='return'){
        $array[$j][] = '<div class="form-group m-form__group">
        <div class="input-group m-input-group m-input-group--pill">
        <input style="max-width: 100px;" required value="0" max="' . ($row->quantity-$returned_qty) . '" type="text" name="qty_' . $row->item_id . '" class="returned_qty numeric_fields form-control m-input m-input--pill m-input--air" placeholder="Returned Qty"  aria-describedby="basic-addon1">
        <div class="input-group-append"><span class="input-group-text" id="basic-addon1">' . $row->unit_name . '</span></div>
        </div>
        </div>';
      }

      $j++;


    endforeach;

    $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 select_material_issue_returns($page_data_type = "",$page='')
  {

    $json_data = array();
    $j = 0;
    $sl_no = 0;
    $data = $array = array();
    if(isset($_POST['location_from']) && $_POST['location_from']!='' && $_POST['location_from']!='all'){
      $data['smb.from_location_id'] = $_POST['location_from'];
    }
    if(isset($_POST['subcontract']) && $_POST['subcontract']!='' && $_POST['subcontract']!='all'){
      $data['smb.subcontract_id'] = $_POST['subcontract'];
    }
    if(isset($_POST['work_id']) && $_POST['work_id']!='' && $_POST['work_id']!='all'){
      $data['sl.work_id'] = $_POST['work_id'];
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['smb.created_by'] = $_POST['user_id'];
    }
    if($this->session->userdata('user_role')!='admin' && $this->config->item('user_data_access_view_all')!=1){
      $data['smb.created_by'] = $this->session->userdata('user_role');
    }
    if (isset($_POST['material_id']) && $_POST['material_id'] != '' && $_POST['material_id'] != 'all') {
      $data['sr.material_id'] = $_POST['material_id'];
    }

    $entry_approval = 1;
    if ($page_data_type == 'approval_entries') {
      $entry_approval = 'all';
      $data['u.user_role >'] = 2;
      if (isset($_POST['approval_status']) && $_POST['approval_status'] != '' && $_POST['approval_status'] != 'all') {
        $entry_approval = $_POST['approval_status'];
      }
    }
    // Select All Available Materials in Stock
    $result  = $this->Subcontracts->select_material_return("smr.*,smi.bill_id,smi.make_spec,m.material_name,mu.unit_name,smb.*,sl.work_id as from_work_id,sl.work_id,sl.location_name as from_loc_name,u1.user_alias as created_user,wc.work_location as from_loc_address,c.contractor_name,c.contractor_id,c.phone as contractor_phone,c.contractor_address,u2.user_alias as supervisor_name,u2.phone_no as supervisor_phone", $data, '', $entry_approval);
    $total_amount = 0;
    foreach ($result->result() as $row) :


      $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="stock_transfer" data-approval-status="' . $row->entry_approval_status . '" data-id="' . $row->transfer_id . '" id="btn_data_entry_approval" href="#data_entry_approve_modal" data-toggle="modal" class="btn btn-sm btn-warning m-btn m-btn--icon  m-btn--pill m-btn--air">
        <i class="la la-check-circle"></i> / <i class="la la-times-circle"></i>
        </a>';
      }
      if ($page_data_type == 'approval_entries' && $this->config->item('Mobile_App_enable_data_entry_approval') == 1) {
        if ($row->entry_approval_status == 1) {
          $entry_approval_status = "<br/><span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> Approved</span>";
        } elseif ($row->entry_approval_status == 2) {
          $entry_approval_status = "<br/><span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> Rejected</span>";
        } else {
          $entry_approval_status = "<br/><span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> Pending</span>";
        }
      }

      $sl_no++;
      $array[$j][] = $sl_no;
      $array[$j][] = $row->return_id;
      $array[$j][]='<a href="'.base_url().'subcontracts/material_issue/view/'.$row->bill_id.'">'."#".$row->bill_id.'</a>';
      $array[$j][]=date('d-m-Y',strtotime($row->returned_date));
      $array[$j][]='<a href="'.base_url().'work/profile/'.$row->work_id.'">'.$row->from_loc_name.'</a>';
      $array[$j][]="#".$row->contractor_id."-".$row->contractor_name."<br/>".$row->contractor_phone;
      $array[$j][] = $row->material_name;
      $array[$j][] = $row->make_spec;
      $array[$j][] = $row->unit_name;
      $array[$j][] = $row->returned_qty;
      $array[$j][] = $row->return_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][] = '';
      }

      $j++;


    endforeach;

    $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 select_material_issue_bills($param=""){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $data=$array=array();
    if(isset($_POST['location_from']) && $_POST['location_from']!='' && $_POST['location_from']!='all'){
      $data['smb.from_location_id'] = $_POST['location_from'];
    }
    if(isset($_POST['subcontract']) && $_POST['subcontract']!='' && $_POST['subcontract']!='all'){
      $data['smb.subcontract_id'] = $_POST['subcontract'];
    }
    if(isset($_POST['work_id']) && $_POST['work_id']!='' && $_POST['work_id']!='all'){
      $data['sl.work_id'] = $_POST['work_id'];
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['smb.created_by'] = $_POST['user_id'];
    }
    if($this->session->userdata('user_role')!='admin' && $this->config->item('user_data_access_view_all')!=1){
      $data['smb.created_by'] = $this->session->userdata('user_role');
    }
    $result	= $this->Subcontracts->select_material_issue_bill("smb.*,sl.work_id as from_work_id,sl.work_id,sl.location_name as from_loc_name,u1.user_alias as created_user,wc.work_location as from_loc_address,c.contractor_name,c.contractor_id,c.phone as contractor_phone,c.contractor_address,u2.user_alias as supervisor_name,u2.phone_no as supervisor_phone",$data);
    foreach ($result->result() as $row):
      $btn_edit=$btn_delete='';
      if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager'){
        $btn_edit='<a style="margin-left: 5px;margin-right: 5px" href="'.base_url().'subcontracts/material_issue/edit/'.$row->bill_id.'" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="material_issue_bill_delete_btn" href="#material_issue_bill_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only  m-btn--pill m-btn--air">
        <i class="la la-trash"></i>
        </a>';
      }
      $sl_no++;
      $array[$j][]=$sl_no;
      $array[$j][]='<a href="'.base_url().'subcontracts/material_issue/view/'.$row->bill_id.'">'."#".$row->bill_id.'</a>';
      $array[$j][]=date('d-m-Y',strtotime($row->bill_date));
      $array[$j][]='<a href="'.base_url().'work/profile/'.$row->work_id.'">'.$row->from_loc_name.'</a>';
      $array[$j][]="#".$row->contractor_id."-".$row->contractor_name."<br/>".$row->contractor_phone;
      $array[$j][]=$row->supervisor_name."<br/>".$row->supervisor_phone;
      $array[$j][]=$row->vehicle_no."<br/>".$row->vehicle_driver_phone;
      $array[$j][]=$row->bill_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->created_user."</li>";
      }else{
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->created_user.'</li>';
      }
      $array[$j][]=$btn_edit.$btn_delete;
      $array[$j][]=$row->bill_id;

      $j++;

    endforeach;

    $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
  }

}
