<?php

namespace App\Models;

use CodeIgniter\Model;

class BahanModel extends Model
{
    protected $table            = 'tb_bahan';
    protected $primaryKey       = 'id_bahan';
    protected $returnType       = 'array';

    // Soft Delete
    protected $useSoftDeletes   = true;
    protected $deletedField     = 'deleted_at';

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

    protected $allowedFields    = [
        'kode_bahan',
        'nama_bahan',
        'satuan_bahan',
        'stok_bahan',
        'harga_bahan',
        'keterangan_bahan',
        'status_bahan',
    ];

    // ── Ambil semua bahan aktif (exclude soft-deleted) ───────────────────────
    public function getAllAktif(): array
    {
        return $this->where('status_bahan', 'aktif')
            ->orderBy('nama_bahan', 'ASC')
            ->findAll();
    }

    // ── Ambil semua (aktif + nonaktif, exclude soft-deleted) ─────────────────
    public function getAll(): array
    {
        return $this->orderBy('nama_bahan', 'ASC')->findAll();
    }

    // ── Ambil semua termasuk yang soft-deleted ───────────────────────────────
    public function getAllWithTrashed(): array
    {
        return $this->withDeleted()
            ->orderBy('nama_bahan', 'ASC')
            ->findAll();
    }

    // ── Ambil bahan yang soft-deleted saja ───────────────────────────────────
    public function getDeleted(): array
    {
        return $this->db->table($this->table)
            ->where('deleted_at IS NOT NULL', null, false)
            ->orderBy('deleted_at', 'DESC')
            ->get()
            ->getResultArray();
    }

    // ── Cek apakah kode sudah dipakai ────────────────────────────────────────
    public function isKodeTaken(string $kode, int $excludeId = 0): bool
    {
        $builder = $this->withDeleted()->where('kode_bahan', $kode);
        if ($excludeId > 0) {
            $builder->where('id_bahan !=', $excludeId);
        }
        return $builder->countAllResults() > 0;
    }

    // ── Toggle status aktif / nonaktif ───────────────────────────────────────
    public function toggleStatus(int $id): void
    {
        $row = $this->find($id);
        if (! $row) return;
        $newStatus = $row['status_bahan'] === 'aktif' ? 'nonaktif' : 'aktif';
        $this->update($id, ['status_bahan' => $newStatus]);
    }

    // ── Restore soft-deleted row ─────────────────────────────────────────────
    public function restore(int $id): bool
    {
        return $this->db->table($this->table)
            ->where($this->primaryKey, $id)
            ->update([$this->deletedField => null]);
    }

    // ── Tambah stok + update harga rata-rata tertimbang ──────────────────────
    public function addStokWithHarga(int $id, float $jumlah, float $harga): void
    {
        $row = $this->find($id);
        if (! $row) return;

        $stokLama  = (float) $row['stok_bahan'];
        $stokBaru  = $stokLama + $jumlah;

        $hargaBaru = $stokBaru > 0
            ? (($stokLama * (float) $row['harga_bahan']) + ($jumlah * $harga)) / $stokBaru
            : $harga;

        $this->update($id, [
            'stok_bahan'  => round($stokBaru, 3),
            'harga_bahan' => round($hargaBaru, 2),
        ]);
    }

    // ── Kurangi stok ─────────────────────────────────────────────────────────
    public function kurangiStok(int $id, float $jumlah): void
    {
        $row = $this->find($id);
        if (! $row) return;
        $stokBaru = max(0, (float) $row['stok_bahan'] - $jumlah);
        $this->update($id, ['stok_bahan' => round($stokBaru, 3)]);
    }

    // ── Ambil semua bahan + statistik pembelian & penggunaan ─────────────────
    // FIX: JOIN ke tb_detail_pembelian_bahan (bukan tb_pembelian_bahan)
    // karena kolom jumlah_bahan sudah pindah ke tabel detail
    public function getAllWithStats(): array
    {
        $sql = "
            SELECT
                b.*,
                COALESCE(SUM(td.jumlah_bahan), 0)        AS total_dibeli,
                COALESCE(SUM(tu.jumlah_penggunaan), 0)   AS total_dipakai
            FROM tb_bahan b
            LEFT JOIN tb_detail_pembelian_bahan td
                ON td.id_bahan = b.id_bahan
            LEFT JOIN tb_penggunaan_bahan tu
                ON tu.id_bahan = b.id_bahan AND tu.deleted_at IS NULL
            WHERE b.deleted_at IS NULL
            GROUP BY b.id_bahan
            ORDER BY b.nama_bahan ASC
        ";
        return $this->db->query($sql)->getResultArray();
    }
    
    public function getBahanAktif(): array
    {
        return $this->db->query(
            "SELECT id_bahan, nama_bahan, satuan_bahan, stok_bahan
         FROM tb_bahan
         WHERE status_bahan = 'aktif'
         ORDER BY nama_bahan ASC"
        )->getResultArray();
    }
}
