<?php

namespace App\Models;

use CodeIgniter\Model;

/**
 * Model untuk tb_detail_pembelian_bahan (DETAIL item per transaksi).
 */
class DetailPembelianBahanModel extends Model
{
    protected $table      = 'tb_detail_pembelian_bahan';
    protected $primaryKey = 'id_detail_pembelian_bahan';
    protected $returnType = 'array';

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

    // Tidak pakai soft delete — kalau header dihapus, detail CASCADE DELETE via FK
    protected $useSoftDeletes = false;

    protected $allowedFields = [
        'id_pembelian_bahan',
        'id_bahan',
        'jumlah_bahan',
        'harga_satuan_bahan',
        'subtotal_bahan',
    ];

    // ── Ambil semua detail milik 1 transaksi ──────────────────────────────────
    public function getByPembelian(int $idPembelian): array
    {
        return $this->db->table('tb_detail_pembelian_bahan d')
            ->select('d.*, b.nama_bahan, b.satuan_bahan')
            ->join('tb_bahan b', 'b.id_bahan = d.id_bahan', 'left')
            ->where('d.id_pembelian_bahan', $idPembelian)
            ->get()
            ->getResultArray();
    }

    // ── Hapus semua detail milik 1 transaksi (cascade manual jika perlu) ─────
    public function deleteByPembelian(int $idPembelian): void
    {
        $this->where('id_pembelian_bahan', $idPembelian)->delete();
    }
}