<?php

namespace App\Controllers;

use App\Models\RuanganModel;
use App\Models\SumberDanaModel;
use App\Models\JenisBarangModel;
use App\Models\KibKategoriModel;
use App\Models\KibDetailModel;

class MasterData extends BaseController
{
    protected $ruanganModel;
    protected $sumberDanaModel;
    protected $jenisBarangModel;
    protected $kibKategoriModel;
    protected $kibDetailModel;

    public function __construct()
    {
        $this->ruanganModel    = new RuanganModel();
        $this->sumberDanaModel = new SumberDanaModel();
        $this->jenisBarangModel = new JenisBarangModel();
        $this->kibKategoriModel = new KibKategoriModel();
        $this->kibDetailModel   = new KibDetailModel();
    }

    // --- RUANGAN ---
    public function ruangan()
    {
        $data = [
            'title'   => 'Data Ruangan',
            'ruangan' => $this->ruanganModel->findAll()
        ];
        return view('master/ruangan', $data);
    }

    public function simpanRuangan()
    {
        $id   = $this->request->getPost('id');
        $data = ['nama_ruangan' => $this->request->getPost('nama_ruangan')];
        if ($id) $this->ruanganModel->update($id, $data);
        else $this->ruanganModel->insert($data);
        return redirect()->to('/master/ruangan');
    }

    public function hapusRuangan($id)
    {
        $this->ruanganModel->delete($id);
        return redirect()->to('/master/ruangan');
    }

    // --- SUMBER DANA ---
    public function sumberDana()
    {
        $data = [
            'title'  => 'Data Sumber Dana',
            'sumber' => $this->sumberDanaModel->findAll()
        ];
        return view('master/sumber_dana', $data);
    }

    public function simpanSumberDana()
    {
        $id   = $this->request->getPost('id');
        $data = ['nama_sumber' => $this->request->getPost('nama_sumber')];
        if ($id) $this->sumberDanaModel->update($id, $data);
        else $this->sumberDanaModel->insert($data);
        return redirect()->to('/master/sumber-dana');
    }

    public function hapusSumberDana($id)
    {
        $this->sumberDanaModel->delete($id);
        return redirect()->to('/master/sumber-dana');
    }

    // --- JENIS BARANG ---
    public function jenisBarang()
    {
        $data = [
            'title' => 'Data Jenis Barang',
            'jenis' => $this->jenisBarangModel->findAll()
        ];
        return view('master/jenis_barang', $data);
    }

    public function simpanJenisBarang()
    {
        $id   = $this->request->getPost('id');
        $data = ['nama_jenis' => $this->request->getPost('nama_jenis')];
        if ($id) $this->jenisBarangModel->update($id, $data);
        else $this->jenisBarangModel->insert($data);
        return redirect()->to('/master/jenis-barang');
    }

    public function hapusJenisBarang($id)
    {
        $this->jenisBarangModel->delete($id);
        return redirect()->to('/master/jenis-barang');
    }

    // --- KODE BARANG (KIB) ---
    public function kodeBarang()
    {
        $db = \Config\Database::connect();
        $builder = $db->table('kib_kategori');
        $builder->select('kib_kategori.*, COUNT(kib_detail.id) as jumlah_item');
        $builder->join('kib_detail', 'kib_detail.id_kib_kategori = kib_kategori.id', 'left');
        $builder->groupBy('kib_kategori.id');
        $builder->orderBy('kib_kategori.id', 'ASC');

        $data = [
            'title'   => 'Kode Barang (KIB)',
            'kibList' => $builder->get()->getResultArray(),
        ];
        return view('master/kode_barang', $data);
    }

    public function simpanKib()
    {
        $id   = $this->request->getPost('id');
        $data = [
            'nama_kib'   => $this->request->getPost('nama_kib'),
            'kode_brg'   => $this->request->getPost('kode_brg'),
            'keterangan' => $this->request->getPost('keterangan'),
        ];
        if ($id) $this->kibKategoriModel->update($id, $data);
        else $this->kibKategoriModel->insert($data);
        return redirect()->to('/master/kode-barang');
    }

    public function hapusKib($id)
    {
        // Hapus juga detail-nya
        $this->kibDetailModel->where('id_kib_kategori', $id)->delete();
        $this->kibKategoriModel->delete($id);
        return redirect()->to('/master/kode-barang');
    }

    public function aturKib($id)
    {
        $kib     = $this->kibKategoriModel->find($id);
        if (!$kib) return redirect()->to('/master/kode-barang');

        $details = $this->kibDetailModel->where('id_kib_kategori', $id)->orderBy('kode', 'ASC')->findAll();

        // Hitung nomor urut berikutnya
        $nextNo  = str_pad(count($details) + 1, 2, '0', STR_PAD_LEFT);

        $data = [
            'title'   => 'Atur KIB: ' . $kib['nama_kib'],
            'kib'     => $kib,
            'details' => $details,
            'nextNo'  => $nextNo,
        ];
        return view('master/kib_detail', $data);
    }

    public function simpanKibDetail()
    {
        $id              = $this->request->getPost('id');
        $id_kib_kategori = $this->request->getPost('id_kib_kategori');
        $kode_prefix     = $this->request->getPost('kode_prefix');
        $kode_urut       = $this->request->getPost('kode_urut');

        $data = [
            'id_kib_kategori' => $id_kib_kategori,
            'kode'            => $kode_prefix . $kode_urut,
            'nama_barang'     => $this->request->getPost('nama_barang'),
            'keterangan'      => $this->request->getPost('keterangan'),
        ];

        if ($id) $this->kibDetailModel->update($id, $data);
        else $this->kibDetailModel->insert($data);

        return redirect()->to('/master/kode-barang/atur/' . $id_kib_kategori);
    }

    public function hapusKibDetail($id)
    {
        $detail = $this->kibDetailModel->find($id);
        $id_kib = $detail['id_kib_kategori'] ?? 0;
        $this->kibDetailModel->delete($id);
        return redirect()->to('/master/kode-barang/atur/' . $id_kib);
    }
}
