<?php

namespace App\Controllers\Api;

use App\Models\BarangUnitModel;
use App\Models\MutasiBarangModel;
use App\Models\PemeliharaanModel;
use App\Models\PenghapusanModel;

class UnitRiwayatController extends BaseApiController
{
    public function show($id_unit)
    {
        $unitModel   = new BarangUnitModel();
        $mutasiModel = new MutasiBarangModel();
        $rawatModel  = new PemeliharaanModel();
        $hapusModel  = new PenghapusanModel();

        // ===============================
        // DATA UNIT
        // ===============================
        $unit = $unitModel
            ->select('
                barang_unit.*,
                barang.nama_barang,
                ruangan.nama_ruangan
            ')
            ->join('barang', 'barang.id_barang = barang_unit.id_barang')
            ->join('ruangan', 'ruangan.id_ruangan = barang_unit.id_ruangan')
            ->find($id_unit);

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

        $timeline = [];
        $pemusnahan = null;

        // ===============================
        // 1️⃣ CREATE (SELALU ADA)
        // ===============================
        $timeline[] = [
            'tanggal'   => $unit['created_at'],
            'tipe'      => 'create',
            'judul'     => 'Unit dibuat',
            'deskripsi' =>
                "Unit {$unit['kode_unit']} dibuat dan ditempatkan di {$unit['nama_ruangan']}",
        ];

        // ===============================
        // 2️⃣ MUTASI
        // ===============================
        $mutasi = $mutasiModel
            ->select('
                mutasi_barang.tanggal,
                r1.nama_ruangan AS dari_ruangan,
                r2.nama_ruangan AS ke_ruangan
            ')
            ->join('ruangan r1', 'r1.id_ruangan = mutasi_barang.dari_ruangan')
            ->join('ruangan r2', 'r2.id_ruangan = mutasi_barang.ke_ruangan')
            ->where('id_unit', $id_unit)
            ->orderBy('tanggal', 'ASC')
            ->findAll();

        foreach ($mutasi as $m) {
            $timeline[] = [
                'tanggal'   => $m['tanggal'],
                'tipe'      => 'mutasi',
                'judul'     => 'Mutasi unit',
                'deskripsi' =>
                    "Dipindahkan dari {$m['dari_ruangan']} ke {$m['ke_ruangan']}",
            ];
        }

        // ===============================
        // 3️⃣ PEMELIHARAAN
        // ===============================
        $rawat = $rawatModel
            ->where('id_unit', $id_unit)
            ->orderBy('tanggal', 'ASC')
            ->findAll();

        foreach ($rawat as $r) {
            $timeline[] = [
                'tanggal'   => $r['tanggal'],
                'tipe'      => 'pemeliharaan',
                'judul'     => 'Pemeliharaan',
                'deskripsi' =>
                    "{$r['jenis_perbaikan']} (Rp " .
                    number_format($r['biaya'], 0, ',', '.') . ")",
            ];
        }

        // ===============================
        // 4️⃣ SORT SEMUA KECUALI PEMUSNAHAN
        // ===============================
        usort($timeline, function ($a, $b) {
            return strtotime($a['tanggal']) <=> strtotime($b['tanggal']);
        });

        // ===============================
        // 5️⃣ PEMUSNAHAN (TERMINAL STATE)
        // ===============================
        $hapus = $hapusModel
            ->where('id_unit', $id_unit)
            ->first();

        if ($hapus) {
            $timeline[] = [
                'tanggal'   => $hapus['tanggal'],
                'tipe'      => 'pemusnahan',
                'judul'     => 'Pemusnahan',
                'deskripsi' => $hapus['alasan'],
            ];
        }

        // ===============================
        // RESPONSE
        // ===============================
        return $this->respondSuccess([
            'unit'     => $unit,
            'timeline' => $timeline,
        ], 'Riwayat unit');
    }
}