<?php

namespace App\Models;

use CodeIgniter\Model;

class InvoiceModel extends Model
{
    protected $table         = 'invoices';
    protected $useTimestamps = false;
    protected $allowedFields = ['agency_id', 'invoice_number', 'subtotal', 'tax_percentage', 'tax_amount', 'total', 'currency', 'status', 'due_date', 'pdf_path', 'created_at'];

    public function forAgency(int $agencyId, int $page = 1, int $perPage = 20): array
    {
        $offset = ($page - 1) * $perPage;
        return $this->where('agency_id', $agencyId)->orderBy('created_at', 'DESC')->findAll($perPage, $offset);
    }

    public function nextInvoiceNumber(): string
    {
        $year = date('Y');
        $count = $this->like('invoice_number', "INV-{$year}-", 'after')->countAllResults() + 1;
        return sprintf('INV-%s-%05d', $year, $count);
    }
}
