<?php

namespace HelpGent\App\Support\Element\Fields;

defined( 'ABSPATH' ) || exit;

use HelpGent\App\Support\Element\Element;
use HelpGent\App\Support\Element\Summary\Chart;
use HelpGent\WpMVC\RequestValidator\Validator;
use stdClass;
use WP_REST_Request;

class RatingStar extends Element {

    use Chart;

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

    public function validate( WP_REST_Request $wp_rest_request, Validator $validator, array $element ) {
        $rating_amount = $element['attributes']['rating_amount'];

        $rule = '';

        if ( '1' === $element['attributes']['required'] ) {
            $rule = 'required|';
        }

        $validator->validate(
            [
                $element['element_type'] => "{$rule}integer|max:{$rating_amount}",
            ], false
        );

        static::throw_validator_errors( $validator );
    }

    protected function get_element_summary( stdClass $form, array $element ) {
        add_filter( "helpgent_chart_summery", [$this, 'prepare_chart_summery'], 10, 2 );

        return $this->get_answers( $form, $element );
    }

    public function prepare_chart_summery( array $value, array $element ) {
        $value['rating_icon']   = helpgent_get_nested_value( 'attributes.rating_icon', $element );
        $value['rating_amount'] = helpgent_get_nested_value( 'attributes.rating_amount', $element );

        return $value;
    }
}