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

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

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

    $this->load->model('User_model', 'User');
    $this->load->model('Work_model', 'Work');
    $this->load->model('Client_model', 'Client');
    $this->load->model('Supplier_model', 'Supplier');
    $this->load->model('Purchase_bill_model', 'Purchases');
    $this->load->model('Purchase_order_model', 'Purchase_order');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Employees_model', 'Employee');
    $this->load->model('Salary_slips_model', 'Salary_slips');
    $this->load->model('Bills_model', 'Bills');
    $this->load->model('Loan_model', 'Loan');
    $this->load->library('Bills_management','bills_management');
    $this->load->model('Vehicle_model', 'Vehicle');
    $this->load->model('Vehicle_work_slips_model', 'Vehicle_work_slips');
    $this->load->model('Tools_model', 'Tools');
    $this->load->library('Stock_management','stock_management');
    $this->load->model('Subcontracts_model', 'Subcontracts');

    $this->load->library('Projects_management','projects_management');

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

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

  public function view($param1="")
  {

  }

  public function create()
  {
    $redirect_url= $this->security->xss_clean($this->input->post('redirect_url'));
    $subcontract_data_type='';
    $bill_data['bill_type'] = $this->security->xss_clean($this->input->post('bill_type'));
    if($bill_data['bill_type']=='expense'){
      $bill_data['bill_expense_type'] = $this->security->xss_clean($this->input->post('expense_type'));
      if($bill_data['bill_expense_type']=='work'){
        $bill_data['work_id'] = $this->security->xss_clean($this->input->post('work_id'));
        $bill_data['project_stage_id'] = $this->projects_management->get_project_stage_id($bill_data['work_id']);
      }else{
        $bill_data['work_id'] = 0;
      }
      $bill_data['bill_credit_ac'] = $this->security->xss_clean($this->input->post('expense_head'));
    }elseif($bill_data['bill_type']=='subcontract'){
      $bill_data['subcontract_id'] = $this->security->xss_clean($this->input->post('subcontract_id'));
      $bill_data['bill_credit_ac'] = "8"; //Subcontract Payments
      // Select Work
      $bill_data['work_id'] = $this->Subcontracts->select_subcontract("sc.work_id",array("sc.contract_id"=>$bill_data['subcontract_id']))->row()->work_id;
      $subcontract_data_type = $this->security->xss_clean($this->input->post('subcontract_data_type'));
      $bill_data['subcontract_labours_no'] = $this->security->xss_clean($this->input->post('subcontract_labours_no'));
      if(isset($bill_data['work_id']) && $bill_data['work_id']!=''){
        $bill_data['project_stage_id'] = $this->projects_management->get_project_stage_id($bill_data['work_id']);
      }
      if($this->config->item('Subcontract_bill_template')==2 && $this->input->post('subcontract_bill_type')){
        $bill_data['subcontract_bill_type'] = $this->security->xss_clean($this->input->post('subcontract_bill_type'));
      }
    }elseif($bill_data['bill_type']=='vehicle'){
      $bill_data['bill_expense_type'] = $this->security->xss_clean($this->input->post('expense_type'));
      $bill_data['vehicle_id'] = $this->security->xss_clean($this->input->post('vehicle_id'));
      $bill_data['bill_credit_ac'] = $this->security->xss_clean($this->input->post('expense_head'));
      $bill_data['bill_supplier_id'] = $this->security->xss_clean($this->input->post('supplier_id'));
    }
    if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
      $bill_data['entry_approval_status'] = 0;
    }
    if($bill_data['bill_type']=='expense' && $this->config->item('User_enable_data_entry_approval_2_level')==1 && $this->session->userdata('user_role_id')>2){
      $bill_data['entry_approval_status_2'] = 0;
    }
    if($subcontract_data_type!='advance_payment'){
      if($bill_data['bill_type']=='subcontract' && $this->config->item('Subcontract_bill_type')=='work_items_based'){
        $bill_work_items = array();
        $work_items = $this->Subcontracts->select_subcontract_work_items("scwi.*,wt.type_name,mu.unit_name", array("sc.contract_id" => $bill_data['subcontract_id']))->result();
        foreach ($work_items as $key => $value) {
          if($this->input->post('qty_'.$value->item_id) && $this->input->post('qty_'.$value->item_id)!=''){
            $item_data = array();
            $item_data['item_type'] = 'subcontract_work_item';
            $item_data['item_id'] = $value->item_id;
            $item_data['qty'] = $this->input->post('qty_'.$value->item_id);
            $item_data['unit_rate'] = $this->input->post('unit_rate_'.$value->item_id);
            $bill_work_items[] = $item_data;
          }
        }
        if(!empty($bill_work_items)){
          $bill_data['bill_items'] = serialize($bill_work_items);
        }


      }elseif($bill_data['bill_type']=='expense' && $this->input->post('bill_items') && $this->input->post('bill_items')!=''){ //Local Material Purchase
        // $bill_work_items = array();
        // $bill_items=$newArrayitems=array();
        //   $bill_items = $this->security->xss_clean($this->input->post('bill_items'));
        // $items_array_length = sizeof($bill_items);
        // // Convert to New Formatted Array
        // foreach (array_keys($bill_items) as $fieldKey) {
        //   foreach ($bill_items[$fieldKey] as $key=>$value) {
        //     $newArrayitems[$key][$fieldKey] = $value;
        //   }
        // }
        // foreach ($newArrayitems as $row) {
        //   $item_data = array();
        //   $item_data['item_type'] = 'expense_bill_item';
        //   $item_data['item_name'] = $row['item_name'];
        //   $item_data['item_qty'] = $row['item_qty'];
        //   $item_data['item_unit'] = $row['item_unit'];
        //   $item_data['item_rate'] = $row['item_rate'];
        //   $item_data['item_total'] = $row['item_total'];
        //   $bill_work_items[] = $item_data
        // }
        //
        // if(!empty($bill_work_items)){
        //   $bill_data['bill_items'] = serialize($bill_work_items);
        // }
      }

      $bill_data['bill_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('bill_date'))));
      $bill_data['bill_no'] = $this->security->xss_clean($this->input->post('bill_no'));
      if($this->input->post('bill_amount')){
        $bill_data['bill_gross_amount'] = $this->security->xss_clean($this->input->post('bill_amount'));
      }
      $bill_data['bill_tax_percent'] = $this->security->xss_clean($this->input->post('bill_tax_percent'));
      $bill_data['bill_tax_amount'] = $bill_data['bill_tds_amount'] = 0;
      if($this->input->post('bill_retention_percent')){
        $bill_data['bill_retention_percent'] = (float) $this->security->xss_clean($this->input->post('bill_retention_percent'));
      }
      if($this->input->post('bill_retention_amount')){
        $bill_data['bill_retention_amount'] = (float) $this->security->xss_clean($this->input->post('bill_retention_amount'));
      }

      if($this->input->post('bill_gross_amount')){
        $bill_data['bill_gross_amount'] = (float) $this->security->xss_clean($this->input->post('bill_gross_amount'));
      }
      if($this->input->post('bill_tax_amount')){
        $bill_data['bill_tax_amount'] = (float) $this->security->xss_clean($this->input->post('bill_tax_amount'));
      }
      if($this->input->post('bill_tds_amount')){
        $bill_data['bill_tds_amount'] = $this->security->xss_clean($this->input->post('bill_tds_amount'));
      }
      if($this->input->post('bill_deduction_amount')){
        $bill_data['other_deductions'] = $this->security->xss_clean($this->input->post('bill_deduction_amount'));
      }
      if($this->input->post('bill_tax_no')){
        $bill_data['bill_tax_no'] = $this->security->xss_clean($this->input->post('bill_tax_no'));
      }
      $bill_data['bill_amount'] = (float) $bill_data['bill_gross_amount'] + (float) $bill_data['bill_tax_amount'];
      $bill_data['bill_payable_amount'] = $this->security->xss_clean($this->input->post('bill_payable_amount'));
      $bill_data['bill_consignee_name'] = $this->security->xss_clean($this->input->post('consignee'));
      $bill_data['bill_description'] = $this->security->xss_clean($this->input->post('bill_description'));
      $bill_data['bill_remarks'] = $this->security->xss_clean($this->input->post('bill_remarks'));
      $bill_data['created_date'] = date('Y-m-d H:i:s');
      $bill_data['created_by'] = $this->session->userdata('user_id');

      //      File Validations
      $file_error = 0;
      if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']["size"] > 0) {
        //      File Upload
        $config['upload_path']   = 'uploads/bills/';
        $config['allowed_types'] = 'jpg|jpeg|png|pdf|doc|docx|xls|xl';
        $config['max_size']      = 3000;
        // $config['max_width']     = 1980;
        // $config['max_height']    = 1080;
        $config['encrypt_name']    = TRUE;
        // $config['file_name'] = date('YmdHis');
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('uploaded_file')) {
          $error = array('error' => $this->upload->display_errors());
          $file_error = 1;
          $flash_data['flashdata_msg'] = $error['error'];
          $flash_data['flashdata_type'] = "warning";
          $flash_data['flashdata_title'] = "Uploaded File Error";
          $flash_data['status'] = 2;
        }else {
          $file_data = $this->upload->data();
          $bill_data['bill_attachment'] = $file_data['file_name'];
        }
      }
      if($file_error==0){
        $bill_result =  $this->Bills->create_bills($bill_data);
        $flash_data['status'] = $bill_result['status'];
        if ($flash_data['status'] == 1) {
          $flash_data['flashdata_msg'] = ucwords($bill_data['bill_type']).' Bill Created Successfully!.';
          $flash_data['flashdata_type'] = 'success';
          $flash_data['alert_type'] = 'success';
          $flash_data['flashdata_title'] = 'Success !';

          if($bill_data['bill_type']=='subcontract' && $this->config->item('Subcontract_labours')==1){
            $labours = $this->security->xss_clean($this->input->post('labours'));
            $subcontract_labour_data['bill_id'] = $bill_result['insert_id'];
            $subcontract_labour_data['created_date'] = date('Y-m-d H:i:s');
            $subcontract_labour_data['created_by'] = $this->session->userdata('user_id');
            if($labours!=''){
              foreach ($labours as $key2 => $value2) {
                $subcontract_labour_data['labour_id'] = $value2;
                $subcontract_labour_data['no_of_days'] = $this->security->xss_clean($this->input->post('days_'.$value2));
                $labour_result =  $this->Subcontracts->create_subcontract_labour_wage($subcontract_labour_data);
              }
            }
          }
          if($bill_data['bill_type']=='subcontract' && $this->config->item('Subcontract_bill_template')==2 && $this->input->post('subcontract_bill_type')){
            $bill_items=$newArrayitems=array();
            if($this->input->post('bill_items')){
              $bill_items = $this->security->xss_clean($this->input->post('bill_items'));
            }
            $items_array_length = sizeof($bill_items);
            // Convert to New Formatted Array
            foreach (array_keys($bill_items) as $fieldKey) {
              foreach ($bill_items[$fieldKey] as $key=>$value) {
                $newArrayitems[$key][$fieldKey] = $value;
              }
            }
            $item_data['bill_id'] = $bill_result['insert_id'];
            foreach ($newArrayitems as $row) {
              $item_data['item_description'] = $row['description'];
              $item_data['total_qty'] = $row['item_qty'];
              $item_data['unit'] = $row['unit'];
              $item_data['unit_rate'] = $row['unit_price'];
              $item_data['total_amount'] = $row['item_total'];
              $item_data['item_remarks'] = $row['remarks'];
              $item_result =  $this->Bills->create_bill_items($item_data);
            }
          }
          if($bill_data['bill_type']=='expense' && $this->input->post('bill_items') && $this->input->post('bill_items')!=''){
            $bill_work_items = array();
            $bill_items=$newArrayitems=array();
              $bill_items = $this->security->xss_clean($this->input->post('bill_items'));
            $items_array_length = sizeof($bill_items);
            // Convert to New Formatted Array
            foreach (array_keys($bill_items) as $fieldKey) {
              foreach ($bill_items[$fieldKey] as $key=>$value) {
                $newArrayitems[$key][$fieldKey] = $value;
              }
            }

            foreach ($newArrayitems as $row) {
              $item_data = array();
              $item_data['bill_id'] = $bill_result['insert_id'];
              $item_data['item_description'] = $row['item_name'];
              $item_data['total_qty'] = $row['item_qty'];
              $item_data['unit'] = $row['item_unit'];
              $item_data['unit_rate'] = $row['item_rate'];
              $item_data['total_amount'] = $row['item_total'];
              $item_result =  $this->Bills->create_bill_items($item_data);
            }
          }

          if($this->input->post('paid_amount')>0){
            $transaction_data['reference_id'] = $bill_result['insert_id'];
            $transaction_data['reference_type'] = $bill_data['bill_type']."_bill";
            $transaction_data['tr_type'] = $bill_data['bill_type']."_bill_transaction";
            $transaction_data['tr_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('paid_date'))));
            $transaction_data['tr_debit_acc'] = $this->security->xss_clean($this->input->post('debit_acc'));
            $transaction_data['tr_credit_acc'] = $bill_data['bill_credit_ac'];
            $transaction_data['tr_description'] = ucwords($bill_data['bill_type'])." Bill Transaction";
            $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('paid_amount'));
            $transaction_data['tr_mode'] = $this->security->xss_clean($this->input->post('payment_mode'));
            $transaction_data['tr_reference_no'] = $this->security->xss_clean($this->input->post('reference_no'));
            if($this->input->post('reference_date')!=''){
              $transaction_data['tr_reference_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('reference_date'))));
            }
            $transaction_data['tr_remarks'] = $this->security->xss_clean($this->input->post('tr_remarks'));
            $transaction_data['created_date'] = date('Y-m-d H:i:s');
            $transaction_data['created_by'] = $this->session->userdata('user_id');
            $transaction_result =  $this->Account->create_account_transaction($transaction_data);
            if($transaction_result['status']==1){
              $flash_data['flashdata_msg'] .= " Transaction Entry Added.";
            }else{
              $flash_data['flashdata_msg'] .= " Transaction Entry Adding Failed !!";
            }
          }
          // Calculate & Update Bill Total
          $this->bills_management->calculate_bill_total($bill_result['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 !!';
        }
      }else{
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Associated with Uploaded File. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'File Error !!';
      }
    }elseif($subcontract_data_type=='advance_payment'){
      if($this->input->post('paid_amount')>0){
        $transaction_data['reference_id'] = $this->security->xss_clean($this->input->post('subcontract_id'));
        $work_id = $this->Subcontracts->select_subcontract("sc.work_id",array("sc.contract_id"=>$transaction_data['reference_id']))->row()->work_id;
        $transaction_data['tr_project_stage_id'] = $this->projects_management->get_project_stage_id($work_id);

        $transaction_data['reference_type'] = "subcontract";
        $transaction_data['tr_type'] = "subcontract_advance_transaction";
        $transaction_data['tr_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('paid_date'))));
        $transaction_data['tr_debit_acc'] = $this->security->xss_clean($this->input->post('debit_acc'));
        $transaction_data['tr_credit_acc'] = "8"; //Subcontract Payments
        $transaction_data['tr_description'] = "Subcontract Advance Transaction";
        $transaction_data['tr_amount'] = $this->security->xss_clean($this->input->post('paid_amount'));
        $transaction_data['tr_mode'] = $this->security->xss_clean($this->input->post('payment_mode'));
        $transaction_data['tr_reference_no'] = $this->security->xss_clean($this->input->post('reference_no'));
        if($this->input->post('reference_date')!=''){
          $transaction_data['tr_reference_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('reference_date'))));
        }
        $transaction_data['tr_remarks'] = $this->security->xss_clean($this->input->post('tr_remarks'));
        $transaction_data['created_date'] = date('Y-m-d H:i:s');
        $transaction_data['created_by'] = $this->session->userdata('user_id');
        if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
          $transaction_data['tr_entry_approval_status'] = 0;
        }
        $transaction_result =  $this->Account->create_account_transaction($transaction_data);
        $flash_data['status'] = $transaction_result['status'];
        if($transaction_result['status']==1){
          $flash_data['flashdata_msg'] = " Transaction Entry Added Successfully.";
          $flash_data['flashdata_type'] = 'success';
          $flash_data['alert_type'] = 'success';
          $flash_data['flashdata_title'] = 'Success !';
        }else{
          $flash_data['flashdata_msg'] = " Transaction Entry Adding Failed !!";
          $flash_data['flashdata_type'] = 'error';
          $flash_data['alert_type'] = 'danger';
          $flash_data['flashdata_title'] = 'Error !!';
        }
      }else{
        $flash_data['flashdata_msg'] = " Transaction Entry Adding Failed !!";
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else{
      $flash_data['flashdata_msg'] = " Transaction Entry Adding Failed !!";
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }
  public function update()
  {
    $redirect_url= $this->security->xss_clean($this->input->post('redirect_url'));
    $bill_data['bill_id'] = $this->security->xss_clean($this->input->post('bill_id'));
    $bill_data['bill_type'] = $this->security->xss_clean($this->input->post('bill_type'));
    if($bill_data['bill_type']=='expense'){
      $bill_data['bill_expense_type'] = $this->security->xss_clean($this->input->post('expense_type_edit'));
      $expense_type = $this->security->xss_clean($this->input->post('expense_type_edit'));
      if($expense_type=='work'){
        $bill_data['work_id'] = $this->security->xss_clean($this->input->post('work_id'));
      }else{
        $bill_data['work_id'] = 0;
      }
      $bill_data['bill_credit_ac'] = $this->security->xss_clean($this->input->post('expense_head'));
    }elseif($bill_data['bill_type']=='subcontract'){
      $bill_data['subcontract_id'] = $this->security->xss_clean($this->input->post('subcontract_id'));
      $bill_data['bill_credit_ac'] = "8"; //Subcontract Payments
      $bill_data['subcontract_labours_no'] = $this->security->xss_clean($this->input->post('subcontract_labours_no'));
    }elseif($bill_data['bill_type']=='vehicle'){
      $bill_data['bill_expense_type'] = $this->security->xss_clean($this->input->post('expense_type_edit'));
      $bill_data['vehicle_id'] = $this->security->xss_clean($this->input->post('vehicle_id'));
      $bill_data['bill_credit_ac'] = $this->security->xss_clean($this->input->post('expense_head'));
      $bill_data['bill_supplier_id'] = $this->security->xss_clean($this->input->post('supplier_id'));
    }

    if($bill_data['bill_type']=='expense' && $bill_data['bill_credit_ac']=='23'){ //Local Material Purchase
      $bill_work_items = array();
      $bill_items=$newArrayitems=array();
      if($this->input->post('bill_items')){
        $bill_items = $this->security->xss_clean($this->input->post('bill_items'));
      }
      $items_array_length = sizeof($bill_items);
      // Convert to New Formatted Array
      foreach (array_keys($bill_items) as $fieldKey) {
        foreach ($bill_items[$fieldKey] as $key=>$value) {
          $newArrayitems[$key][$fieldKey] = $value;
        }
      }
      foreach ($newArrayitems as $row) {
        $item_data = array();
        $item_data['item_type'] = 'expense_bill_item';
        $item_data['item_name'] = $row['item_name'];
        $item_data['item_qty'] = $row['item_qty'];
        $item_data['item_total'] = $row['item_total'];
        $bill_work_items[] = $item_data;
      }

      if(!empty($bill_work_items)){
        $bill_data['bill_items'] = serialize($bill_work_items);
      }
    }

    $bill_data['bill_date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('bill_date'))));
    $bill_data['bill_no'] = $this->security->xss_clean($this->input->post('bill_no'));
    $bill_data['bill_gross_amount'] = $this->security->xss_clean($this->input->post('bill_amount'));
    $bill_data['bill_tax_percent'] = $this->security->xss_clean($this->input->post('bill_tax_percent'));
    $bill_data['bill_tax_amount'] = $bill_data['bill_tds_amount'] = 0;
    if($this->input->post('bill_gross_amount')){
      $bill_data['bill_gross_amount'] = $this->security->xss_clean($this->input->post('bill_gross_amount'));
    }
    if($this->input->post('bill_tax_amount')){
      $bill_data['bill_tax_amount'] = $this->security->xss_clean($this->input->post('bill_tax_amount'));
    }
    if($this->input->post('bill_tds_amount')){
      $bill_data['bill_tds_amount'] = $this->security->xss_clean($this->input->post('bill_tds_amount'));
    }
    if($this->input->post('bill_retention_percent')){
      $bill_data['bill_retention_percent'] = (float) $this->security->xss_clean($this->input->post('bill_retention_percent'));
    }
    if($this->input->post('bill_retention_amount')){
      $bill_data['bill_retention_amount'] = (float) $this->security->xss_clean($this->input->post('bill_retention_amount'));
    }
    if($this->input->post('bill_deduction_amount')){
      $bill_data['other_deductions'] = $this->security->xss_clean($this->input->post('bill_deduction_amount'));
    }
    if($this->input->post('bill_tax_no')){
      $bill_data['bill_tax_no'] = $this->security->xss_clean($this->input->post('bill_tax_no'));
    }
    $bill_data['bill_amount'] = $bill_data['bill_gross_amount'] + $bill_data['bill_tax_amount'];
    $bill_data['bill_payable_amount'] = $this->security->xss_clean($this->input->post('bill_payable_amount'));
    $bill_data['bill_amount'] = $this->security->xss_clean($this->input->post('bill_payable_amount'));
    $bill_data['bill_consignee_name'] = $this->security->xss_clean($this->input->post('consignee'));
    $bill_data['bill_description'] = $this->security->xss_clean($this->input->post('bill_description'));
    $bill_data['bill_remarks'] = $this->security->xss_clean($this->input->post('bill_remarks'));
    $bill_data['bill_tax_percent'] = $this->security->xss_clean($this->input->post('bill_tax_percent'));
    $bill_data['updated_date'] = date('Y-m-d H:i:s');
    $bill_data['updated_by'] = $this->session->userdata('user_id');

    //      File Validations
    $file_error = 0;
    if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']["size"] > 0) {
      //      File Upload
      $config['upload_path']   = 'uploads/bills/';
      $config['allowed_types'] = 'jpg|jpeg|png|pdf|doc|docx|xls|xl';
      $config['max_size']      = 3000;
      // $config['max_width']     = 1980;
      // $config['max_height']    = 1080;
      $config['encrypt_name']    = TRUE;
      // $config['file_name'] = date('YmdHis');
      $this->load->library('upload', $config);
      if (!$this->upload->do_upload('uploaded_file')) {
        $error = array('error' => $this->upload->display_errors());
        $file_error = 1;
        $flash_data['flashdata_msg'] = $error['error'];
        $flash_data['flashdata_type'] = "warning";
        $flash_data['flashdata_title'] = "Uploaded File Error";
        $flash_data['status'] = 2;
      }else {
        $file_data = $this->upload->data();
        $bill_data['bill_attachment'] = $file_data['file_name'];
      }
    }else{
      if($this->input->post('attachment_delete_status')==1){
        $bill_data['bill_attachment'] = "";
      }
    }

    if($file_error==0){
      $bill_result =  $this->Bills->update_bills($bill_data);
      $flash_data['status'] = $bill_result;
      if ($flash_data['status'] == 1) {
        if($bill_data['bill_type']=='expense'){
          // Update Head(tr_credit_acc) in Transaction
          $bill_transaction_where['ats.reference_type'] = 'expense_bill';
          $bill_transaction_where['ats.tr_type'] = 'expense_bill_transaction';
          $bill_transaction_where['ats.reference_id'] = $bill_data['bill_id'];
          $bill_transactions = $this->Account->select_account_transaction("ats.transaction_id", $bill_transaction_where,'expense_bill')->result();
          foreach ($bill_transactions as $key => $value) {
            $transaction_update_data['transaction_id'] = $value->transaction_id;
            $transaction_update_data['tr_credit_acc'] = $bill_data['bill_credit_ac'];
            $this->Account->update_account_transaction($transaction_update_data);
          }
        }

        $flash_data['flashdata_msg'] = ucwords($bill_data['bill_type']).' Bill Details Updated Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';

        // Calculate & Update Bill Total
        $this->bills_management->calculate_bill_total($bill_data['bill_id']);
      } else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
      echo json_encode($flash_data);
    }

  }
  public function delete()
  {
    $redirect_url= $this->security->xss_clean($this->input->post('redirect_url'));
    $bill_type = $this->security->xss_clean($this->input->post('bill_type'));
    if($bill_type=='purchase_bill'){
      $bill_data['purchase_id'] = $this->security->xss_clean($this->input->post('bill_id'));
      $bill_data['delete_status']=1;
      $bill_details = $this->Purchases->select_purchase("p.*",array("p.purchase_id"=>$bill_data['purchase_id']),'all','','','all')->row();
      if($bill_details->purchase_order_id!=0){
        // Check Payemnts Need to Return to Order
        // $purchase_bill_payments = $this->Account->select_account_transaction("ats.*", array("ats.reference_id" => $bill_data['purchase_id'], "ats.reference_type" => 'purchase_bill'),'purchase_bill')->result();
      }
      $bill_result = $this->Purchases->update_purchase($bill_data);
      if($bill_data['purchase_id']!=0){
        $where_data['purchase_id'] = $bill_data['purchase_id'];
        $update_data['delete_status']=1;
        $bill_result_2 = $this->Bills->update_bills_2($where_data,$update_data);
        $this->stock_management->update_stock_register($bill_data['purchase_id']);
      }


      // Delete Supplier Advance Redeem
      $advance_return_transaction = $this->Account->select_advance_return_transaction("art.*,u.user_alias as created_user",array("art.reference_id" => $bill_data['purchase_id'],"art.tr_type" => 'purchase_bill_transaction',"art.reference_type" => 'purchase_bill'))->result();
      foreach ($advance_return_transaction as $key => $value) {
        $advance_return_transaction_data['tr_id'] = $value->tr_id;
        $advance_return_transaction_data['delete_status'] = 1;
        $this->Account->update_advance_return_transaction($advance_return_transaction_data);
      }
      if($bill_result==1 && $bill_details->purchase_order_id!=0){
        // Check Payemnts Need to Return to Order
        // foreach ($purchase_bill_payments as $key => $value) {
        //
        // }

        // Remove Bill Id from Purchase Order
        $order_details =  $this->Purchase_order->select_purchase_order("purchase_bill_id",array("po.order_id"=>$bill_details->purchase_order_id));
        if($order_details->num_rows()==1){
          $order_data['order_id'] = $bill_details->purchase_order_id;
          $bill_id_array = explode(',',$order_details->row()->purchase_bill_id);
          if (($key = array_search($bill_data['purchase_id'], $bill_id_array)) !== false) {
            unset($bill_id_array[$key]);
          }
          if(sizeof($bill_id_array)>0){
            $order_data['purchase_bill_id'] = implode(',',$bill_id_array);
          }else{
            $order_data['purchase_bill_id'] = '';
          }
          $this->Purchase_order->update_purchase_order($order_data);
        }
      }
      $bill_type = 'Purchase';
    }elseif($bill_type=='purchase_order'){
      $bill_data['order_id'] = $this->security->xss_clean($this->input->post('bill_id'));
      $bill_data['delete_status']=1;
      $bill_result = $this->Purchase_order->update_purchase_order($bill_data);
      $bill_type = 'Purchase Order';
      // Delete Supplier Advance Redeem
      $advance_return_transaction = $this->Account->select_advance_return_transaction("art.*,u.user_alias as created_user",array("art.reference_id" => $bill_data['order_id'],"art.tr_type" => 'purchase_order_transaction',"art.reference_type" => 'purchase_order'))->result();
      foreach ($advance_return_transaction as $key => $value) {
        $advance_return_transaction_data['tr_id'] = $value->tr_id;
        $advance_return_transaction_data['delete_status'] = 1;
        $this->Account->update_advance_return_transaction($advance_return_transaction_data);
      }
    }elseif($bill_type=='expense_bill' || $bill_type=='subcontract_bill' || $bill_type=='vehicle_bill'){
      $bill_data['bill_id'] = $this->security->xss_clean($this->input->post('bill_id'));
      $bill_data['delete_status']=1;
      $bill_details	= $this->Bills->select_bills("b.bill_type",array("b.bill_id"=>$bill_data['bill_id']),'','','','all','all')->row();
      $bill_result = $this->Bills->update_bills($bill_data);
      $bill_type = $bill_details->bill_type;
    }

    $flash_data['status'] = $bill_result;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = ucwords($bill_type).' Bill 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 get_details()
  {
    $data = array();
    $json_data['count'] = 0;
    $bill_type = $_POST['bill_type'];
    if($bill_type=='expense_bill' || $bill_type=='subcontract_bill' || $bill_type=='vehicle_bill'){
      $data['b.bill_id'] = $_POST['bill_id'];
      $bill_data = $this->Bills->select_bills("b.*,ah1.acc_head_id,ah1.acc_head_name as credit_account,u.user_alias,wc.work_name,c.contractor_name,sc.contractor,sc.sub_work_name,sc.contract_id,v.id,v.vehicle_no,v.vehicle_name,vc.consignee_name as vehicle_consignee_name",$data,$bill_type,'','',$this->config->item('select_data_entry_approval'),$this->config->item('select_data_entry_approval'));
      if($bill_data->num_rows()==1){
        $bill_data = $bill_data->row();
        $json_data['count'] = 1;
        $json_data['bill_id'] = "#".$bill_data->bill_id;
        $json_data['bill_no'] = $bill_data->bill_no;
        $json_data['bill_date'] = date('d-m-Y',strtotime($bill_data->bill_date));
        $json_data['bill_total_amount'] = number_format($bill_data->bill_payable_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['bill_total_paid'] = number_format($bill_data->bill_total_paid,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['bill_balance_amount'] = number_format($bill_data->bill_balance_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['consignee'] = $bill_data->bill_consignee_name;
        $json_data['credit_account'] = $bill_data->credit_account;
        $json_data['credit_acc'] = $bill_data->acc_head_id;
        if($bill_type=='subcontract_bill'){
          $json_data['subwork_name'] = $bill_data->sub_work_name;
          $json_data['contract_id'] = $bill_data->contract_id;
          $json_data['project_name'] = $bill_data->work_name;
          $work_types="<ul style='padding-left: 25px;margin-bottom: 0'>";
          if(isset($bill_data->work_type_names)){
            $work_types_array = explode(",",$bill_data->work_type_names);
            foreach ($work_types_array as $key => $value) {
              $work_types .= "<li>".$value."</li>";
            }
          }
          $work_types.="</ul>";
          $json_data['subwork_types'] = $work_types;
        }elseif($bill_type=='vehicle_bill'){
          $json_data['vehicle_id'] = $bill_data->id;
          $json_data['vehicle_no'] = $bill_data->vehicle_no;
          $json_data['vehicle_name'] = $bill_data->vehicle_name;
          $json_data['vehicle_consignee_name'] = $bill_data->vehicle_consignee_name;
        }
      }
    }elseif($bill_type=='subcontract'){
      // subcontract Advance
      $data['sc.contract_id'] = $_POST['bill_id'];
      $bill_data = $this->Subcontracts->select_subcontract("sc.*,u.user_alias,wc.work_name,c.contractor_name",$data);
      if($bill_data->num_rows()==1){
        $bill_data = $bill_data->row();
        $bill_amount=$this->Bills->select_bills("COALESCE(SUM(bill_payable_amount),0) as total_amount",array("b.subcontract_id"=>$bill_data->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"=>$bill_data->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" => $bill_data->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"=>$bill_data->contract_id,"b.bill_type"=>'subcontract'))->row()->total_amount;

        $json_data['count'] = 1;
        $json_data['bill_id'] = "#".$bill_data->contract_id;
        $json_data['bill_no'] = '';
        $json_data['bill_date'] = '';
        $json_data['bill_total_amount'] = '';
        $json_data['bill_total_paid'] = '';
        $json_data['bill_balance_amount'] = '';
        $json_data['consignee'] = $bill_data->contractor_name;
        $json_data['credit_account'] = '';
        $json_data['subwork_name'] = $bill_data->sub_work_name;
        $json_data['contract_id'] = $bill_data->contract_id;
        $json_data['project_name'] = $bill_data->work_name;
        $json_data['bill_amount'] = number_format($bill_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['bill_paid_amount'] = number_format($bill_paid_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['advance_paid_amount'] = number_format($advance_paid_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['bill_balance_amount'] = number_format($bill_balance_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['est_budget'] = number_format($bill_data->total_budget,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['budget_balance'] = number_format(($bill_data->total_budget-($bill_paid_amount+$advance_paid_amount)),$this->config->item('Currency_amount_decimals_2'),'.','');
        $work_types="<ul style='padding-left: 25px;margin-bottom: 0'>";
        $work_types_array = explode(",",$bill_data->work_type_names);
        foreach ($work_types_array as $key => $value) {
          $work_types .= "<li>".$value."</li>";
        }
        $work_types.="</ul>";
        $json_data['subwork_types'] = $work_types;
      }
    }elseif($bill_type=='purchase_bill'){
      $data['p.purchase_id'] = $_POST['bill_id'];
      $bill_data = $this->Purchases->select_purchase("p.*,u.user_alias,s.supplier_id,s.supplier_name,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id",$data,'all','','','all');
      if($bill_data->num_rows()==1){
        $bill_data = $bill_data->row();
        $json_data['count'] = 1;
        if($bill_data->location_type=='work_site'){
          $location_name = $bill_data->location_name . ' [Work Site]';
        }elseif($bill_data->location_type=='ware_house'){
          $location_name = $bill_data->location_name . ' [Warehouse]';
        }
        $json_data['bill_id'] = "#".$bill_data->purchase_id;
        $json_data['bill_no'] = $bill_data->bill_invoice_no;
        $json_data['bill_date'] = date('d-m-Y',strtotime($bill_data->purchase_date));
        $json_data['bill_total_amount'] = number_format($bill_data->bill_payable_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['bill_total_paid'] = number_format($bill_data->total_paid,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['bill_balance_amount'] = number_format($bill_data->balance_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['supplier'] = $bill_data->supplier_name;
        $json_data['location'] = $location_name;
      }
    }elseif($bill_type=='purchase_order'){
      $data['po.order_id'] = $_POST['bill_id'];
      $bill_data = $this->Purchase_order->select_purchase_order("po.*,u.user_alias,s.supplier_id,s.supplier_name,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id",$data,'all');
      if($bill_data->num_rows()==1){
        $bill_data = $bill_data->row();
        $json_data['count'] = 1;
        if($bill_data->location_type=='work_site'){
          $location_name = $bill_data->location_name . ' [Work Site]';
        }elseif($bill_data->location_type=='ware_house'){
          $location_name = $bill_data->location_name . ' [Warehouse]';
        }
        $json_data['bill_id'] = "#".$bill_data->order_id;
        $json_data['bill_no'] = $bill_data->reference_no;
        $json_data['bill_date'] = date('d-m-Y',strtotime($bill_data->order_date));
        $json_data['bill_total_amount'] = number_format($bill_data->total_est_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['bill_total_paid'] = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $bill_data->order_id, "ats.reference_type" => 'purchase_order'),'purchase_order','','','',1,'all')->row()->total_paid_amount;
        $json_data['bill_balance_amount'] = "";
        $json_data['supplier'] = $bill_data->supplier_name;
        $json_data['location'] = $location_name;
      }
    }elseif($bill_type=='labour' || $bill_type=='labour_insurance_fd'){
      $data['l.labour_id'] = $_POST['bill_id'];
      $bill_data = $this->Labour->select_labours("l.*,wt.type_name,u.user_alias",$data);
      if($bill_data->num_rows()==1){
        $bill_data = $bill_data->row();
        $json_data['count'] = 1;
        $json_data['bill_id'] = '';
        $json_data['bill_no'] = '';
        $json_data['bill_date'] = '';
        $json_data['bill_total_amount'] = '';
        $json_data['bill_total_paid'] = '';
        $json_data['bill_balance_amount'] = "";
        $json_data['labour'] = $bill_data->labour_name;
        $json_data['work_type'] = $bill_data->type_name;
      }
    }elseif($bill_type=='salary_slip'){
      $data['ss.salary_id'] = $_POST['bill_id'];
      $bill_data = $this->Salary_slips->select_salary_slips("ss.*,e.employee_name,e.user_designation",$data,'','','','','','all');
      if($bill_data->num_rows()==1){
        $bill_data = $bill_data->row();
        $json_data['count'] = 1;
        $json_data['bill_id'] = "#".$bill_data->salary_id;
        $json_data['bill_no'] = date('M Y',strtotime($bill_data->month));
        $json_data['bill_date'] = $bill_data->salary_id;
        $json_data['bill_total_amount'] = number_format($bill_data->net_salary_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['bill_total_paid'] = number_format($bill_data->total_paid_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['bill_balance_amount'] = number_format($bill_data->total_balance_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['employee'] = $bill_data->employee_name;
        $json_data['designation'] = $bill_data->user_designation;
      }
    }elseif($bill_type=='employee'){
      $data['employee_id'] = $_POST['bill_id'];
      $bill_data = $this->Employee->select_employee("e.*",$data);
      if($bill_data->num_rows()==1){
        $bill_data = $bill_data->row();
        $json_data['count'] = 1;
        $json_data['bill_id'] = '';
        $json_data['bill_no'] = '';
        $json_data['bill_date'] = '';
        $json_data['bill_total_amount'] = '';
        $json_data['bill_total_paid'] = '';
        $json_data['bill_balance_amount'] = "";
        $json_data['employee'] = $bill_data->employee_name;
        $json_data['designation'] = $bill_data->user_designation;
      }
    }elseif($bill_type=='vehicle_work_slip'){
      $data['vws.work_slip_id'] = $_POST['bill_id'];
      $bill_data = $this->Vehicle_work_slips->select_vehicle_work_slips("*",$data,'','','','','','all');
      if($bill_data->num_rows()==1){
        $bill_data = $bill_data->row();
        $json_data['count'] = 1;
        $json_data['work_slip_id'] = "#".$bill_data->work_slip_id;
        $json_data['work_id'] = $bill_data->work_id;
        $json_data['worked_date'] = date('d-m-Y',strtotime($bill_data->worked_date));
        $json_data['total_payable_amount'] = number_format($bill_data->total_payable_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['total_paid'] = number_format($bill_data->total_paid,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['balance'] = number_format($bill_data->balance,$this->config->item('Currency_amount_decimals_2'),'.','');
        $json_data['vehicle_name'] = $bill_data->vehicle_name;
        $json_data['vehicle_id'] = $bill_data->id;
        $json_data['vehicle_no'] = $bill_data->vehicle_no;
        $json_data['consignee_name'] = $bill_data->consignee_name;
        $json_data['vehicle_no'] = $bill_data->vehicle_no;
        $json_data['vehicle_name'] = $bill_data->vehicle_name;
      }
    }elseif($bill_type=='user_payment_receipt' || $bill_type=='user_payment_return'){
      $data['ah.acc_head_id'] = $_POST['bill_id'];
      $bill_data = $this->Account->select_account_heads("",$data,'user');
      if($bill_data->num_rows()==1){
        $bill_data = $bill_data->row();
        $json_data['count'] = 1;
        $json_data['bill_id'] = '';
        $json_data['bill_no'] = '';
        $json_data['bill_date'] = '';
        $json_data['bill_total_amount'] = '';
        $json_data['bill_total_paid'] = '';
        $json_data['bill_balance_amount'] = "";
        $json_data['user'] = $bill_data->acc_head_name;
        $json_data['role'] = $bill_data->department_name;
      }
    }elseif($bill_type=='loan'){
      $data['loan_id'] = $_POST['bill_id'];
      $bill_data = $this->Loan->select_loan("l.*,u.user_alias as created_user,ah1.acc_head_name,wc.work_name,lp.loan_provider_name",$data);
      if($bill_data->num_rows()==1){
        $bill_data = $bill_data->row();
        $json_data['count'] = 1;
        $json_data['bill_id'] = '';
        $json_data['bill_no'] = '';
        $json_data['bill_date'] = '';
        $json_data['bill_total_amount'] = '';
        $json_data['bill_total_paid'] = '';
        $json_data['bill_balance_amount'] = "";
        $json_data['loan_title'] = $bill_data->loan_title;
        $json_data['provider'] = $bill_data->loan_provider_name;
      }
    }elseif($bill_type=='tool_rent' || $bill_type=='tool_transfer'){
      if($bill_type=='tool_rent'){
        $data['id'] = $_POST['bill_id'];
        $bill_data = $this->Tools->select_tool_rent("t.*,tc.cat_name",$data);
      }else{
        $data['transfer_id'] = $_POST['bill_id'];
        $bill_data = $this->Tools->select_tool_transfers("t.*,tc.cat_name",$data);
      }
      if($bill_data->num_rows()==1){
        $bill_data = $bill_data->row();
        $json_data['count'] = 1;
        $json_data['bill_id'] = '';
        $json_data['bill_no'] = '';
        $json_data['bill_date'] = '';
        $json_data['bill_total_amount'] = '';
        $json_data['bill_total_paid'] = '';
        $json_data['bill_balance_amount'] = "";
        $json_data['name'] = $bill_data->name;
        $json_data['cat'] = $bill_data->cat_name;
      }
    }elseif($bill_type=='vehicle_opbalance' || $bill_type=='vehicle_renewal'){
      $data['v.id'] = $_POST['bill_id'];
      $bill_data = $this->Vehicle->select_vehicle("v.*,vc.consignee_name",$data);
      if($bill_data->num_rows()==1){
        $bill_data = $bill_data->row();
        $json_data['count'] = 1;
        $json_data['bill_id'] = '';
        $json_data['bill_no'] = '';
        $json_data['bill_date'] = '';
        $json_data['bill_total_amount'] = '';
        $json_data['bill_total_paid'] = '';
        $json_data['bill_balance_amount'] = "";
        $json_data['name'] = $bill_data->vehicle_name;
        $json_data['vehicle_no'] = $bill_data->vehicle_no;
        $json_data['vehicle_name'] = $bill_data->vehicle_name;
        $json_data['consignee_name'] = $bill_data->consignee_name;
      }
    }
    echo json_encode($json_data);
  }
  public function get_profile(){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $profile_data="";
    $data=array();
    if(isset($_POST['bill_id']) && $_POST['bill_id']!='' && $_POST['bill_id']!='all'){
      $data['b.bill_id'] = $_POST['bill_id'];
    }
    $result	= $this->Bills->select_bills("b.*,ah1.acc_head_name as credit_account,u.user_alias,wc.work_name as expense_work_name,wc2.work_name as subcontract_work_name,sc.contractor,c.contractor_name,sc.sub_work_name,sc.contract_id,sc.contract_type",$data,'','','',$this->config->item('select_data_entry_approval'),$this->config->item('select_data_entry_approval'));
    if($result->num_rows()==1){
      $row = $result->row();

      $bill_type = '<button style="color: #111 !important" type="button" class="btn m-btn--pill m-btn--air btn-outline-warning m-btn m-btn--outline-2x">'.ucwords($row->bill_type).' Bill</button>';

      if($row->work_id!=0){
        $expense_type="<span style='font-size: 1rem;' class='m-badge m-badge--focus m-badge--wide'><i class='fa fa-tag'></i> Work Expense</span>";
      }else{
        $expense_type="<span style='font-size: 1rem;' class='m-badge m-badge--info m-badge--wide'><i class='fa fa-tag'></i> Office Expense</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 class="btn m-btn--gradient-from-info m-btn--gradient-to-focus  m-btn  m-btn--icon m-btn--air m-btn--pill" target="_blank" href="'.$bill_attachment_url.'">View Attachment</a>';
      }
      // $no_of_bills=$this->Bills->select_bills("b.bill_id",array("b.subcontract_id"=>$row->contract_id,"b.bill_type"=>'subcontract'))->num_rows();
      $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_bill_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> Bill Overview
      </a>
      </li>
      <li class="nav-item m-tabs__item">
      <a class="nav-link m-tabs__link quick_sidebar_tab_bill_profile_transactions quick_sidebar_tabs" data-table-no="bill_table1" data-toggle="tab" href="#m_tabs_6_2" role="tab" aria-selected="false">
      <i class="fa fa-clipboard-list"></i> Transactions
      </a>
      </li>
      </ul>
      </div>
      </div>
      <div class="m-portlet__body">
      <div class="tab-content">
      <div class="tab-pane active show quick_sidebar_tab_bill_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">Bill Details</h3>
      <div class="row" >
      <div class="col-lg-3" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Bill ID
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input type="text" readonly value="#'.$row->bill_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-3" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Bill Type
      </label>
      <div class="m-input-icon m-input-icon--right">
      '.$bill_type.'
      </div>
      </div>
      </div>
      <div class="col-lg-3">
      <div class="form-group m-form__group" >
      <label for="user_name">
      Bill No
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input  readonly value="'.$row->bill_no.'"  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">
      Bill Date
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input readonly value="'.date('d-m-Y',strtotime($row->bill_date)).'" 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-calendar"></i></span></span>
      </div>
      </div>
      </div>
      </div>
      <div class="row">';
      if($row->bill_type=='expense'){
        $profile_data.='<div class="col-lg-4" >
        <div class="form-group m-form__group" >
        <label for="user_name">
        Expense Type
        </label>
        <div class="m-input-icon m-input-icon--right">
        '.$expense_type.'
        </div>
        </div>
        </div>
        <div class="col-lg-4" >
        <div class="form-group m-form__group" >
        <label for="user_name">
        Expense Head
        </label>
        <div class="m-input-icon m-input-icon--right">
        <input readonly value="'.$row->credit_account.'" 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>';
        if($row->work_id!=0){
          $profile_data.='<div class="col-lg-4" >
          <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->expense_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>';
        }
      }elseif($row->bill_type=='subcontract'){
        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>";
        }
        $profile_data.='<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" 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">
        Contractor
        </label>
        <div class="m-input-icon m-input-icon--right">
        <input readonly value="'.$row->contractor_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-4" >
        <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->subcontract_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>';
      }

      $profile_data.='<div class="col-lg-4">
      <div class="form-group m-form__group">
      <label for="user_name">
      Consignee
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input readonly value="'.$row->bill_consignee_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-user"></i></span></span>
      </div>
      </div>
      </div>
      <div class="col-lg-4">
      <div class="form-group m-form__group">
      <label for="user_name">
      Bill Description
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input readonly value="'.$row->bill_description.'" 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-edit"></i></span></span>
      </div>
      </div>
      </div>
      <div class="col-lg-4" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Bill Remarks
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input readonly value="'.$row->bill_remarks.'" 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>';
      if($row->bill_type=='subcontract'){
        $profile_data.='<div class="col-lg-4" >
        <div class="form-group m-form__group" >
        <label for="user_name">
        No of Labours Worked
        </label>
        <div class="m-input-icon m-input-icon--right">
        <input readonly value="'.$row->subcontract_labours_no.'" 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-users"></i></span></span>
        </div>
        </div>
        </div>';
      }
      $profile_data.='</div>';
      if($row->bill_attachment!=''){
        $profile_data.='<div class="row">
        <div class="col-lg-8"></div>
        <div class="col-lg-4">
        <div class="form-group m-form__group">
        <label for="user_name">
        Attachment
        </label>
        <div class="m-input-icon m-input-icon--right">
        '.$bill_attachment_btn.'
        </div>
        </div>
        </div>
        </div>';
      }
      $profile_data.='</div>
      </div>';
$bill_items	= $this->Bills->select_bill_items("",array("bill_id"=>$row->bill_id))->result();
      if($row->bill_type=='expense' && sizeof($bill_items)>0){
        // $bill_items = unserialize($row->bill_items);
        $profile_data.='<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">Bill Items</h3>
        <div class="row"><table class="table table-striped m-table m-table--head-bg-brand">
        <thead>
        <tr>
        <th>Sl No</th>
        <th>Item Name</th>
        <th>Qty</th>
        <th>Unit</th>
        <th>Rate</th>
        <th>Total Amount</th>
        </tr>
        </thead>
        <tbody>';
        $item_slno=0;
        foreach ($bill_items as $key2 => $value2) {
          $item_slno++;
          $profile_data.='<tr>
          <td>'.$item_slno.'</td>
          <td>'.$value2->item_description.'</td>
          <td>'.$value2->total_qty.'</td>
          <td>'.$value2->unit.'</td>
          <td>'.$value2->unit_rate.'</td>
          <td>'.$value2->total_amount.'</td>
          <td>'.$value2->item_remarks.'</td>
          </tr>';
        }
        $profile_data.='</tbody></table></div>
        </div>
        </div>';
      }
      if($row->bill_type=='subcontract' && $this->config->item('Subcontract_bill_type')=='work_items_based' && $row->bill_items!=''){
        $bill_items = unserialize($row->bill_items);
        $profile_data.='<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 Details</h3>
        <div class="row"><table class="table table-striped m-table m-table--head-bg-brand">
        <thead>
        <tr>
        <th>Sl No</th>
        <th>Work Type</th>
        <th>Unit Rate</th>
        <th>Unit</th>
        <th>Acheived Qty</th>
        <th>Total Amount</th>
        </tr>
        </thead>
        <tbody>';
        $item_slno=0;
        foreach ($bill_items as $key2 => $value2) {
          if($value2['item_type']=='subcontract_work_item'){
            $item_data = $this->Subcontracts->select_subcontract_work_items("scwi.*,wt.type_name,mu.unit_name,sc.contract_type", array("scwi.item_id" => $value2['item_id']));
            if($item_data->num_rows()==1){
              $item_data = $item_data->row();
              $item_slno++;
              if($item_data->contract_type=='unit_rate'){
                $unit_rate = $item_data->unit_rate;
              }else{
                $unit_rate = $value2['unit_rate'];
              }
              $profile_data.='<tr>
              <td>'.$item_slno.'</td>
              <td>'.$item_data->type_name.'</td>
              <td>'.$unit_rate.'</td>
              <td>'.$item_data->unit_name.'</td>
              <td>'.$value2['qty'].'</td>
              <td>'.round($value2['qty']*$unit_rate,$this->config->item('Currency_amount_decimals_2')).'</td>
              </tr>';
            }
          }
        }
        $profile_data.='</tbody></table></div>
        </div>
        </div>';
      }
      if($row->bill_type=='subcontract' && $this->config->item('Subcontract_labours')==1){
        $labour_wages = $this->Subcontracts->select_subcontract_labour_wage("slw.*,sl.labour_name,sl.skill_type,wt.type_name", array("slw.bill_id" => $row->bill_id))->result();
        $profile_data.='<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">Labour Details</h3>
        <div class="row"><table class="table table-striped m-table m-table--head-bg-brand">
        <thead>
        <tr>
        <th>Sl No</th>
        <th>Labour Name</th>
        <th>Skill Type</th>
        <th>No of Days</th>
        </tr>
        </thead>
        <tbody>';
        $item_slno=0;
        foreach ($labour_wages as $key2 => $value2) {
          $item_slno++;
          $profile_data.='<tr>
          <td>'.$item_slno.'</td>
          <td>'.$value2->labour_name.'</td>
          <td>'.$value2->skill_type.'</td>
          <td>'.$value2->no_of_days.'</td>
          </tr>';
        }
        $profile_data.='</tbody></table></div>
        </div>
        </div>';
      }
      if($row->bill_type=='subcontract' && $this->config->item('Subcontract_bill_template')==2){
        $bill_items	= $this->Bills->select_bill_items("",array("bill_id"=>$row->bill_id))->result();
        $profile_data.='<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 Item Details</h3>
        <div class="row"><table class="table table-striped m-table m-table--head-bg-brand">
        <thead>
        <tr>
        <th>Sl No</th>';
        if($row->subcontract_bill_type==1){
          $profile_data.='<th>Work Description</th>';
          $profile_data.='<th>Total Qty</th>';
          $profile_data.='<th>Unit</th>';
        }elseif($row->subcontract_bill_type==2){
          $profile_data.='<th>Work Description</th>';
          $profile_data.='<th>Total Len</th>';
          $profile_data.='<th>Road Cutting</th>';
        }else{
          $profile_data.='<th>Work Description</th>';
          $profile_data.='<th>Total Qty</th>';
          $profile_data.='<th>Unit</th>';
        }
        $profile_data.='<th>Rate</th>
        <th>Total Amount</th>
        <th>Remarks</th>
        </tr>
        </thead>
        <tbody>';
        $item_slno=0;
        foreach ($bill_items as $key2 => $value2) {
          $item_slno++;
          $profile_data.='<tr>
          <td>'.$item_slno.'</td>
          <td>'.$value2->item_description.'</td>
          <td>'.$value2->total_qty.'</td>
          <td>'.$value2->unit.'</td>
          <td>'.$value2->unit_rate.'</td>
          <td>'.$value2->total_amount.'</td>
          <td>'.$value2->item_remarks.'</td>
          </tr>';
        }
        $profile_data.='</tbody></table></div>
        </div>
        </div>';
      }
      $profile_data.='<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">Amount Details</h3>
      <div class="row" >
      <div class="col-lg-3" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Gross Amount
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input type="text" readonly value="'.$this->config->item('currency_format')->formatCurrency($row->bill_gross_amount,$this->config->item('Currency_currency_shortname')).'"  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">
      Discount Amount
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input  readonly value="'.$this->config->item('currency_format')->formatCurrency($row->bill_discount_amount,$this->config->item('Currency_currency_shortname')).'"  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>'.$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">
      Tax Amount
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input  readonly value="'.$this->config->item('currency_format')->formatCurrency($row->bill_tax_amount,$this->config->item('Currency_currency_shortname')).'"  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>'.$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">
      TDS Amount
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input  readonly value="'.$this->config->item('currency_format')->formatCurrency($row->bill_tds_amount,$this->config->item('Currency_currency_shortname')).'"  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>'.$this->config->item('Currency_currency_format').'</span></span>
      </div>
      </div>
      </div>
      </div>
      <div class="row">
      <div class="col-lg-4" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Other Deductions
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input readonly value="'.$this->config->item('currency_format')->formatCurrency($row->other_deductions,$this->config->item('Currency_currency_shortname')).'" 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-4" >
      <div class="form-group m-form__group" >
      <label for="user_name">
      Payable Amount
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input readonly value="'.$this->config->item('currency_format')->formatCurrency($row->bill_payable_amount,$this->config->item('Currency_currency_shortname')).'" 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-4">
      <div class="form-group m-form__group">
      <label for="user_name">
      Total Paid
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input readonly value="'.$this->config->item('currency_format')->formatCurrency($row->bill_total_paid,$this->config->item('Currency_currency_shortname')).'" 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-8" ></div>
      <div class="col-lg-4">
      <div class="form-group m-form__group">
      <label for="user_name">
      Balance
      </label>
      <div class="m-input-icon m-input-icon--right">
      <input readonly value="'.$this->config->item('currency_format')->formatCurrency($row->bill_balance_amount,$this->config->item('Currency_currency_shortname')).'" 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>
      </div>
      </div>
      <div class="tab-pane quick_sidebar_tab_bill_profile_transactions" 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="bill_transactions_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
  }
}
?>
