<?php

namespace App\Controllers;

use App\Models\BarangModel;
use App\Models\TanahModel;
use App\Models\BangunanModel;
use App\Models\BukuModel;
use App\Models\JenisBarangModel;
use App\Models\RuanganModel;
use App\Models\SumberDanaModel;
use App\Models\KibKategoriModel;
use App\Models\KibDetailModel;
use PhpOffice\PhpSpreadsheet\IOFactory;

class DataAset extends BaseController
{
    protected $barangModel;
    protected $tanahModel;
    protected $bangunanModel;
    protected $bukuModel;

    public function __construct()
    {
        $this->barangModel = new BarangModel();
        $this->tanahModel = new TanahModel();
        $this->bangunanModel = new BangunanModel();
        $this->bukuModel = new BukuModel();
    }

    private function handleUpload($fileInputName)
    {
        $file = $this->request->getFile($fileInputName);
        if ($file && $file->isValid() && !$file->hasMoved()) {
            $newName = $file->getRandomName();
            $file->move(FCPATH . 'uploads', $newName);
            return $newName;
        }
        return null;
    }

    // --- JSON ENDPOINT: KIB Details ---
    public function getKibDetails($id_kib)
    {
        $details = (new KibDetailModel())->where('id_kib_kategori', $id_kib)->orderBy('kode','ASC')->findAll();
        return $this->response->setJSON($details);
    }

    // --- BARANG ---
    public function barang()
    {
        $db = \Config\Database::connect();
        $builder = $db->table('barang');
        $builder->select('barang.*, kib_detail.nama_barang as nama_jenis, ruangan.nama_ruangan, sumber_dana.nama_sumber');
        $builder->join('kib_detail', 'kib_detail.kode = barang.kode_barang', 'left');
        $builder->join('ruangan', 'ruangan.id = barang.id_ruangan', 'left');
        $builder->join('sumber_dana', 'sumber_dana.id = barang.id_sumber_dana', 'left');
        
        // Ambil jenis unik dari kib_detail untuk filter
        $jenisUnik = $db->table('kib_detail')->select('nama_barang as nama_jenis')->distinct()->get()->getResultArray();

        $data = [
            'title'    => 'Data Barang',
            'barang'   => $builder->get()->getResultArray(),
            'jenis'    => $jenisUnik,
            'ruangan'  => (new RuanganModel())->findAll(),
            'sumber'   => (new SumberDanaModel())->findAll(),
            'kibList'  => (new KibKategoriModel())->findAll(),
            'kibDetails' => (new KibDetailModel())->findAll(),
        ];
        return view('aset/barang', $data);
    }

    public function simpanBarang()
    {
        $id = $this->request->getPost('id');
        $data = [
            'kib' => $this->request->getPost('kib'),
            'kode_barang' => $this->request->getPost('kode_barang'),
            'nama_barang' => $this->request->getPost('nama_barang'),
            'merk' => $this->request->getPost('merk'),
            'spesifikasi' => $this->request->getPost('spesifikasi'),
            'jumlah' => $this->request->getPost('jumlah'),
            'harga_satuan' => $this->request->getPost('harga_satuan'),
            'harga_total' => $this->request->getPost('jumlah') * $this->request->getPost('harga_satuan'),
            'id_sumber_dana' => $this->request->getPost('id_sumber_dana'),
            'id_ruangan' => $this->request->getPost('id_ruangan'),
            'tahun_perolehan' => $this->request->getPost('tahun_perolehan'),
            'umur_ekonomis' => $this->request->getPost('umur_ekonomis'),
            'penyusutan_per_tahun' => $this->request->getPost('harga_satuan') / max($this->request->getPost('umur_ekonomis'), 1),
            'kondisi' => $this->request->getPost('kondisi'),
        ];

        $foto = $this->handleUpload('foto');
        if ($foto) {
            $data['foto'] = $foto;
        }

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

        return redirect()->to('/aset/barang');
    }

    public function hapusBarang($id)
    {
        $this->barangModel->delete($id);
        return redirect()->to('/aset/barang');
    }

    public function hapusSemuaBarang()
    {
        $db = \Config\Database::connect();
        $db->table('barang')->truncate();
        return redirect()->to('/aset/barang');
    }

    public function importBarang()
    {
        $file = $this->request->getFile('file_excel');
        if ($file && $file->isValid()) {
            $spreadsheet = IOFactory::load($file->getTempName());
            $sheetData = $spreadsheet->getActiveSheet()->toArray();
            
            // Format Excel diharapkan: KIB | Kode Barang | Nama Barang | ID Jenis | Merk | Spesifikasi | Jumlah | Harga Satuan | ID Sumber Dana | ID Ruangan | Tahun Perolehan | Umur Ekonomis | Kondisi
            for ($i = 1; $i < count($sheetData); $i++) {
                $row = $sheetData[$i];
                if (empty($row[1])) continue; // Lewati jika kode barang kosong

                $jumlah = (int)($row[6] ?? 1);
                $harga_satuan = (float)($row[7] ?? 0);
                $umur = (int)($row[11] ?? 1);

                $data = [
                    'kib' => $row[0] ?? null,
                    'kode_barang' => $row[1],
                    'nama_barang' => $row[2],
                    'id_jenis' => $row[3],
                    'merk' => $row[4],
                    'spesifikasi' => $row[5],
                    'jumlah' => $jumlah,
                    'harga_satuan' => $harga_satuan,
                    'harga_total' => $jumlah * $harga_satuan,
                    'id_sumber_dana' => $row[8],
                    'id_ruangan' => $row[9],
                    'tahun_perolehan' => $row[10],
                    'umur_ekonomis' => $umur,
                    'penyusutan_per_tahun' => $harga_satuan / max($umur, 1),
                    'kondisi' => $row[12] ?? 'Baik',
                ];
                $this->barangModel->insert($data);
            }
        }
        return redirect()->to('/aset/barang');
    }

    // --- TANAH & BANGUNAN ---
    public function tanahBangunan()
    {
        $tanah = $this->tanahModel->findAll();
        $bangunan = $this->bangunanModel->findAll();

        $tanahAwal = array_sum(array_column($tanah, 'nilai_perolehan'));
        $tanahSkrg = array_sum(array_column($tanah, 'nilai_sekarang'));
        $tanahKenaikan = max($tanahSkrg - $tanahAwal, 0);

        $bangunanAwal = array_sum(array_column($bangunan, 'nilai_perolehan'));
        $bangunanSkrg = array_sum(array_column($bangunan, 'nilai_sekarang'));
        $bangunanPenyusutan = max($bangunanAwal - $bangunanSkrg, 0);

        $data = [
            'title'      => 'Data Tanah & Bangunan',
            'tanah'      => $tanah,
            'bangunan'   => $bangunan,
            'tanahStats' => [
                'awal' => $tanahAwal,
                'kenaikan' => $tanahKenaikan,
                'skrg' => $tanahSkrg
            ],
            'bangunanStats' => [
                'awal' => $bangunanAwal,
                'penyusutan' => $bangunanPenyusutan,
                'skrg' => $bangunanSkrg
            ],
            'kibList'    => (new KibKategoriModel())->findAll(),
            'kibDetails' => (new KibDetailModel())->findAll(),
        ];
        return view('aset/tanah_bangunan', $data);
    }

    public function simpanTanah()
    {
        $id = $this->request->getPost('id');
        $data = [
            'kib'                => $this->request->getPost('kib'),
            'kode_barang'        => $this->request->getPost('kode_barang'),
            'nama_tanah'         => $this->request->getPost('nama_tanah'),
            'status_kepemilikan' => $this->request->getPost('status_kepemilikan'),
            'luas'               => $this->request->getPost('luas'),
            'lokasi'             => $this->request->getPost('lokasi'),
            'tahun_perolehan'    => $this->request->getPost('tahun_perolehan'),
            'nilai_perolehan'    => $this->request->getPost('nilai_perolehan'),
            'kenaikan_per_tahun' => $this->request->getPost('kenaikan_per_tahun'),
            'nilai_sekarang'     => $this->request->getPost('nilai_perolehan') + ($this->request->getPost('kenaikan_per_tahun') * (date('Y') - $this->request->getPost('tahun_perolehan'))),
            'kondisi'            => $this->request->getPost('kondisi'),
            'keterangan'         => $this->request->getPost('keterangan'),
        ];
        if ($id) $this->tanahModel->update($id, $data);
        else $this->tanahModel->insert($data);
        return redirect()->to('/aset/tanah-bangunan');
    }

    public function hapusTanah($id)
    {
        $this->tanahModel->delete($id);
        return redirect()->to('/aset/tanah-bangunan');
    }

    public function simpanBangunan()
    {
        $id = $this->request->getPost('id');
        $data = [
            'kib'                  => $this->request->getPost('kib'),
            'kode_barang'          => $this->request->getPost('kode_barang'),
            'nama_bangunan'        => $this->request->getPost('nama_bangunan'),
            'luas_bangunan'        => $this->request->getPost('luas_bangunan'),
            'jumlah_ruang'         => $this->request->getPost('jumlah_ruang'),
            'tahun_dibangun'       => $this->request->getPost('tahun_dibangun'),
            'nilai_perolehan'      => $this->request->getPost('nilai_perolehan'),
            'penyusutan_per_tahun' => $this->request->getPost('penyusutan_per_tahun'),
            'nilai_sekarang'       => $this->request->getPost('nilai_perolehan') - ($this->request->getPost('penyusutan_per_tahun') * (date('Y') - $this->request->getPost('tahun_dibangun'))),
            'kondisi'              => $this->request->getPost('kondisi'),
        ];
        if ($id) $this->bangunanModel->update($id, $data);
        else $this->bangunanModel->insert($data);
        return redirect()->to('/aset/tanah-bangunan');
    }

    public function hapusBangunan($id)
    {
        $this->bangunanModel->delete($id);
        return redirect()->to('/aset/tanah-bangunan');
    }

    // --- BUKU ---
    public function buku()
    {
        $db = \Config\Database::connect();
        $builder = $db->table('buku');
        $builder->select('buku.*, ruangan.nama_ruangan, sumber_dana.nama_sumber');
        $builder->join('ruangan', 'ruangan.id = buku.id_ruangan', 'left');
        $builder->join('sumber_dana', 'sumber_dana.id = buku.id_sumber_dana', 'left');
        
        $data = [
            'title'      => 'Data Buku',
            'buku'       => $builder->get()->getResultArray(),
            'ruangan'    => (new RuanganModel())->findAll(),
            'sumber'     => (new SumberDanaModel())->findAll(),
            'kibList'    => (new KibKategoriModel())->findAll(),
            'kibDetails' => (new KibDetailModel())->findAll(),
        ];
        return view('aset/buku', $data);
    }

    public function simpanBuku()
    {
        $id = $this->request->getPost('id');
        $tgl_input = $this->request->getPost('tgl_pengadaan');
        $tgl_pengadaan = (strlen($tgl_input) == 4) ? $tgl_input . '-01-01' : $tgl_input;

        $data = [
            'kib' => $this->request->getPost('kib'),
            'kode_barang' => $this->request->getPost('kode_barang'),
            'tgl_pengadaan' => $tgl_pengadaan,
            'id_sumber_dana' => $this->request->getPost('id_sumber_dana'),
            'judul' => $this->request->getPost('judul'),
            'jenis_bacaan' => $this->request->getPost('jenis_bacaan'),
            'pengarang' => $this->request->getPost('pengarang'),
            'penerbit' => $this->request->getPost('penerbit'),
            'tahun_terbit' => $this->request->getPost('tahun_terbit'),
            'harga_satuan' => $this->request->getPost('harga_satuan'),
            'jumlah' => $this->request->getPost('jumlah'),
            'total_harga' => $this->request->getPost('harga_satuan') * $this->request->getPost('jumlah'),
            'kondisi' => $this->request->getPost('kondisi'),
            'id_ruangan' => $this->request->getPost('id_ruangan'),
            'umur_ekonomis' => $this->request->getPost('umur_ekonomis') ?: 5, // Default 5 jika kosong
            'penyusutan_per_tahun' => $this->request->getPost('harga_satuan') / max($this->request->getPost('umur_ekonomis') ?: 5, 1),
        ];

        $foto = $this->handleUpload('foto');
        if ($foto) {
            $data['foto'] = $foto;
        }

        if ($id) $this->bukuModel->update($id, $data);
        else $this->bukuModel->insert($data);
        return redirect()->to('/aset/buku');
    }

    public function hapusBuku($id)
    {
        $this->bukuModel->delete($id);
        return redirect()->to('/aset/buku');
    }

    public function hapusSemuaBuku()
    {
        $db = \Config\Database::connect();
        $db->table('buku')->truncate();
        return redirect()->to('/aset/buku');
    }

    public function importBuku()
    {
        $file = $this->request->getFile('file_excel');
        if ($file && $file->isValid()) {
            $spreadsheet = IOFactory::load($file->getTempName());
            $sheetData = $spreadsheet->getActiveSheet()->toArray();
            
            // Format Excel: KIB | Kode Brg | Tgl Pengadaan | ID Sumber Dana | Judul | Jenis Bacaan | Pengarang | Penerbit | Tahun Terbit | Harga Satuan | Jumlah | ID Ruangan | Kondisi
            for ($i = 1; $i < count($sheetData); $i++) {
                $row = $sheetData[$i];
                if (empty($row[4])) continue; // Lewati jika judul kosong

                $harga_satuan = (float)($row[9] ?? 0);
                $jumlah = (int)($row[10] ?? 1);

                $data = [
                    'kib' => $row[0] ?? null,
                    'kode_barang' => $row[1] ?? null,
                    'tgl_pengadaan' => $row[2] ?? date('Y-m-d'),
                    'id_sumber_dana' => $row[3],
                    'judul' => $row[4],
                    'jenis_bacaan' => $row[5],
                    'pengarang' => $row[6],
                    'penerbit' => $row[7],
                    'tahun_terbit' => $row[8],
                    'harga_satuan' => $harga_satuan,
                    'jumlah' => $jumlah,
                    'total_harga' => $harga_satuan * $jumlah,
                    'id_ruangan' => $row[11],
                    'kondisi' => $row[12] ?? 'Baik',
                ];
                $this->bukuModel->insert($data);
            }
        }
        return redirect()->to('/aset/buku');
    }
}
