<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Invoice extends Model
{
    protected $fillable = [
        'lease_id', 'invoice_number', 'month', 'rent_amount',
        'electricity_amount', 'maintenance_amount', 'other_charges',
        'other_charges_description', 'total_amount', 'due_date', 'status',
    ];

    protected $casts = [
        'rent_amount' => 'decimal:2',
        'electricity_amount' => 'decimal:2',
        'maintenance_amount' => 'decimal:2',
        'other_charges' => 'decimal:2',
        'total_amount' => 'decimal:2',
        'due_date' => 'date',
    ];

    public function lease(): BelongsTo
    {
        return $this->belongsTo(Lease::class);
    }

    public function payments(): HasMany
    {
        return $this->hasMany(Payment::class);
    }

    // Total paid against this invoice
    public function getTotalPaidAttribute(): float
    {
        return (float) $this->payments()->sum('amount_paid');
    }

    // Balance remaining
    public function getBalanceRemainingAttribute(): float
    {
        return (float) $this->total_amount - $this->total_paid;
    }

    // Scope: pending invoices
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    // Scope: overdue invoices
    public function scopeOverdue($query)
    {
        return $query->where('status', 'overdue');
    }

    // Scope: paid invoices
    public function scopePaid($query)
    {
        return $query->where('status', 'paid');
    }

    // Generate next invoice number
    public static function generateInvoiceNumber(): string
    {
        $prefix = Setting::get('invoice_prefix', 'RD');
        $year = date('Y');
        $lastInvoice = static::where('invoice_number', 'like', "{$prefix}-{$year}-%")
            ->orderByDesc('invoice_number')
            ->first();

        if ($lastInvoice) {
            $lastNumber = (int) substr($lastInvoice->invoice_number, -4);
            $nextNumber = $lastNumber + 1;
        } else {
            $nextNumber = 1;
        }

        return sprintf('%s-%s-%04d', $prefix, $year, $nextNumber);
    }
}
