<?php

namespace App\Controllers;

use App\Models\PeminjamanModel;
use App\Models\PerbaikanModel;
use App\Models\PengajuanModel;
use App\Models\PenghapusanModel;
use App\Models\BarangModel;
use App\Models\RuanganModel;

class ManajemenAset extends BaseController
{
    protected $peminjamanModel;
    protected $perbaikanModel;
    protected $pengajuanModel;
    protected $penghapusanModel;

    public function __construct()
    {
        $this->peminjamanModel = new PeminjamanModel();
        $this->perbaikanModel = new PerbaikanModel();
        $this->pengajuanModel = new PengajuanModel();
        $this->penghapusanModel = new PenghapusanModel();
    }

    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;
    }

    // --- PEMINJAMAN ---
    public function peminjaman()
    {
        $db = \Config\Database::connect();
        $builder = $db->table('peminjaman');
        $builder->select('peminjaman.*, barang.nama_barang, ruangan.nama_ruangan');
        $builder->join('barang', 'barang.id = peminjaman.id_barang', 'left');
        $builder->join('ruangan', 'ruangan.id = peminjaman.id_ruangan', 'left');
        $rows = $builder->get()->getResultArray();

        $total_biaya = array_sum(array_column($rows, 'biaya'));

        $data = [
            'title'      => 'Peminjaman Aset',
            'data'       => $rows,
            'total_biaya'=> $total_biaya,
            'barang'     => (new BarangModel())->findAll(),
            'ruangan'    => (new RuanganModel())->findAll(),
        ];
        return view('transaksi/peminjaman', $data);
    }

    public function simpanPeminjaman()
    {
        $id = $this->request->getPost('id');
        $data = [
            'id_barang'        => $this->request->getPost('id_barang'),
            'id_ruangan'       => $this->request->getPost('id_ruangan'),
            'tgl_peminjaman'   => $this->request->getPost('tgl_peminjaman'),
            'tgl_pengembalian' => $this->request->getPost('tgl_pengembalian'),
            'biaya'            => $this->request->getPost('biaya') ?: 0,
            'keterangan'       => $this->request->getPost('keterangan'),
        ];

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

        $bukti_bayar = $this->handleUpload('bukti_bayar');
        if ($bukti_bayar) $data['bukti_bayar'] = $bukti_bayar;

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

        return redirect()->to('/transaksi/peminjaman');
    }

    public function hapusPeminjaman($id)
    {
        $this->peminjamanModel->delete($id);
        return redirect()->to('/transaksi/peminjaman');
    }

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

    // --- PERBAIKAN ---
    public function perbaikan()
    {
        $db = \Config\Database::connect();
        $builder = $db->table('perbaikan');
        $builder->select('perbaikan.*, barang.kode_barang, barang.nama_barang, ruangan.nama_ruangan');
        $builder->join('barang', 'barang.id = perbaikan.id_barang', 'left');
        $builder->join('ruangan', 'ruangan.id = perbaikan.id_ruangan', 'left');
        $rows = $builder->get()->getResultArray();

        $total_biaya = array_sum(array_column($rows, 'biaya'));

        $data = [
            'title'      => 'Perbaikan Aset',
            'data'       => $rows,
            'total_biaya'=> $total_biaya,
            'barang'     => (new BarangModel())->findAll(),
            'ruangan'    => (new RuanganModel())->findAll(),
        ];
        return view('transaksi/perbaikan', $data);
    }

    public function simpanPerbaikan()
    {
        $id = $this->request->getPost('id');
        $data = [
            'id_barang'       => $this->request->getPost('id_barang'),
            'id_ruangan'      => $this->request->getPost('id_ruangan'),
            'jenis_perbaikan' => $this->request->getPost('jenis_perbaikan'),
            'tgl_kerusakan'   => $this->request->getPost('tgl_kerusakan'),
            'tgl_perbaikan'   => $this->request->getPost('tgl_perbaikan'),
            'biaya'           => $this->request->getPost('biaya') ?: 0,
        ];

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

        $bukti_bayar = $this->handleUpload('bukti_bayar');
        if ($bukti_bayar) $data['bukti_bayar'] = $bukti_bayar;

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

        return redirect()->to('/transaksi/perbaikan');
    }

    public function hapusPerbaikan($id)
    {
        $this->perbaikanModel->delete($id);
        return redirect()->to('/transaksi/perbaikan');
    }

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

    // --- PENGAJUAN ---
    public function pengajuan()
    {
        $db = \Config\Database::connect();
        $builder = $db->table('pengajuan');
        $builder->select('pengajuan.*, ruangan.nama_ruangan');
        $builder->join('ruangan', 'ruangan.id = pengajuan.id_ruangan', 'left');
        $rows = $builder->get()->getResultArray();

        $total_biaya = array_sum(array_column($rows, 'biaya'));

        $data = [
            'title'      => 'Pengajuan Aset',
            'data'       => $rows,
            'total_biaya'=> $total_biaya,
            'ruangan'    => (new RuanganModel())->findAll(),
        ];
        return view('transaksi/pengajuan', $data);
    }

    public function simpanPengajuan()
    {
        $id = $this->request->getPost('id');
        $data = [
            'nama_barang'      => $this->request->getPost('nama_barang'),
            'id_ruangan'       => $this->request->getPost('id_ruangan'),
            'tgl_pengajuan'    => $this->request->getPost('tgl_pengajuan'),
            'tgl_persetujuan'  => $this->request->getPost('tgl_persetujuan'),
            'biaya'            => $this->request->getPost('biaya') ?: 0,
            'keterangan'       => $this->request->getPost('keterangan'),
            'status_realisasi' => $this->request->getPost('status_realisasi') ?: 'Pending',
        ];

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

        $bukti_bayar = $this->handleUpload('bukti_bayar');
        if ($bukti_bayar) $data['bukti_bayar'] = $bukti_bayar;

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

        return redirect()->to('/transaksi/pengajuan');
    }

    public function hapusPengajuan($id)
    {
        $this->pengajuanModel->delete($id);
        return redirect()->to('/transaksi/pengajuan');
    }

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

    // --- PENGHAPUSAN ---
    public function penghapusan()
    {
        $db = \Config\Database::connect();
        $builder = $db->table('penghapusan');
        $builder->select('penghapusan.*, barang.nama_barang, ruangan.nama_ruangan');
        $builder->join('barang', 'barang.id = penghapusan.id_barang', 'left');
        $builder->join('ruangan', 'ruangan.id = penghapusan.id_ruangan', 'left');
        $rows = $builder->get()->getResultArray();

        $total_pemasukan = array_sum(array_column($rows, 'pemasukan'));

        $data = [
            'title'          => 'Penghapusan Aset',
            'data'           => $rows,
            'total_pemasukan'=> $total_pemasukan,
            'barang'         => (new BarangModel())->findAll(),
            'ruangan'        => (new RuanganModel())->findAll(),
        ];
        return view('transaksi/penghapusan', $data);
    }

    public function simpanPenghapusan()
    {
        $id = $this->request->getPost('id');
        $data = [
            'id_barang'        => $this->request->getPost('id_barang'),
            'id_ruangan'       => $this->request->getPost('id_ruangan'),
            'tgl_kerusakan'    => $this->request->getPost('tgl_kerusakan'),
            'tgl_persetujuan'  => $this->request->getPost('tgl_persetujuan'),
            'keterangan'       => $this->request->getPost('keterangan'),
            'status_realisasi' => $this->request->getPost('status_realisasi'),
            'pemasukan'        => $this->request->getPost('pemasukan') ?: 0,
        ];

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

        $bukti_realisasi = $this->handleUpload('bukti_realisasi');
        if ($bukti_realisasi) $data['bukti_realisasi'] = $bukti_realisasi;

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

        return redirect()->to('/transaksi/penghapusan');
    }

    public function hapusPenghapusan($id)
    {
        $this->penghapusanModel->delete($id);
        return redirect()->to('/transaksi/penghapusan');
    }

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