<?php

class HappyForms_Part_SelectExtended extends HappyForms_Part_Select {

	private $class_name = 'HappyForms_Part_SelectExtended';

	public function __construct() {
		parent::__construct();

		$this->hook();
	}

	public function hook() {
	
	}

	public function validate_value( $value, $part = array(), $form = array() ) {
		$validated_value = parent::validate_value( $value, $part, $form );
		
		if ( is_wp_error( $validated_value ) ) {
			return $validated_value;
		}

		return $this->validate_option_limits( $validated_value, $part, $form );
	}

	public function customize_enqueue_scripts( $deps = array() ) {
		parent::customize_enqueue_scripts( $deps );

		wp_enqueue_script(
			'part-select-extended',
			happyforms_get_plugin_url() . 'inc/assets/js/parts/part-select-extended.js',
			$deps, HAPPYFORMS_VERSION, true
		);
	}

	private function validate_option_limits( $value, $part, $form ) {
		foreach( $part['options'] as $o => $option ) {
			$option = wp_parse_args( $option, happyforms_upgrade_get_option_limiter()->get_option_fields() );

			if ( ! $option['limit_submissions'] || $o !== intval( $value ) ) {
				continue;
			}

			$limit = intval( $option['limit_submissions_amount'] );
			$form_id = $form['ID'];
			$option_id = $option['id'];
			$count = happyforms_get_message_controller()->count_by_option( $form_id, $option_id, $limit );

			if ( $count === $limit ) {
				return new WP_Error( 'error', happyforms_get_validation_message( 'field_invalid' ) );
			}
		}
		
		return $value;
	}

	public function get_part_options( $options, $part, $form ) {
		if ( is_customize_preview() ) {
			return $options;
		}

		if ( $this->type !== $part['type'] ) {
			return $options;
		}

		$options = array_filter( $options, function( $option ) use( $part, $form ) {
			$option = wp_parse_args( $option, $this->get_option_defaults() );

			if ( ! intval( $option['limit_submissions'] ) ) {
				return true;
			}

			$limit = intval( $option['limit_submissions_amount'] );
			$form_id = $form['ID'];
			$option_id = $option['id'];
			$count = happyforms_get_message_controller()->count_by_option( $form_id, $option_id, $limit );

			return $limit > $count;
		} );

		return $options;
	}

	public function submission_success( $submission, $form, $message ) {
		$parts = array();

		foreach( $form['parts'] as $part ) {
			if ( $this->type !== $part['type'] ) {
				continue;
			}

			foreach( $part['options'] as $o => $option ) {
				$option = wp_parse_args( $option, $this->get_option_defaults() );

				if ( ! $option['limit_submissions'] ) {
					continue;
				}

				$part_name = happyforms_get_part_name( $part, $form );

				if ( ! isset( $_REQUEST[$part_name] ) || ( $o !== intval( $_REQUEST[$part_name] ) ) ) {
					continue;
				}

				$meta_key = happyforms_get_option_counter_meta_key( $form['ID'], $option['id'] );
				update_post_meta( $message['ID'], $meta_key, 1 );
			}
		}
	}

}
