<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Production 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('Stock_model', 'Stock');
    $this->load->model('Material_model', 'Material');
    $this->load->model('Purchase_bill_model', 'Purchases');
    $this->load->model('Subcontracts_model', 'Subcontracts');
    $this->load->model('Production_model', 'Production');
    $this->load->library('Stock_management', 'stock_management');
    $this->load->model('Account_model', 'Account');
    $this->load->library('Boq_management', 'boq_management');
    $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");
    if ($this->User->is_logged_in($allowed_user_roles) == false) {
      redirect(base_url(), 'refresh');
    }
    //        File Directory
    $this->page_data['directory'] = "production";
  }
  public function index()
  {
    $this->view();
  }

  public function view()
  {

    // Check Module is Enabled or Not
    if ($this->config->item('app_module_production') == 0) {
      redirect(base_url() . 'dashboard', 'refresh');
    }

    if ($this->session->userdata('user_role') == 'supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    }


    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations("", array('sl.work_id' => '0'))->result();

    if ($this->session->userdata('user_role') == 'supervisor') {
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    $this->page_data['materials'] = $this->Material->select_material()->result();

    $this->page_data['page_name'] = 'production_view';
    $this->load->view('Index', $this->page_data);
  }
  public function add()
  {
    // Check Module is Enabled or Not
    if ($this->config->item('app_module_production') == 0) {
      redirect(base_url() . 'dashboard', 'refresh');
    }
    $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("", array('sl.work_id' => '0'))->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();

    $this->page_data['page_name'] = 'production_add';
    $this->load->view('Index', $this->page_data);
  }
  public function damages()
  {
    // Check Module is Enabled or Not
    if ($this->config->item('app_module_stock_management') == 0) {
      redirect(base_url() . 'dashboard', 'refresh');
    }

    if ($this->session->userdata('user_role') == 'supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, wc.assigned_users)");
    }
    $this->page_data['stock_locations'] = $this->Stock->select_stock_locations('',array("location_type"=>'ware_house'))->result();

    if ($this->session->userdata('user_role') == 'supervisor') {
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    $this->page_data['materials'] = $this->Material->select_material()->result();
    $this->page_data['material_categories'] = $this->Material->select_category("")->result();

    $this->page_data['page_name'] = 'stock_damages';
    $this->load->view('Index', $this->page_data);
  }
  public function create_production()
  {
    $production_data['location_id'] = $this->security->xss_clean($this->input->post('location'));
    $production_data['date'] = date('Y-m-d',strtotime($this->security->xss_clean($this->input->post('production_date'))));
    $production_data['material_id'] = $this->security->xss_clean($this->input->post('product_material'));
    $production_data['production_qty'] = $this->security->xss_clean($this->input->post('production_qty'));
    $production_data['steg_used'] = $this->security->xss_clean($this->input->post('steg'));
    $production_data['created_date'] = date('Y-m-d H:i:s');
    $production_data['created_by'] = $this->session->userdata('user_id');
    $production_data['remarks'] = $this->security->xss_clean($this->input->post('remarks'));

    $material_data = $this->Material->select_material("",array("material_id"=>$production_data['material_id']))->row();
    // Insert Product as New Stock Entry
    $stock_data['location_id'] = $production_data['location_id'];
    $stock_data['stock_name'] = $material_data->material_name;
    $stock_data['material_id'] = $production_data['material_id'];
    $stock_data['unit'] = $material_data->unit;
    $stock_data['total_production_qty'] = $production_data['production_qty'];
    $stock_data['created_date'] = date('Y-m-d H:i:s');
    $stock_data['created_by'] = $this->session->userdata('user_id');
    $result3 = $this->Stock->insert_stock_register($stock_data);

    if($result3['status']==1){
      $production_data['stock_id'] = $result3['insert_id'];
      $production_result = $this->Production->insert_production($production_data);

      if($production_result['status']==1){
        $data['production_id']  = $production_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'];
          $data['average_qty'] = $row['average_used'];

          $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_transferred_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" => $production_data['location_id'], "sr.material_id" => $data2['material_id'], "sr.unit" => $data2['unit_id'],  "sr.total_balance_qty >" => 0));
          }else{
            $stock_register = $this->Stock->select_stock_register("sr.*", array("sr.location_id" => $production_data['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));
          }
          $remaining_qty = $total_stock_transferred_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['used_qty']  = $available_stock_item_qty;
              } else {
                $data['used_qty']  = $remaining_qty;
              }
              $remaining_qty = $remaining_qty - $data['used_qty'];
              $data['used_stock_id'] = $value->stock_id;

              $result = $this->Production->insert_production_materials_used($data);
              // Insert to consumption
              $consumption_data['consumption_qty']  = $data['used_qty'];
              $consumption_data['stock_id'] = $data['used_stock_id'];
              $consumption_data['production_used_id'] = $result['insert_id'];
              $consumption_data['created_date'] = date('Y-m-d H:i:s');
              $consumption_data['created_by'] = $this->session->userdata('user_id');
              $consumption_data['consumption_date'] = $production_data['date'];
              $stock_cons_data = $this->Stock->select_stock_consumption("MAX(cons_group_id) as last_group_id");
              if ($stock_cons_data->num_rows() == 1) {
                $consumption_data['cons_group_id'] = ($stock_cons_data->row()->last_group_id) + 1;
              } else {
                $consumption_data['cons_group_id'] = 1;
              }
              $consumption_result = $this->Stock->insert_stock_consumption($consumption_data);

              //  Update Stock Register
              $this->stock_management->calculate_stock_balance($data['used_stock_id']);
            }
          }
        }
        if (isset($result) && $result['status'] == 1) {

          $this->stock_management->calculate_stock_balance($result3['insert_id']);

          $flash_data['status'] = $result['status'];
          $flash_data['flashdata_msg'] = 'Production Entry 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 !!';
      }
    }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_production($page_data_type = "")
  {

    $json_data = array();
    $j = 0;
    $sl_no = 0;
    $data = $array = array();
    if (isset($_POST['location']) && $_POST['location'] != '' && $_POST['location'] != 'all') {
      $data['sr.location_id'] = $_POST['location'];
    }
    if (isset($_POST['material_id']) && $_POST['material_id'] != '' && $_POST['material_id'] != 'all') {
      $data['p.material_id'] = $_POST['material_id'];
    }
    if (isset($_POST['material_category']) && $_POST['material_category'] != '' && $_POST['material_category'] != 'all') {
      $data['m.category'] = $_POST['material_category'];
    }
    if (isset($_POST['user_id']) && $_POST['user_id'] != '' && $_POST['user_id'] != 'all') {
      $data['p.created_by'] = $_POST['user_id'];
    }
    if ($this->config->item('user_data_access_view_all') != 1) {
      $data['p.created_by'] = $this->session->userdata('user_role');
    }
    if (isset($_POST['start_date']) && $_POST['start_date'] != '' && $_POST['start_date'] != 'all') {
      $data['p.date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if (isset($_POST['end_date']) && $_POST['end_date'] != '' && $_POST['end_date'] != 'all') {
      $data['p.date <='] = date('Y-m-d', strtotime($_POST['end_date']));
    }
    $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
    $production  = $this->Production->select_production("p.*,sr.unit_price,sr.material_id,m.material_name,mu.unit_name,sr.unit,sl.location_name,u.user_alias as created_user,u.user_role as created_user_role_id,sl.location_type", $data, '', $entry_approval);
    $total_amount = 0;
    foreach ($production->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>";
      //   }
      // }
      $materials_used_list = '';
      $materials_used = $this->Production->select_production_materials_used('pmu.*,m.material_name,mu.unit_name',array("pmu.production_id"=>$row->production_id))->result();
      foreach ($materials_used as $key => $value) {
        $materials_used_list .= $value->material_name." | ".$value->used_qty." ".$value->unit_name." | ".$value->average_qty." ".$value->unit_name.'<br/>';
      }

      $location_name= '<a href="' . base_url() . 'stock/locations/profile/' . $row->location_id . '">' . $row->location_name . '<br/>[Warehouse]</a>';
      $sl_no++;
      $array[$j][] = $sl_no;
      $array[$j][] = $row->production_id;
      $array[$j][] = date('d-m-Y',strtotime($row->date));
      $array[$j][] = $location_name;
      $array[$j][] = $row->material_name;
      $array[$j][] = $row->production_qty;
      $array[$j][] = $row->unit_name;
      $array[$j][] = $row->steg_used;
      $array[$j][] = $materials_used_list;
      $array[$j][] = $row->remarks;
      $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 create_damages()
  {
    $stock_slnos = $this->input->post('stock_slnos');

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

            $remaining_qty = $remaining_qty - $data['damage_qty'];

            $data['stock_id'] = $value;
            // Update Stock Consumption
            $result = $this->Stock->insert_stock_damages($data);
            //  Update Stock Register
            $result2 = $this->stock_management->calculate_stock_balance($data['stock_id']);
          }
        }
      }
    }
    if (isset($result) && $result['status'] == 1) {
      $flash_data['status'] = $result['status'];
      $flash_data['flashdata_msg'] = 'Stock Damages 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 delete_damages()
  {
    $flash_data = array();
    $flash_data['status'] = 0;
    $damage_ids = explode(',',$this->input->post('damage_ids'));
    foreach ($damage_ids as $key => $value) {
      $data['id'] = $value;
      $data['delete_status'] = 1;
      // Get Consumption Details
      $damage_data = $this->Stock->select_stock_damages('sd.*', array("sd.id"=>$data['id']),'', 'all');
      if($damage_data->num_rows()==1){
        $result = $this->Stock->update_stock_damages($data);
        $flash_data['status'] = $result;
        //  Update Stock Register
        $result2 = $this->stock_management->calculate_stock_balance($damage_data->row()->stock_id);
      }
    }
    if ($result == 1) {
      $flash_data['flashdata_msg'] = 'Damage Entry Deleted Successfully!';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    $flash_data['message'] = $flash_data['flashdata_msg'];
    echo json_encode($flash_data);
  }
  public function select_stock_damages($page_data_type = "")
  {

    $json_data = array();
    $j = 0;
    $sl_no = 0;
    $data = $array = array();
    if (isset($_POST['location_id']) && $_POST['location_id'] != '' && $_POST['location_id'] != 'all') {
      $data['sr.location_id'] = $_POST['location_id'];
    }
    if (isset($_POST['location_id']) && $_POST['location_id'] != '' && $_POST['location_id'] != 'all') {
      $data['sd.location_id'] = $_POST['location_id'];
    }

    if (isset($_POST['material_id']) && $_POST['material_id'] != '' && $_POST['material_id'] != 'all') {
      $data['sr.material_id'] = $_POST['material_id'];
    }
    if (isset($_POST['material_category']) && $_POST['material_category'] != '' && $_POST['material_category'] != 'all') {
      $data['m.category'] = $_POST['material_category'];
    }
    if (isset($_POST['user_id']) && $_POST['user_id'] != '' && $_POST['user_id'] != 'all') {
      $data['sd.created_by'] = $_POST['user_id'];
    }
    if (isset($_POST['start_date']) && $_POST['start_date'] != '' && $_POST['start_date'] != 'all') {
      $data['sd.date >='] = date('Y-m-d', strtotime($_POST['start_date']));
    }
    if (isset($_POST['end_date']) && $_POST['end_date'] != '' && $_POST['end_date'] != 'all') {
      $data['sd.date <='] = date('Y-m-d', strtotime($_POST['end_date']));
    }
    if (isset($_POST['date']) && $_POST['date'] != '') {
      $date = array();
      $date = explode('-', $_POST['date']);
      $start_date = date('Y-m-d', strtotime($date[0]));
      $end_date = date('Y-m-d', strtotime($date[1]));
      $data["STR_TO_DATE(sd.date,'%Y-%m-%d') <="] = $end_date;
      $data["STR_TO_DATE(sd.date,'%Y-%m-%d') >="] = $start_date;
    }

    $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
    $damaged_stock  = $this->Stock->select_stock_damages("GROUP_CONCAT(sd.id) AS damage_ids,COALESCE(SUM(sd.damage_qty),0) as total_damaged_qty,COALESCE(SUM(sd.damage_qty*sr.unit_price),0) as total_damaged_amt,sd.*,sr.unit_price,sr.material_id,m.material_name,mu.unit_name,sr.unit,sd.location_id,u.user_alias as created_user,sl.location_name,u.user_role as created_user_role_id", $data, array("sd.date", "sd.group_id", 'sr.material_id','sr.unit','sr.purchase_supplier_id','sr.unit_price','sr.location_id'), $entry_approval);
    $total_amount = 0;
    foreach ($damaged_stock->result() as $row) :
      if ($row->id != '') {
        $stock_amount = round($row->total_damaged_amt);
        $total_amount += $stock_amount;

        $btn_delete=$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_damages" data-approval-status="' . $row->entry_approval_status . '" data-id="' . $row->id3 . '" id="btn_data_entry_approval" href="#data_entry_approve_modal" data-toggle="modal" class="btn btn-sm btn-warning m-btn m-btn--icon  m-btn--pill m-btn--air">
          <i class="la la-check-circle"></i> / <i class="la la-times-circle"></i>
          </a>';
        }
        if(($this->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_delete='<a style="margin-left: 5px;margin-right: 5px"  id="btn_delete_damages"  href="#damages_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 ($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->id;
        $array[$j][] = date('d-m-Y', strtotime($row->date));
        $array[$j][] = $row->material_name;
        $array[$j][] = $row->unit_name;
        $array[$j][] = round($row->total_damaged_qty,2);
        $array[$j][] = $stock_amount;
        $array[$j][] = '<a href="' . base_url() . 'stock/locations/profile/' . $row->location_id . '">' . $row->location_name . '</a>';
        $array[$j][] = $row->created_user . $entry_approval_status;
        $array[$j][] = $btn_approve.$btn_delete;

        $j++;
      }

    endforeach;
    if (sizeof($array) > 0) {
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = "<strong>Grand Total</strong>";
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = "<strong>" . round($total_amount,$this->config->item('Currency_amount_decimals_2')) . "</strong>";
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
    }
    $json_data['data'] = $array;
    $json_data['draw'] = 5;
    $json_data['recordsTotal'] = sizeof($array);
    $json_data['recordsFiltered'] = sizeof($array);
    echo json_encode($json_data);  // send data as json format
  }
}
