<?php

namespace App\Models;

use CodeIgniter\Model;

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

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

    public function getForBill(int $billId): array
    {
        return $this->where('vendor_bill_id', $billId)
            ->orderBy('sort_order', 'ASC')
            ->orderBy('id', 'ASC')
            ->findAll();
    }

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