<?php
declare(strict_types=1);

namespace App\Modules\Rentals\Models;

use App\Core\Model;
use App\Core\App;

class RentalInvoice extends Model
{
    protected static string $table      = 'rental_invoices';
    protected static string $primaryKey = 'id';
    protected static bool   $timestamps = true;
    protected static bool   $softDelete = false;
    protected static bool   $autoTrackAuthor = true;

    protected static array $fillable = [
        'invoice_number',
        'contract_id',
        'entity_id',
        'period_start',
        'period_end',
        'due_date',
        'base_amount',
        'utilities_amount',
        'vat_amount',
        'late_fee_amount',
        'total_amount',
        'status',
        'paid_at',
        'payment_id',
        'notes',
        'journal_entry_id',
    ];

    public static function getStatuses(): array
    {
        return [
            'unpaid'    => 'غير مدفوعة',
            'paid'      => 'مدفوعة',
            'overdue'   => 'متأخرة',
            'cancelled' => 'ملغاة',
        ];
    }

    public static function getStatusLabel(string $status): string
    {
        return self::getStatuses()[$status] ?? $status;
    }

    public static function getStatusColor(string $status): string
    {
        return match ($status) {
            'paid'      => '#059669',
            'overdue'   => '#DC2626',
            'cancelled' => '#6B7280',
            default     => '#D97706',
        };
    }

    public static function generateNumber(): string
    {
        $prefix = 'RI-' . date('Ym') . '-';
        $db     = App::getInstance()->db();
        $row    = $db->selectOne(
            "SELECT invoice_number FROM rental_invoices WHERE invoice_number LIKE ? ORDER BY id DESC LIMIT 1",
            [$prefix . '%']
        );

        $nextSeq = 1;
        if ($row) {
            $number  = is_object($row) ? $row->invoice_number : ($row['invoice_number'] ?? '');
            $parts   = explode('-', (string) $number);
            $nextSeq = ((int) ($parts[2] ?? 0)) + 1;
        }

        return $prefix . str_pad((string) $nextSeq, 4, '0', STR_PAD_LEFT);
    }

    public static function getForContract(int $contractId): array
    {
        return static::query()
            ->where('contract_id', '=', $contractId)
            ->orderBy('period_start', 'ASC')
            ->get();
    }
}
