<?php

namespace App\Models\Master;

use CodeIgniter\Model;

class ResellerModel extends Model
{
    protected $table         = 'tb_reseller';
    protected $primaryKey    = 'id_reseller';
    protected $returnType    = 'array';
    protected $protectFields = true;
    protected $allowedFields = [
        'nama_reseller', 'no_hp_reseller', 'alamat_reseller',
        'status_reseller', 'id_produk_terkait_reseller', 'link_reseller',
    ];
    protected $useTimestamps = false;

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

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

        // Return sebagai map: id_produk => harga_khusus
        $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 $idReseller, array $hargaPerProduk): void
    {
        // Hapus dulu semua harga lama reseller ini
        $this->db->query(
            "DELETE FROM tb_harga_reseller WHERE id_reseller = ?",
            [$idReseller]
        );

        // Insert harga baru
        foreach ($hargaPerProduk as $idProduk => $harga) {
            if ($harga > 0) {
                $this->db->query(
                    "INSERT INTO tb_harga_reseller (id_reseller, id_produk, harga_khusus)
                     VALUES (?, ?, ?)",
                    [$idReseller, (int)$idProduk, (float)$harga]
                );
            }
        }
    }
}