<?php

namespace HelpGent\App\Support\Element\Fields;

defined( 'ABSPATH' ) || exit;

use Exception;
use HelpGent\App\Support\Element\Element;
use HelpGent\App\Support\Element\Summary\Pagination;
use HelpGent\WpMVC\RequestValidator\Validator;
use WP_REST_Request;

class Date extends Element {

    use Pagination;

    public static function get_key(): string {
        return 'date';
    }

    public function validate( WP_REST_Request $wp_rest_request, Validator $validator, array $element ) {
        $attributes      = $element['attributes'];
        $selected_format = $attributes['date_format'];
        $formats         = $this->formats();

        if ( empty( $formats[$selected_format] ) ) {
            throw new Exception( esc_html__( 'Date format not found.', 'helpgent' ) );
        }

        $format   = str_replace( '-', $attributes['separator'], $formats[$selected_format] );
        $required = $attributes['required'];

        $rule = '';

        if ( '1' === $required ) {
            $rule = 'required|';
        }

        $validator->validate(
            [
                self::get_key() => "{$rule}date:{$format}",
            ], false
        );

        static::throw_validator_errors( $validator );
    }

    private function formats() {
        return [
            'en-US' => 'm-d-Y',
            'en-GB' => 'd-m-Y',
            'en-ZA' => 'Y-m-d',
        ];
    }
}