<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'price_list_id', 'item_code', 'item_name', 'description',
        'unit', 'unit_price', 'sort_order', 'created_at',
    ];

    public function getForList(int $priceListId): array
    {
        return $this->where('price_list_id', $priceListId)
            ->orderBy('sort_order', 'ASC')
            ->orderBy('id', 'ASC')
            ->findAll();
    }

    public function replaceForList(int $priceListId, array $lines): void
    {
        $this->where('price_list_id', $priceListId)->delete();
        $now = date('Y-m-d H:i:s');
        $sort = 0;
        foreach ($lines as $line) {
            $name = trim((string) ($line['item_name'] ?? ''));
            if ($name === '') {
                continue;
            }
            $this->insert([
                'price_list_id' => $priceListId,
                'item_code'     => trim((string) ($line['item_code'] ?? '')) ?: null,
                'item_name'     => $name,
                'description'   => trim((string) ($line['description'] ?? '')) ?: null,
                'unit'          => trim((string) ($line['unit'] ?? '')) ?: 'pcs',
                'unit_price'    => (float) ($line['unit_price'] ?? 0),
                'sort_order'    => $sort++,
                'created_at'    => $now,
            ]);
        }
    }
}
