<?php

namespace App\Rules;

use Carbon\Carbon;
use Carbon\Exceptions\InvalidFormatException;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Translation\PotentiallyTranslatedString;

class ValidSqlDate implements ValidationRule {
    /**
     * Run the validation rule.
     *
     * @param string $attribute
     * @param mixed $value
     * @param Closure(string): PotentiallyTranslatedString $fail
     */
    public function validate( string $attribute, mixed $value, Closure $fail ): void {
        if ( $value != '' ) {
            try {
                $date = Carbon::createFromFormat( 'Y-m-d', $value );

                if ( $date->greaterThan( Carbon::createFromFormat( 'Y-m-d', '2038-01-01' ) ) ) {
                    $fail( __( "Date can't be greater than Jan 1, 2038" ) );
                } elseif ( $date->lessThan( Carbon::createFromFormat( 'Y-m-d', '1970-01-01' ) ) ) {
                    $fail( __( "Date can't be less than Jan 1, 1970" ) );
                }
            } catch ( InvalidFormatException $e ) {
                $fail( __( "Invalid :attribute date" ) );
            }
        }
    }
}
