<?php

namespace App\Models;

use CodeIgniter\Model;

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

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

    public function getForDelivery(int $deliveryId): array
    {
        return $this->where('delivery_id', $deliveryId)
            ->orderBy('sort_order', 'ASC')
            ->orderBy('id', 'ASC')
            ->findAll();
    }

    public function replaceForDelivery(int $deliveryId, array $lines): void
    {
        $this->where('delivery_id', $deliveryId)->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([
                'delivery_id' => $deliveryId,
                '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,
            ]);
        }
    }
}
