<?php

namespace App\Models;

use CodeIgniter\Model;

class ResepModel extends Model
{
    protected $table      = 'tb_resep';
    protected $primaryKey = 'id_resep';

    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;

    protected $allowedFields = [
        'nama_resep',
        'id_produk',
        'catatan_resep',
    ];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    // ── Ambil semua resep dengan jumlah bahan & nama produk ─────────
    public function getResepWithDetails(): array
    {
        return $this->db->table('tb_resep r')
            ->select('
                r.id_resep,
                r.nama_resep,
                r.id_produk,
                r.catatan_resep,
                p.nama_produk,
                COUNT(d.id_detail_resep) AS jumlah_bahan
            ')
            ->join('tb_produk p', 'p.id_produk = r.id_produk', 'left')
            ->join('tb_detail_resep d', 'd.id_resep = r.id_resep', 'left')
            ->groupBy('r.id_resep')
            ->orderBy('r.nama_resep', 'ASC')
            ->get()->getResultArray();
    }

    // ── Ambil detail lengkap satu resep (header + items) ────────────
    public function getResepDetail(int $id): ?array
    {
        $header = $this->db->table('tb_resep r')
            ->select('r.id_resep, r.nama_resep, r.id_produk, r.catatan_resep, p.nama_produk')
            ->join('tb_produk p', 'p.id_produk = r.id_produk', 'left')
            ->where('r.id_resep', $id)
            ->get()->getRowArray();

        if (!$header) return null;

        $items = $this->db->table('tb_detail_resep d')
            ->select('d.id_detail_resep, d.id_bahan, d.jumlah_bahan, b.nama_bahan, b.satuan_bahan')
            ->join('tb_bahan b', 'b.id_bahan = d.id_bahan', 'left')
            ->where('d.id_resep', $id)
            ->get()->getResultArray();

        $header['items'] = $items;
        return $header;
    }

    // ── Simpan resep baru (header + items) ──────────────────────────
    public function simpanResep(string $nama, int $idProduk, string $catatan, array $items): int
    {
        $this->db->transBegin();
        try {
            $idResep = $this->insert([
                'nama_resep'   => $nama,
                'id_produk'    => $idProduk,
                'catatan_resep'=> $catatan,
            ]);

            foreach ($items as $item) {
                $this->db->table('tb_detail_resep')->insert([
                    'id_resep'     => $idResep,
                    'id_bahan'     => (int) $item['id_bahan'],
                    'jumlah_bahan' => (float) $item['jumlah_bahan'],
                    'created_at'   => date('Y-m-d H:i:s'),
                    'updated_at'   => date('Y-m-d H:i:s'),
                ]);
            }

            $this->db->transCommit();
            return $idResep;
        } catch (\Throwable $e) {
            $this->db->transRollback();
            throw $e;
        }
    }

    // ── Update resep: header diupdate, detail dihapus & insert ulang ─
    // id_resep di tb_produksi TIDAK berubah karena header tidak dihapus
    public function updateResep(int $id, string $nama, int $idProduk, string $catatan, array $items): void
    {
        $this->db->transBegin();
        try {
            // Update header — id_resep tetap sama, FK produksi aman
            $this->update($id, [
                'nama_resep'   => $nama,
                'id_produk'    => $idProduk,
                'catatan_resep'=> $catatan,
            ]);

            // Hapus detail lama, insert ulang
            $this->db->table('tb_detail_resep')->where('id_resep', $id)->delete();

            foreach ($items as $item) {
                $this->db->table('tb_detail_resep')->insert([
                    'id_resep'     => $id,
                    'id_bahan'     => (int) $item['id_bahan'],
                    'jumlah_bahan' => (float) $item['jumlah_bahan'],
                    'created_at'   => date('Y-m-d H:i:s'),
                    'updated_at'   => date('Y-m-d H:i:s'),
                ]);
            }

            $this->db->transCommit();
        } catch (\Throwable $e) {
            $this->db->transRollback();
            throw $e;
        }
    }

    // ── Hapus resep + detailnya ──────────────────────────────────────
    public function hapusResep(int $id): void
    {
        $this->db->transBegin();
        try {
            $this->db->table('tb_detail_resep')->where('id_resep', $id)->delete();
            $this->delete($id);
            $this->db->transCommit();
        } catch (\Throwable $e) {
            $this->db->transRollback();
            throw $e;
        }
    }

    // ── Dipakai ProduksiModel: ambil resep berdasar id_produk ───────
    public function getResepByProduk(int $idProduk): array
    {
        $headers = $this->db->table('tb_resep')
            ->where('id_produk', $idProduk)
            ->orderBy('nama_resep', 'ASC')
            ->get()->getResultArray();

        foreach ($headers as &$h) {
            $h['items'] = $this->db->table('tb_detail_resep d')
                ->select('d.id_bahan, d.jumlah_bahan, b.nama_bahan, b.satuan_bahan, b.stok_bahan, b.harga_bahan')
                ->join('tb_bahan b', 'b.id_bahan = d.id_bahan', 'left')
                ->where('d.id_resep', $h['id_resep'])
                ->get()->getResultArray();
        }

        return $headers;
    }
}