<?php

namespace App\Models\Master;

use CodeIgniter\Model;

class MaklonModel extends Model
{
    protected $table         = 'tb_maklon';
    protected $primaryKey    = 'id_maklon';
    protected $returnType    = 'array';
    protected $protectFields = true;
    protected $allowedFields = [
        'nama_maklon', 'no_hp_maklon', 'alamat_maklon',
        'status_maklon', 'id_produk_terkait_maklon',
    ];
    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    public function getActive()
    {
        return $this->where('status_maklon', 'Aktif')->findAll();
    }

    // Ambil harga khusus per produk milik maklon ini
    public function getHargaKhusus(int $idMaklon): array
    {
        $rows = $this->db->query(
            "SELECT id_produk, harga_khusus FROM tb_harga_maklon WHERE id_maklon = ?",
            [$idMaklon]
        )->getResultArray();

        $map = [];
        foreach ($rows as $r) {
            $map[$r['id_produk']] = (float)$r['harga_khusus'];
        }
        return $map;
    }

    // Simpan harga khusus per produk (upsert)
    public function saveHargaKhusus(int $idMaklon, array $hargaPerProduk): void
    {
        $this->db->query(
            "DELETE FROM tb_harga_maklon WHERE id_maklon = ?",
            [$idMaklon]
        );

        foreach ($hargaPerProduk as $idProduk => $harga) {
            if ($harga > 0) {
                $this->db->query(
                    "INSERT INTO tb_harga_maklon (id_maklon, id_produk, harga_khusus)
                     VALUES (?, ?, ?)",
                    [$idMaklon, (int)$idProduk, (float)$harga]
                );
            }
        }
    }
}