<?php

namespace GriffinForms\Frontend\Security\FieldValidations;

use DateTimeImmutable;
use Exception;

/**
 * Class InputDate
 * Handles basic PHP validation for date fields in GriffinForms.
 */
class InputDate extends Format
{
    /**
     * Perform server-side validation for the input date field.
     *
     * @param string $value The date value submitted by the user.
     */
    protected function customValidate($value, $iteration_index)
    {
        // Ensure the provided date is valid
        if (!$this->isValidDate($value)) {
            $this->addError(__('Invalid date format.', 'griffinforms-form-builder'));
            return;
        }
    }

    /**
     * Checks if a given date string is valid.
     *
     * @param string $value The date string to check.
     * @return bool True if valid, false otherwise.
     */
    private function isValidDate($value)
    {
        try {
            new DateTimeImmutable($value);
            return true;
        } catch (Exception $e) {
            return false;
        }
    }
}