<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\BahanModel;
use App\Models\PembelianBahanModel;
use App\Models\PenggunaanBahanModel;

class Bahan extends BaseController
{
    private BahanModel           $model;
    private PembelianBahanModel  $modelBeli;
    private PenggunaanBahanModel $modelPakai;

    public function __construct()
    {
        $this->model      = new BahanModel();
        $this->modelBeli  = new PembelianBahanModel();
        $this->modelPakai = new PenggunaanBahanModel();
    }

    // ── GET /bahan ────────────────────────────────────────────────────────────
    public function index(): string
    {
        return view('bahan/index', [
            'title' => 'Manajemen Bahan',
        ]);
    }

    // ── GET /bahan/data  (AJAX) ───────────────────────────────────────────────
    public function data(): \CodeIgniter\HTTP\ResponseInterface
    {
        if (! $this->request->isAJAX()) return $this->forbidden();

        $list  = $this->model->getAllWithStats();
        $trash = $this->model->getDeleted();

        $totalNilai = array_sum(array_map(
            fn($r) => (float) $r['stok_bahan'] * (float) $r['harga_bahan'],
            $list
        ));
        $stokNipis = count(array_filter(
            $list, fn($r) => (float) $r['stok_bahan'] <= 5 && (float) $r['stok_bahan'] > 0
        ));
        $stokHabis = count(array_filter(
            $list, fn($r) => (float) $r['stok_bahan'] <= 0
        ));

        return $this->response->setJSON([
            'success'    => true,
            'list'       => $list,
            'trash'      => $trash,
            'penggunaan' => $this->modelPakai->getRiwayat(100),
            'summary'    => [
                'total_jenis' => count($list),
                'total_nilai' => $totalNilai,
                'stok_nipis'  => $stokNipis,
                'stok_habis'  => $stokHabis,
                'total_beli'  => $this->modelBeli->getTotalNilai(),
            ],
        ]);
    }

    // ── POST /bahan/simpan ────────────────────────────────────────────────────
    public function simpan(): \CodeIgniter\HTTP\ResponseInterface
    {
        if (! $this->request->isAJAX()) return $this->forbidden();

        $body = $this->request->getJSON(true) ?? [];
        $id   = (int) ($body['id_bahan'] ?? 0);
        $nama = trim($body['nama_bahan'] ?? '');

        if (! $nama) {
            return $this->response->setJSON([
                'success' => false,
                'error'   => 'Nama bahan wajib diisi.',
            ]);
        }

        $data = [
            'nama_bahan'       => $nama,
            'satuan_bahan'     => trim($body['satuan_bahan']     ?? 'kg'),
            'harga_bahan'      => (float) ($body['harga_bahan']   ?? 0),
            'keterangan_bahan' => trim($body['keterangan_bahan'] ?? ''),
        ];

        if ($id > 0) {
            if (! $this->model->find($id)) {
                return $this->response->setJSON(['success' => false, 'error' => 'Data tidak ditemukan.']);
            }
            $this->model->update($id, $data);
            $msg = "Bahan \"$nama\" berhasil diperbarui.";
        } else {
            $data['stok_bahan']   = 0;
            $data['status_bahan'] = 'aktif';
            $this->model->insert($data);
            $id  = $this->model->getInsertID();
            $msg = "Bahan \"$nama\" berhasil ditambahkan.";
        }

        return $this->response->setJSON(['success' => true, 'id_bahan' => $id, 'message' => $msg]);
    }

    // ── POST /bahan/pakai ─────────────────────────────────────────────────────
    public function pakai(): \CodeIgniter\HTTP\ResponseInterface
    {
        if (! $this->request->isAJAX()) return $this->forbidden();

        $body    = $this->request->getJSON(true) ?? [];
        $idBahan = (int) ($body['id_bahan']            ?? 0);
        $jumlah  = (float) ($body['jumlah_penggunaan'] ?? 0);

        if (! $idBahan || $jumlah <= 0) {
            return $this->response->setJSON([
                'success' => false,
                'error'   => 'Bahan dan jumlah wajib diisi dengan benar.',
            ]);
        }

        $bahan = $this->model->find($idBahan);
        if (! $bahan) {
            return $this->response->setJSON(['success' => false, 'error' => 'Bahan tidak ditemukan.']);
        }

        if ((float) $bahan['stok_bahan'] < $jumlah) {
            return $this->response->setJSON([
                'success' => false,
                'error'   => "Stok tidak mencukupi. Tersedia: {$bahan['stok_bahan']} {$bahan['satuan_bahan']}.",
            ]);
        }

        $this->modelPakai->insert([
            'id_bahan'             => $idBahan,
            'tanggal_penggunaan'   => trim($body['tanggal_penggunaan']   ?? date('Y-m-d')),
            'jumlah_penggunaan'    => $jumlah,
            'keperluan_penggunaan' => trim($body['keperluan_penggunaan'] ?? ''),
            'catatan_penggunaan'   => trim($body['catatan_penggunaan']   ?? ''),
        ]);

        $this->model->kurangiStok($idBahan, $jumlah);

        return $this->response->setJSON([
            'success' => true,
            'message' => "Penggunaan dicatat. Stok berkurang {$jumlah} {$bahan['satuan_bahan']}.",
        ]);
    }

    // ── POST /bahan/toggle-status ─────────────────────────────────────────────
    public function toggleStatus(): \CodeIgniter\HTTP\ResponseInterface
    {
        if (! $this->request->isAJAX()) return $this->forbidden();

        $id = (int) ($this->request->getJSON(true)['id_bahan'] ?? 0);
        if (! $id) {
            return $this->response->setJSON(['success' => false, 'error' => 'ID tidak valid.']);
        }

        $bahan = $this->model->find($id);
        if (! $bahan) {
            return $this->response->setJSON(['success' => false, 'error' => 'Bahan tidak ditemukan.']);
        }

        $this->model->toggleStatus($id);
        $newStatus = $bahan['status_bahan'] === 'aktif' ? 'nonaktif' : 'aktif';
        $label     = $newStatus === 'aktif' ? 'diaktifkan' : 'dinonaktifkan';

        return $this->response->setJSON([
            'success'    => true,
            'message'    => "Bahan \"{$bahan['nama_bahan']}\" berhasil $label.",
            'new_status' => $newStatus,
        ]);
    }

    // ── POST /bahan/hapus  (soft delete) ──────────────────────────────────────
    public function hapus(): \CodeIgniter\HTTP\ResponseInterface
    {
        if (! $this->request->isAJAX()) return $this->forbidden();

        $id = (int) ($this->request->getJSON(true)['id_bahan'] ?? 0);
        if (! $id) {
            return $this->response->setJSON(['success' => false, 'error' => 'ID tidak valid.']);
        }

        $bahan = $this->model->find($id);
        if (! $bahan) {
            return $this->response->setJSON(['success' => false, 'error' => 'Data tidak ditemukan.']);
        }

        $this->model->delete($id);

        return $this->response->setJSON([
            'success' => true,
            'message' => "Bahan \"{$bahan['nama_bahan']}\" berhasil dihapus. Bisa dipulihkan kapan saja.",
        ]);
    }

    // ── POST /bahan/restore ───────────────────────────────────────────────────
    public function restore(): \CodeIgniter\HTTP\ResponseInterface
    {
        if (! $this->request->isAJAX()) return $this->forbidden();

        $id = (int) ($this->request->getJSON(true)['id_bahan'] ?? 0);
        if (! $id) {
            return $this->response->setJSON(['success' => false, 'error' => 'ID tidak valid.']);
        }

        $bahan = $this->model->withDeleted()->find($id);
        if (! $bahan) {
            return $this->response->setJSON(['success' => false, 'error' => 'Bahan tidak ditemukan.']);
        }

        if ($bahan['deleted_at'] === null) {
            return $this->response->setJSON(['success' => false, 'error' => 'Bahan ini belum dihapus.']);
        }

        $this->model->restore($id);

        return $this->response->setJSON([
            'success' => true,
            'message' => "Bahan \"{$bahan['nama_bahan']}\" berhasil dipulihkan.",
        ]);
    }

    private function forbidden(): \CodeIgniter\HTTP\ResponseInterface
    {
        return $this->response->setStatusCode(403)->setJSON([
            'success' => false,
            'error'   => 'Forbidden',
        ]);
    }
}