<?php
/**
 * This class handles box model control css output.
 *
 * @package Typer\Customizer
 *
 * @since 1.0.0
 */

namespace Seventhqueen\Typer\Customizer\Modules\Kirki_Extend\Output;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Overrides Kirki CSS output.
 *
 * @since 1.0.0
 * @ignore
 * @access private
 *
 * @package Typer\Customizer
 */
class Box_Model extends \Seventhqueen\Typer\Customizer\Modules\Kirki_Extend\Base\Output {

	/**
	 * Processes a single item from the `output` array.
	 *
	 * @param array $output Defined single output.
	 * @param array $value Settings value.
	 *
	 * @SuppressWarnings(PHPMD.NPathComplexity)
	 * @since 1.0.0
	 *
	 */
	protected function apply_output( $output, $value ) {

		$output = wp_parse_args(
			$output,
			[
				'element'     => '',
				'property'    => '',
				'media_query' => 'global',
				'prefix'      => '',
				'suffix'      => '',
			]
		);

		if ( ! is_array( $value ) ) {
			return;
		}

		if ( ! isset( $this->field['exclude'] ) ) {
			$this->field['exclude'] = [];
		}

		$positions    = [ 'top', 'right', 'bottom', 'left' ];
		$default_unit = \Seventhqueen\Typer\Customizer\Control\Box_Model::$default_unit;

		if ( ! in_array( 'margin', $this->field['exclude'], true ) ) {
			$margin_unit = isset( $value['margin_unit'] ) ? $value['margin_unit'] : $default_unit;

			foreach ( $positions as $position ) {
				// Accepts non-numeric value such as 'auto'.
				if ( array_key_exists( 'margin_' . $position, $value ) ) {
					$property = 'margin-' . $position;
					$unit     = is_numeric( $value[ 'margin_' . $position ] ) ? $margin_unit : '';

					$this->styles[ $output['media_query'] ][ $output['element'] ][ $property ] = $output['prefix'] . $this->process_property_value( $property, $value[ 'margin_' . $position ] ) . $unit . $output['suffix'];
				}
			}
		}

		if ( ! in_array( 'padding', $this->field['exclude'], true ) ) {
			$padding_unit = isset( $value['padding_unit'] ) ? $value['padding_unit'] : $default_unit;

			foreach ( $positions as $position ) {
				// Does not accept any value that is not numeric.
				if ( array_key_exists( 'padding_' . $position, $value ) && is_numeric( $value[ 'padding_' . $position ] ) ) {
					$property = 'padding-' . $position;
					$unit     = $padding_unit;

					$this->styles[ $output['media_query'] ][ $output['element'] ][ $property ] = $output['prefix'] . $this->process_property_value( $property, $value[ 'padding_' . $position ] ) . $unit . $output['suffix'];
				}
			}
		}
	}
}
