<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Carbon;

class DownloadDateRangeRule implements ValidationRule
{
    protected Carbon $startDate;

    protected Carbon $endDate;

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!$this->validateDateString($value)) {
            $fail('Date range must be in the format YYYY/MM/DD to YYYY/MM/DD.');
            return;
        }

        if (!$this->startDate->isPast() || !$this->endDate->isPast()) {
            $fail('Date range cannot be in the future.');
            return;
        }

        if ($this->startDate->greaterThan($this->endDate)) {
            $fail('Start date must be before end date.');
        }
    }

    function validateDateString($dateString): bool
    {
        $regex = '/^(\d{4}\/\d{2}\/\d{2}) to (\d{4}\/\d{2}\/\d{2})$/';
        if (preg_match($regex, $dateString, $matches)) {
            $this->startDate = Carbon::parse($matches[1]);
            $this->endDate = Carbon::parse($matches[2]);
            return true;
        }
        return false;
    }


}
