<?php

namespace App\Models;

use CodeIgniter\Model;

class RfqSupplierModel extends Model
{
    protected $table         = 'rfq_suppliers';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;

    protected $allowedFields = [
        'rfq_id', 'supplier_id', 'created_at',
    ];

    public function getSupplierIdsForRfq(int $rfqId): array
    {
        $rows = $this->where('rfq_id', $rfqId)->findAll();
        $ids  = [];
        foreach ($rows as $row) {
            $ids[] = (int) $row['supplier_id'];
        }

        return $ids;
    }

    public function replaceForRfq(int $rfqId, array $supplierIds): void
    {
        $this->where('rfq_id', $rfqId)->delete();
        $now  = date('Y-m-d H:i:s');
        $seen = [];

        foreach ($supplierIds as $sid) {
            $id = (int) $sid;
            if ($id <= 0 || isset($seen[$id])) {
                continue;
            }
            $seen[$id] = true;
            $this->insert([
                'rfq_id'      => $rfqId,
                'supplier_id' => $id,
                'created_at'  => $now,
            ]);
        }
    }
}
