<?php

namespace App\Models;

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

class BackupSchedule extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'type',
        'frequency',
        'time',
        'day_of_week',
        'day_of_month',
        'enabled',
        'retention_days',
        'options',
        'last_run_at',
        'next_run_at',
    ];

    protected $casts = [
        'options' => 'array',
        'enabled' => 'boolean',
        'last_run_at' => 'datetime',
        'next_run_at' => 'datetime',
    ];

    /**
     * Calculează următoarea dată de rulare
     */
    public function calculateNextRun(): void
    {
        $time = $this->time;
        $now = now();

        switch ($this->frequency) {
            case 'daily':
                $next = $now->copy()->setTimeFromTimeString($time);
                if ($next->isPast()) {
                    $next->addDay();
                }
                break;

            case 'weekly':
                $next = $now->copy()->setTimeFromTimeString($time);
                $next->next($this->day_of_week);
                if ($next->isPast()) {
                    $next->addWeek();
                }
                break;

            case 'monthly':
                $next = $now->copy()->setTimeFromTimeString($time)->day($this->day_of_month);
                if ($next->isPast()) {
                    $next->addMonth();
                }
                break;

            default:
                $next = null;
        }

        $this->next_run_at = $next;
        $this->save();
    }

    /**
     * Verifică dacă programarea trebuie să ruleze
     */
    public function shouldRun(): bool
    {
        return $this->enabled &&
               $this->next_run_at &&
               $this->next_run_at->isPast();
    }

    /**
     * Marchează ca rulată
     */
    public function markAsRun(): void
    {
        $this->last_run_at = now();
        $this->calculateNextRun();
    }
}
