<?php

namespace App\Models;

use App\Enums\Currency;
use App\Enums\RenewalStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Renewal extends Model
{
    use HasFactory;

    protected $fillable = [
        'client_id',
        'contract_start_date',
        'next_due_date',
        'domain_enabled',
        'domain_amount',
        'hosting_enabled',
        'hosting_amount',
        'currency',
        'status',
        'paid_date',
        'paid_note',
    ];

    protected function casts(): array
    {
        return [
            'currency'            => Currency::class,
            'status'              => RenewalStatus::class,
            'domain_enabled'      => 'boolean',
            'hosting_enabled'     => 'boolean',
            'contract_start_date' => 'date',
            'next_due_date'       => 'date',
            'paid_date'           => 'date',
            'domain_amount'       => 'decimal:2',
            'hosting_amount'      => 'decimal:2',
        ];
    }

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

    // Monto total: dominio + hosting (solo los habilitados)
    public function getTotalAmountAttribute(): float
    {
        $total = 0;
        if ($this->domain_enabled) {
            $total += (float) $this->domain_amount;
        }
        if ($this->hosting_enabled) {
            $total += (float) $this->hosting_amount;
        }
        return $total;
    }

    // Días hasta vencimiento (negativo = vencido)
    public function getDaysUntilDueAttribute(): int
    {
        return (int) now()->diffInDays($this->next_due_date, false);
    }
}
