<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class NumberSequence extends Model
{
    protected $fillable = [
        'name',
        'date',
        'current_number',
        'reset_type'
    ];

    protected $casts = [
        'date' => 'date',
        'current_number' => 'integer'
    ];

    /**
     * Get today's sequence for a given name
     */
    public static function getToday(string $name): self
    {
        $today = now()->format('Y-m-d');
        
        return self::firstOrCreate(
            [
                'name' => $name,
                'date' => $today
            ],
            ['current_number' => 0]
        );
    }

    /**
     * Increment and get next number
     */
    public static function getNext(string $name): int
    {
        $sequence = self::getToday($name);
        $sequence->increment('current_number');
        
        return $sequence->current_number;
    }

    /**
     * Reset sequence if needed
     */
    public function resetIfNeeded(): void
    {
        $today = now()->format('Y-m-d');
        
        if ($this->date->format('Y-m-d') !== $today) {
            $this->update([
                'date' => $today,
                'current_number' => 0
            ]);
        }
    }
}