<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class RecurringInvoice extends Model
{
    use HasFactory;

    protected $fillable = [
        'customer_id',
        'title',
        'frequency',
        'start_date',
        'next_run_date',
        'end_date',
        'amount',
        'items',
        'notes',
        'is_active',
        'last_run_at',
    ];

    protected $casts = [
        'start_date' => 'date',
        'next_run_date' => 'date',
        'end_date' => 'date',
        'last_run_at' => 'datetime',
        'items' => 'array',
        'is_active' => 'boolean',
        'amount' => 'decimal:2',
    ];

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    /**
     * Calculate the next run date based on frequency.
     */
    public function calculateNextRunDate($fromDate)
    {
        $date = \Carbon\Carbon::parse($fromDate);

        switch ($this->frequency) {
            case 'daily':
                return $date->addDay();
            case 'weekly':
                return $date->addWeek();
            case 'monthly':
                return $date->addMonth();
            case 'quarterly':
                return $date->addMonths(3);
            case 'yearly':
                return $date->addYear();
            default:
                return $date->addMonth();
        }
    }
}
