<?php

namespace App\Controllers\Api;

use App\Models\BarangModel;

class BarangController extends BaseApiController
{
    protected $barang;

    public function __construct()
    {
        $this->barang = new BarangModel();
    }

  public function index()
{
    $model = new BarangModel();

    $data = $model->getWithRelation();

    return $this->respondSuccess(
        $data,
        'Data barang'
    );
}

    public function show($id)
    {
        $data = $this->barang->find($id);

        if (!$data) {
            return $this->respondError('Barang tidak ditemukan', 404);
        }

        return $this->respondSuccess($data, 'Detail barang');
    }

    public function store()
    {
        $input = $this->getJsonInput();

        if (!$this->barang->insert($input)) {
            return $this->respondError(
                'Gagal menyimpan barang',
                400,
                $this->barang->errors()
            );
        }

        return $this->respondSuccess(null, 'Barang berhasil disimpan', 201);
    }

public function update($id)
{
    $model = new BarangModel();
    $data = $this->request->getJSON(true);

    // 🔥 pastikan kondisi ikut terbaca
    if (!isset($data['kondisi'])) {
        return $this->respondError('Kondisi wajib diisi', 422);
    }

    $model->update($id, [
        'kode_barang'   => $data['kode_barang'] ?? null,
        'nama_barang'   => $data['nama_barang'] ?? null,
        'id_kategori'   => $data['id_kategori'] ?? null,
        'kondisi'       => $data['kondisi'], // 🔥 FIX
    ]);

    return $this->respondSuccess(null, 'Barang berhasil diperbarui');
}


    public function delete($id)
    {
        if (!$this->barang->delete($id)) {
            return $this->respondError('Gagal menghapus barang');
        }

        return $this->respondSuccess(null, 'Barang berhasil dihapus');
    }
}