<?php

namespace App\Models;

use CodeIgniter\Model;

class PackagingUnitModel extends Model
{
    use \App\Models\Traits\Auditable;

    protected $table         = 'packaging_unit';
    protected $primaryKey    = 'pu_idx';
    protected $returnType    = 'object';
    protected $useTimestamps = false;
    protected $allowedFields = [
        'pu_lg_idx', 'pu_bag_code', 'pu_bag_name',
        'pu_box_per_pack', 'pu_pack_per_sheet', 'pu_total_per_box',
        'pu_start_date', 'pu_end_date', 'pu_state',
        'pu_regdate', 'pu_moddate', 'pu_reg_mb_idx',
    ];

    /**
     * 동일 봉투코드에 행이 여러 개여도 최신 등록 1건만 사용.
     *
     * @return array<string, object>
     */
    public function latestActiveMapByBagCode(int $lgIdx): array
    {
        $rows = $this->where('pu_lg_idx', $lgIdx)
            ->where('pu_state', 1)
            ->orderBy('pu_regdate', 'DESC')
            ->orderBy('pu_idx', 'DESC')
            ->findAll();

        $map = [];
        foreach ($rows as $row) {
            $code = (string) ($row->pu_bag_code ?? '');
            if ($code === '' || isset($map[$code])) {
                continue;
            }
            $map[$code] = $row;
        }

        return $map;
    }
}
