<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'goods_receipt_id', 'item_code', 'item_name', 'quantity', 'unit', 'notes',
        'sort_order', 'created_at',
    ];

    public function getForGoodsReceipt(int $goodsReceiptId): array
    {
        return $this->where('goods_receipt_id', $goodsReceiptId)
            ->orderBy('sort_order', 'ASC')
            ->orderBy('id', 'ASC')
            ->findAll();
    }

    public function replaceForGoodsReceipt(int $goodsReceiptId, array $lines): void
    {
        $this->where('goods_receipt_id', $goodsReceiptId)->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([
                'goods_receipt_id' => $goodsReceiptId,
                'item_code'        => trim((string) ($line['item_code'] ?? '')) ?: null,
                'item_name'        => $name,
                'quantity'         => (float) ($line['quantity'] ?? 1),
                'unit'             => trim((string) ($line['unit'] ?? '')) ?: 'pcs',
                'notes'            => trim((string) ($line['notes'] ?? '')) ?: null,
                'sort_order'       => $sort++,
                'created_at'       => $now,
            ]);
        }
    }
}
