<?php

namespace App\Models;

use CodeIgniter\Model;

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

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

    public function getForRfq(int $rfqId): array
    {
        return $this->where('rfq_id', $rfqId)
            ->orderBy('sort_order', 'ASC')
            ->orderBy('id', 'ASC')
            ->findAll();
    }

    public function replaceForRfq(int $rfqId, array $lines): array
    {
        $this->where('rfq_id', $rfqId)->delete();
        $now = date('Y-m-d H:i:s');
        $sort = 0;
        $subtotal = 0.0;
        $saved = [];

        foreach ($lines as $line) {
            $name = trim((string) ($line['item_name'] ?? ''));
            if ($name === '') {
                continue;
            }
            $qty   = (float) ($line['quantity'] ?? 1);
            $price = (float) ($line['unit_price'] ?? 0);
            $total = round($qty * $price, 2);
            $subtotal += $total;

            $row = [
                'rfq_id'      => $rfqId,
                'item_code'   => trim((string) ($line['item_code'] ?? '')) ?: null,
                'item_name'   => $name,
                'description' => trim((string) ($line['description'] ?? '')) ?: null,
                'quantity'    => $qty,
                'unit'        => trim((string) ($line['unit'] ?? '')) ?: 'pcs',
                'unit_price'  => $price,
                'line_total'  => $total,
                'sort_order'  => $sort++,
                'created_at'  => $now,
            ];
            $this->insert($row);
            $saved[] = $row;
        }

        return ['lines' => $saved, 'subtotal' => round($subtotal, 2)];
    }
}
