<?php

namespace App\Rules;

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

class ValidSqlDateTime 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 H:i:s', $value );

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