<?php

namespace App\Models\Control;

use CodeIgniter\Model;

/**
 * Control DB. Line items for a platform `invoices` row — see
 * CreateInvoiceLineItemsTable.
 */
class InvoiceLineItemModel extends Model
{
    protected $table            = 'invoice_line_items';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = false; // created_at only, no updates — set explicitly on insert

    protected $allowedFields = [
        'invoice_id',
        'description',
        'amount',
        'created_at',
    ];

    protected $validationRules = [
        'invoice_id'  => 'required|integer',
        'description' => 'required|max_length[255]',
        'amount'      => 'required|decimal',
    ];

    public function forInvoice(int $invoiceId): array
    {
        return $this->where('invoice_id', $invoiceId)->orderBy('id', 'asc')->findAll();
    }

    public function addLine(int $invoiceId, string $description, string $amount): void
    {
        $this->insert([
            'invoice_id'  => $invoiceId,
            'description' => $description,
            'amount'      => $amount,
            'created_at'  => date('Y-m-d H:i:s'),
        ]);
    }
}
