<?php

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

class M_peralatan extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    function getPeralatan($is_count = false, $limit = null, $start = null, $id = null){
        $param = array();

        if($is_count)
            $query = "SELECT COUNT(p.id) AS jumlah";
        else
            $query ="SELECT p.*, u.nama as jenis_parameter";

        $query .= " FROM peralatan p
          LEFT JOIN parameter_uji u ON u.id = p.jenis_uji
        ";

        if(!$is_count)
			$query .= " ";

        $query .= " WHERE p.is_active = '1'";

		if($id){
			$param[] = $id;
			$query .= " AND p.id = ?";
		}

        $query .= " ORDER BY p.id DESC";

        if($is_count == false && !$id) {
            if (isset($limit)) {
                $query .= " LIMIT ?, ?";
                $param[] = intval($start);
                $param[] = intval($limit);
            }
        }

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

        if($is_count){
			return $result->row_array()['jumlah'];
		} else {
			if($id != null)
				return $result->row_array();
			else
				return $result->result_array();
		}
    }

    function get_alat_by_id($id)
    {
        $this->db->select('p.*');
        $query = $this->db->get_where('peralatan p', ['id'=>$id]);
        $result = $query->row_array();
        return $result;
    }

	function createEdit($data, $id_alat = null){
		$this->db->trans_begin();

		if(!isset($id_alat) || $id_alat === ''){
		$this->db->query("INSERT INTO peralatan(nama_alat, jenis_alat, jenis_uji, keterangan, kategori, last_modified_user) VALUES
			(?,?,?,?,?,?)
		", $data);
		}else{
			$data[] = $id_alat;
			$this->db->query("UPDATE peralatan SET nama_alat = ?, jenis_alat = ?, jenis_uji = ?, keterangan = ?, kategori = ?, last_modified_user = ? WHERE id = ?", $data);
		}

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

    function get_param_uji_by_in($id_in, $kategori = '')
    {
        $this->db->where_in('id', $id_in);
        if($kategori != ''){
            $this->db->where('kategori', $kategori);
        }
        $query = $this->db->get('parameter_uji');
        $result = $query->result_array();
        return $result;
    }

	function hapusAlat($id_alat){
		$this->db->trans_begin();

		$this->db->query("UPDATE peralatan SET is_active = '0' WHERE id = ?
		", $id_alat);

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