<?php

namespace App\Models;

use CodeIgniter\Model;

class BarangUnitModel extends Model
{
    protected $table      = 'barang_unit';
    protected $primaryKey = 'id_unit';

    protected $allowedFields = [
        'id_barang',
        'kode_unit',
        'barcode',
        'sumber_dana',
        'tahun_perolehan',
        'id_ruangan',
        'kondisi',
        'status',
        'created_at'
    ];

    protected $useTimestamps = false;

    // =========================
    // Ambil unit + relasi
    // =========================
   public function getWithRelation($filters = [])
{
    $builder = $this->select('
        barang_unit.*,
        barang.nama_barang,
        kategori.nama_kategori,
        ruangan.nama_ruangan
    ')
    ->join('barang', 'barang.id_barang = barang_unit.id_barang')
    ->join('kategori', 'kategori.id_kategori = barang.id_kategori')
    ->join('ruangan', 'ruangan.id_ruangan = barang_unit.id_ruangan', 'left');

    if (!empty($filters['tahun_perolehan'])) {
        $builder->where(
            'barang_unit.tahun_perolehan',
            $filters['tahun_perolehan']
        );
    }

    if (!empty($filters['sumber_dana'])) {
        $builder->where(
            'barang_unit.sumber_dana',
            $filters['sumber_dana']
        );
    }

    return $builder->orderBy('barang_unit.id_unit', 'DESC')->findAll();
}


    // =========================
    // Unit aktif saja
    // =========================
    public function getActiveUnits()
    {
        return $this->where('status', 'Aktif')->findAll();
    }
}