<?php

namespace App\Models;

use CodeIgniter\Model;

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

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

    public function getForInvoice(int $invoiceId): array
    {
        return $this->where('customer_invoice_id', $invoiceId)
            ->orderBy('sort_order', 'ASC')
            ->orderBy('id', 'ASC')
            ->findAll();
    }

    public function replaceForInvoice(int $invoiceId, array $lines): array
    {
        $this->where('customer_invoice_id', $invoiceId)->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 = [
                'customer_invoice_id' => $invoiceId,
                '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)];
    }
}
