<?php

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

class M_bahan_habis_pakai extends CI_Model {

    protected $idGroup = null;
    protected $iduser = null;

    public function __construct() {
        parent::__construct();
        $this->idGroup = $this->session->userdata("r_idGroup");
        $this->idUser = $userId = $this->session->userdata('r_userId');
    }

    function set_data($data, $data_keys, $id = null){
      $this->db->trans_begin();

      $param = array();
      for($i=0;$i<count($data_keys);$i++){
          $param[] = $data[$data_keys[$i]];
      }

      if(is_null($id)){
        $param_keys = "(".$data_keys[0];
        $keys = "(?";
        for($i=1;$i<count($data_keys);$i++){
          $param_keys .= ", ".$data_keys[$i];
          $keys .= ",?";
        }
        $keys .=")";
        $param_keys .= ")";

        $query = "INSERT INTO bahan_habis_pakai ".$param_keys." VALUES ". $keys;
      }else{
        if(in_array($this->idGroup, array('1', '3'))){
          $this->jumlah_pengambilan($data, $id);
        }

        $param_keys = "SET ".$data_keys[0].'=?';
        for($i=1;$i<count($data_keys);$i++){
          $param_keys .= ", ".$data_keys[$i].'=?';
        }

        $query = "UPDATE bahan_habis_pakai ".$param_keys. " WHERE id_bahan = ? AND is_active = '1'";
        $param[] = $id;

        if(!empty($data['is_active']) && $data['is_active'] == '0'){
          $this->db->query("UPDATE pengambilan_bahan SET is_active = '0' WHERE id_bahan = ?", $id);
        }
      }
      $this->db->query($query, $param);

      if($this->db->trans_status() == false){
        $this->db->trans_rollback();
        return false;
      }else{
        $this->db->trans_commit();
        return true;
      }
    }

    function total_pengambilan($id){
      $result =  $this->db->query("SELECT SUM(jumlah_pengambilan) as total FROM pengambilan_bahan WHERE id_bahan = ?", $id)->row_array()['total'];

      return $result;
    }

    function jumlah_pengambilan($data, $id) {
      $param = array();
      $param[] = $id;
      $param[] = empty($data['jumlah_pengambilan']) || is_null($data['jumlah_pengambilan']) ? 0:$data['jumlah_pengambilan'];
      $param[] = $data['last_modified_user'];

      return $this->db->query("INSERT INTO pengambilan_bahan (id_bahan, jumlah_pengambilan, last_modified_user) VALUES (?,?,?)", $param);
    }

    function get_data(){
      $param = array();
      $query = "SELECT bhp.* FROM bahan_habis_pakai bhp WHERE bhp.is_active = '1'";

      $result = $this->db->query($query, $param)->result_array();

      return $result;
    }

    function get_detail($id){
      $param = array();
      $param[] = $id;
      $query = "SELECT bhp.* FROM bahan_habis_pakai bhp WHERE bhp.is_active = '1' AND id_bahan = ?";

      $result = $this->db->query($query, $param)->row_array();

      return $result;
    }
  }
