<?php

namespace App\Controllers;

use App\Models\ProdukModel;

class Produk extends BaseController
{
    private ProdukModel $model;

    public function __construct()
    {
        $this->model = new ProdukModel();
    }

    // ────────────────────────────────────────────────────────────
    // GET /produk
    // ────────────────────────────────────────────────────────────
    public function index(): string
    {
        return view('produk/index');
    }

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

        try {
            $list = $this->model->getAllWithLog(true);
            $log  = $this->model->getLog(0, 50);

            $aktifList  = array_values(array_filter($list, fn($r) => (int)$r['is_aktif'] === 1));
            $totalStok  = array_sum(array_column($aktifList, 'stok'));
            $totalNilai = array_sum(array_map(fn($r) => (int)$r['stok'] * (float)$r['harga_jual'], $aktifList));
            $stokNipis  = count(array_filter($aktifList, fn($r) => (int)$r['stok'] <= 5));

            return $this->response->setJSON([
                'success' => true,
                'list'    => array_values($list),
                'log'     => $log,
                'summary' => [
                    'total_produk'   => count($aktifList),
                    'total_stok'     => $totalStok,
                    'total_nilai'    => $totalNilai,
                    'stok_nipis'     => $stokNipis,
                    'total_nonaktif' => count($list) - count($aktifList),
                ],
            ]);
        } catch (\Throwable $e) {
            log_message('error', '[Produk::data] ' . $e->getMessage());
            return $this->response->setJSON(['success' => false, 'error' => 'Gagal memuat data: ' . $e->getMessage()]);
        }
    }

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

        // Support JSON body maupun form-data
        $body = $this->request->getJSON(true);
        if (empty($body)) {
            $body = $this->request->getPost();
        }

        $id         = (int)($body['id']         ?? 0);
        $kode       = trim($body['kode']         ?? '');
        $nama       = trim($body['nama']         ?? '');
        $beratGram  = (int)($body['berat_gram']  ?? 250);
        $hargaJual  = (float)($body['harga_jual'] ?? 0);
        $keterangan = trim($body['keterangan']   ?? '');

        // Validasi
        if ($kode === '') {
            return $this->response->setJSON(['success' => false, 'error' => 'Kode produk wajib diisi.']);
        }
        if ($nama === '') {
            return $this->response->setJSON(['success' => false, 'error' => 'Nama produk wajib diisi.']);
        }
        if ($hargaJual <= 0) {
            return $this->response->setJSON(['success' => false, 'error' => 'Harga jual harus lebih dari 0.']);
        }
        if ($beratGram <= 0) {
            $beratGram = 250;
        }

        // Cek duplikat kode
        if ($this->model->isKodeTaken($kode, $id)) {
            return $this->response->setJSON(['success' => false, 'error' => "Kode produk '{$kode}' sudah digunakan."]);
        }

        $data = [
            'kode'       => $kode,
            'nama'       => $nama,
            'berat_gram' => $beratGram,
            'harga_jual' => $hargaJual,
            'keterangan' => $keterangan,
        ];

        try {
            if ($id > 0) {
                $produk = $this->model->findById($id);
                if (!$produk) {
                    return $this->response->setJSON(['success' => false, 'error' => 'Produk tidak ditemukan.']);
                }
                $this->model->updateProduk($id, $data);
                $msg = "Produk '{$nama}' berhasil diperbarui.";
            } else {
                $id  = $this->model->insertProduk($data);
                $msg = "Produk '{$nama}' berhasil ditambahkan.";
            }
        } catch (\Throwable $e) {
            log_message('error', '[Produk::simpan] ' . $e->getMessage());
            return $this->response->setJSON([
                'success' => false,
                'error'   => $e->getMessage(),
                'file'    => $e->getFile(),
                'line'    => $e->getLine(),
            ]);
        }

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

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

        $body       = $this->request->getJSON(true) ?? [];
        $idProduk   = (int)($body['id_produk']  ?? 0);
        $jumlah     = (int)($body['jumlah']      ?? 0);
        $keterangan = trim($body['keterangan']  ?? 'Produksi');

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

        $produk = $this->model->findById($idProduk);
        if (!$produk) {
            return $this->response->setJSON(['success' => false, 'error' => 'Produk tidak ditemukan.']);
        }

        try {
            $this->model->tambahStok($idProduk, $jumlah, $keterangan ?: 'Produksi');
        } catch (\Throwable $e) {
            log_message('error', '[Produk::tambahStok] ' . $e->getMessage());
            return $this->response->setJSON(['success' => false, 'error' => 'Gagal menambah stok.']);
        }

        return $this->response->setJSON(['success' => true, 'message' => "Stok bertambah {$jumlah} kemasan."]);
    }

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

        $body       = $this->request->getJSON(true) ?? [];
        $idProduk   = (int)($body['id_produk']  ?? 0);
        $jumlah     = (int)($body['jumlah']      ?? 0);
        $keterangan = trim($body['keterangan']  ?? 'Terjual');

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

        try {
            $ok = $this->model->kurangiStok($idProduk, $jumlah, $keterangan ?: 'Terjual');
        } catch (\Throwable $e) {
            log_message('error', '[Produk::kurangiStok] ' . $e->getMessage());
            return $this->response->setJSON(['success' => false, 'error' => 'Gagal mengurangi stok.']);
        }

        if (!$ok) {
            return $this->response->setJSON(['success' => false, 'error' => 'Stok tidak mencukupi.']);
        }

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

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

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

        if (!$id) {
            return $this->response->setJSON(['success' => false, 'error' => 'ID tidak valid.']);
        }

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

        try {
            $this->model->nonaktifkan($id);
        } catch (\Throwable $e) {
            log_message('error', '[Produk::nonaktifkan] ' . $e->getMessage());
            return $this->response->setJSON(['success' => false, 'error' => 'Gagal menonaktifkan produk.']);
        }

        return $this->response->setJSON(['success' => true, 'message' => "Produk '{$produk['nama']}' dinonaktifkan."]);
    }

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

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

        if (!$id) {
            return $this->response->setJSON(['success' => false, 'error' => 'ID tidak valid.']);
        }

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

        try {
            $this->model->aktifkan($id);
        } catch (\Throwable $e) {
            log_message('error', '[Produk::aktifkan] ' . $e->getMessage());
            return $this->response->setJSON(['success' => false, 'error' => 'Gagal mengaktifkan produk.']);
        }

        return $this->response->setJSON(['success' => true, 'message' => "Produk '{$produk['nama']}' diaktifkan kembali."]);
    }

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