<?php

/**
 * Recipe Roundup Block.
 *
 * @since   2.1.6
 */

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

/**
 * Main Delicious_Recipe_Roundup Class.
 */
class Delicious_Recipe_Roundup {
	/**
	 * Block attributes.
	 *
	 * @since 2.1.6
	 */
	public static $attributes;

	/**
	 * Block settings.
	 *
	 * @since 2.1.6
	 */
	public static $settings;

	/**
	 * The Constructor.
	 */
	public function __construct() {
		$this->init_hooks();
	}

	/**
	 * Initializes the class hooks.
	 *
	 * @return void
	 */
	public function init_hooks() {
		add_action( 'init', array( $this, 'register_hooks' ) );
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_block_editor_assets' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_block_assets' ) );
	}

	/**
	 * Registers the recipe roundup block as a server-side rendered block.
	 *
	 * @return void
	 */
	public function register_hooks() {
		if ( ! function_exists( 'register_block_type' ) ) {
			return;
		}

		$attributes = array(
			'layout'                  => array(
				'type'    => 'string',
				'default' => 'list',
			),
			'gridItems'               => array(
				'type'    => 'number',
				'default' => 3,
			),
			'listAlignment'           => array(
				'type'    => 'string',
				'default' => 'left',
			),
			'content'                 => array(
				'type'    => 'array',
				'default' => array(),
			),
			'buttonLabel'             => array(
				'type'    => 'string',
				'default' => __( 'Make This Recipe', 'delicious-recipes-pro' ),
			),
			'openInNewTab'            => array(
				'type'    => 'boolean',
				'default' => true,
			),
			'relAttributes'           => array(
				'type'    => 'array',
				'default' => array(),
			),
			'enableRecipeCounter'     => array(
				'type'    => 'boolean',
				'default' => true,
			),
			'enableRecipeCookTime'    => array(
				'type'    => 'boolean',
				'default' => true,
			),
			'enableRecipeCourse'      => array(
				'type'    => 'boolean',
				'default' => true,
			),
			'enableRecipeDifficulty'  => array(
				'type'    => 'boolean',
				'default' => true,
			),
			'enableRecipeKeys'        => array(
				'type'    => 'boolean',
				'default' => true,
			),
			'enableRecipeRating'      => array(
				'type'    => 'boolean',
				'default' => true,
			),
			'enableRecipeDescription' => array(
				'type'    => 'boolean',
				'default' => true,
			),
			'enableRecipeButton'      => array(
				'type'    => 'boolean',
				'default' => true,
			),
			'addItemListSchema'       => array(
				'type'    => 'boolean',
				'default' => true,
			),
			'titleTag'                => array(
				'type'    => 'string',
				'default' => 'h3',
			),
			'fontSize'                => array(
				'type'  => 'object',
				'value' => 32,
				'unit'  => 'px',
				'min'   => 10,
				'max'   => 100,
			),
			'counterColor'            => array(
				'type'       => 'object',
				'text'       => '#000000',
				'background' => '#ffffff',
			),
			'counterFontSize'         => array(
				'type'  => 'object',
				'value' => 20,
				'unit'  => 'px',
				'min'   => 10,
				'max'   => 100,
			),
			'aspectRatio'             => array(
				'type'    => 'string',
				'default' => 'auto',
			),
			'shadow'                  => array(
				'type'    => 'object',
				'hOffset' => '0px',
				'vOffset' => '8px',
				'blur'    => '4px',
				'spread'  => '0px',
				'color'   => '#000',
			),
			'borderRadius'            => array(
				'type'  => 'object',
				'value' => 0,
				'unit'  => 'px',
				'min'   => 0,
				'max'   => 100,
			),
		);

		register_block_type(
			'delicious-recipes-pro/recipe-roundup',
			array(
				'attributes'      => $attributes,
				'render_callback' => array( $this, 'render' ),
			)
		);
	}

	/**
	 * Enqueue block editor assets.
	 *
	 * @return void
	 */
	public function enqueue_block_editor_assets() {
		$global_settings = delicious_recipes_get_global_settings();

		$license_details = get_option( 'delicious_recipes_pro_license' );
		$license_status  = '';
		if ( isset( $license_details ) && ! empty( $license_details ) ) {
			$license_status = isset( $license_details['license_status'] ) ? $license_details['license_status'] : '';
		}

		// Scripts.
		wp_enqueue_script( 'delicious-recipes-pro-roundup-block-js', plugin_dir_url( DELICIOUS_RECIPES_PRO_PLUGIN_FILE ) . 'assets/build/blocks.js', array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-components', 'wp-editor' ), DELICIOUS_RECIPES_PRO_VERSION, true );
		wp_localize_script(
			'delicious-recipes-pro-roundup-block-js',
			'DeliciousRecipesPro',
			array(
				'ajaxURL'        => admin_url( 'admin-ajax.php' ),
				'pluginURL'      => plugin_dir_url( DELICIOUS_RECIPES_PRO_PLUGIN_FILE ),
				'globalSettings' => $global_settings,
				'licenseStatus'  => 'valid' === $license_status ? true : false,
			)
		);

		// Styles.
		wp_enqueue_style(
			'delicious-recipes-pro-block-editor-css',
			plugin_dir_url( DELICIOUS_RECIPES_PRO_PLUGIN_FILE ) . 'assets/build/blocksEditorCSS.css',
			array( 'wp-edit-blocks' ),
			DELICIOUS_RECIPES_PRO_VERSION,
			'all'
		);

		wp_enqueue_style(
			'delicious-recipes-pro-block-css',
			plugin_dir_url( DELICIOUS_RECIPES_PRO_PLUGIN_FILE ) . 'assets/build/blocks.css',
			array( 'wp-editor' ),
			DELICIOUS_RECIPES_PRO_VERSION,
			'all'
		);
	}

	/**
	 * Enqueue block assets.
	 *
	 * @return void
	 */
	public function enqueue_block_assets() {
		if ( has_block( 'delicious-recipes-pro/recipe-roundup' ) ){
			wp_enqueue_style(
				'delicious-recipes-pro-block-css',
				plugin_dir_url( DELICIOUS_RECIPES_PRO_PLUGIN_FILE ) . 'assets/build/blocks.css',
				array(),
				DELICIOUS_RECIPES_PRO_VERSION,
				'all'
			);
		}
	}

	/**
	 * Renders the recipe roundup block.
	 *
	 * @param array $attributes The block attributes.
	 *
	 * @return string
	 */
	public function render( $attributes ) {
		self::$attributes = $attributes;
		ob_start();
		self::render_block( $attributes );
		if ( isset( $attributes['addItemListSchema'] ) && $attributes['addItemListSchema'] ) {
			echo self::get_json_ld( $attributes );
		}
		$output = ob_get_clean();
		return $output;
	}

	/**
	 * Returns the JSON-LD for a recipe-roundup block.
	 *
	 * @param array $attributes The attributes for the block.
	 * @return string The JSON-LD script tag for the recipe-roundup block.
	 */
	public function get_json_ld( $attributes ) {
		$itemListElement = array();
		foreach ( $attributes['content'] as $index => $recipe ) {
			$itemListElement[] = array(
				'@type'       => 'ListItem',
				'position'    => $index + 1,
				'url'         => $recipe['permalink'],
				'name'        => $recipe['name'],
				'image'       => $recipe['thumbnail'],
				'description' => $recipe['recipe_description'],
			);
		}
		$json_ld              = array(
			'@context'        => 'https://schema.org',
			'@type'           => 'ItemList',
			'itemListElement' => $itemListElement,
		);
		$json_ld_obj          = json_encode( $json_ld, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT );
		$structured_data_json = '';
		if ( ! empty( $json_ld ) ) {
			$structured_data_json = '<script type="application/ld+json">' . $json_ld_obj . '</script>';
		}
		return $structured_data_json;
	}


	/**
	 * Renders the recipe roundup block.
	 *
	 * @param array $attributes The block attributes.
	 *
	 * @return string
	 */
	public static function render_block( $attributes ) {
		$title_font_size = '';
		$counter_styles  = '';
		$shadow          = isset( $attributes['shadow'] ) ? $attributes['shadow'] : 'none';
		$box_shadow      = '';
		$aspect_ratio    = isset( $attributes['aspectRatio'] ) ? $attributes['aspectRatio'] : 'auto';
		if ( isset( $attributes['fontSize'] ) ) {
			if ( isset( $attributes['fontSize']['value'] ) && isset( $attributes['fontSize']['unit'] ) ) {
				$title_font_size = "font-size: {$attributes['fontSize']['value']}{$attributes['fontSize']['unit']}";
			}
		}
		if ( isset( $attributes['counterColor'] ) ) {
			if ( isset( $attributes['counterColor']['text'] ) ) {
				$counter_styles .= "color: {$attributes['counterColor']['text']};";
			}
			if ( isset( $attributes['counterColor']['background'] ) ) {
				$counter_styles .= "background-color: {$attributes['counterColor']['background']};";
			}
		}
		if ( isset( $attributes['counterFontSize'] ) ) {
			if ( isset( $attributes['counterFontSize']['value'] ) && isset( $attributes['counterFontSize']['unit'] ) ) {
				$counter_styles .= "font-size: {$attributes['counterFontSize']['value']}{$attributes['counterFontSize']['unit']}";
			}
		}
		if ( isset( $shadow ) && isset( $shadow['enable'] ) && $shadow['enable'] ) {
			$postition  = isset( $shadow['position'] ) === 'inset' ? 'inset' : '';
			$h_offset   = isset( $shadow['horizontal']['value'] ) ? $shadow['horizontal']['value'] . 'px' : '0px';
			$v_offset   = isset( $shadow['vertical']['value'] ) ? $shadow['vertical']['value'] . 'px' : '0px';
			$blur       = isset( $shadow['blur']['value'] ) ? $shadow['blur']['value'] . 'px' : '0px';
			$spread     = isset( $shadow['spread']['value'] ) ? $shadow['spread']['value'] . 'px' : '0px';
			$color      = isset( $shadow['color'] ) ? $shadow['color'] : 'rgba(0, 0, 0, 0.8)';
			$box_shadow = "box-shadow: $postition $h_offset $v_offset $blur $spread $color";
		}
		?>
		<div class="wpd-recipe-roundup-items-container">
			<div class="wpd-recipe-roundup-items" data-layout=<?php echo $attributes['layout']; ?> data-grid-items=<?php echo $attributes['gridItems']; ?> data-list-alignment=<?php echo $attributes['listAlignment']; ?> <?php echo get_block_wrapper_attributes(); ?>>
				<?php
				$index  = 0;
				$layout = $attributes['layout'];
				foreach ( $attributes['content'] as $recipe ) {
					++$index;
					?>
					<div class="wpd-recipe-roundup-item" style="<?php echo $box_shadow; ?>">
						<div class="wpd-recipe">
							<figure class="wpd-recipe-image-wrap">
								<?php if ( isset( $attributes['enableRecipeCounter'] ) && ! empty( $attributes['enableRecipeCounter'] ) ) : ?>
									<span class='wpd-count' style="<?php echo esc_attr( $counter_styles ); ?>"><?php echo $index; ?></span>
								<?php endif; ?>
								<a href=<?php echo $recipe['permalink']; ?> target="<?php echo $attributes['openInNewTab'] ? '_blank' : ''; ?>" rel="<?php echo implode( ' ', $attributes['relAttributes'] ); ?>">
									<?php
									if ( isset( $recipe['thumbnail'] ) && ! empty( $recipe['thumbnail'] ) ) :
										$thumbnail = 'center' === $layout ? wp_get_attachment_image_url( $recipe['thumbnail_id'], 'full' ) : $recipe['thumbnail'];
										?>
										<img src="<?php echo $thumbnail; ?>" alt="<?php echo $recipe['name']; ?>" class="image" style="aspect-ratio: <?php echo esc_attr( $aspect_ratio ); ?> ; height: <?php echo 'auto' !== $aspect_ratio ? 'unset' : ''; ?>; " />
									<?php else : ?>
										<div class="image-placeholder"></div>
									<?php endif; ?>
								</a>
								<span class='dr-category'>
									<?php
									if ( isset( $recipe['recipe_keys'] ) && is_array( $recipe['recipe_keys'] ) && $attributes['enableRecipeKeys'] ) {
										foreach ( $recipe['recipe_keys'] as $recipe_key ) {
											$key = get_term_by( 'name', $recipe_key, 'recipe-key' );
											if ( $key ) {
												$recipe_key_metas = get_term_meta( $key->term_id, 'dr_taxonomy_metas', true );
												$key_svg          = isset( $recipe_key_metas['taxonomy_svg'] ) ? $recipe_key_metas['taxonomy_svg'] : '';
												$term_link        = get_term_link( $key, 'recipe-key' );
												if ( 'string' === gettype( $term_link ) ) {
													?>
													<a href="<?php echo esc_url( $term_link ); ?>" title="<?php echo esc_attr( $recipe_key ); ?>">
														<span class="dr-svg-icon">
															<?php delicious_recipes_get_tax_icon( $key ); ?>
														</span>
														<span class="cat-name">
															<?php echo $recipe_key; ?>
														</span>
													</a>
													<?php
												}
											}
										}
									}
									?>
								</span>
							</figure>
							<div class="dr-archive-details">
								<div class="wpd-meta-container">
									<?php
									if ( isset( $recipe['recipe_course'] ) && is_array( $recipe['recipe_course'] ) && $attributes['enableRecipeCourse'] ) {
										foreach ( $recipe['recipe_course'] as $course ) {
											$course      = ucfirst( $course );
											$course_term = get_term_by( 'name', $course, 'recipe-course' );
											if ( $course_term ) {
												$course_link = get_term_link( $course_term );
												if ( 'string' === gettype( $course_link ) ) {
													?>
														<a href="<?php echo esc_url( $course_link ); ?>" title="<?php echo esc_attr( $course ); ?>">
															<span><?php echo $course; ?></span>
														</a>
													<?php
												}
											}
										}
									}
									?>
								</div>
								<<?php echo $attributes['titleTag']; ?> class="wpd-recipe-title" style="<?php echo esc_attr( $title_font_size ); ?>">
									<a href=<?php echo $recipe['permalink']; ?> target="<?php echo $attributes['openInNewTab'] ? '_blank' : ''; ?>" rel="<?php echo implode( ' ', $attributes['relAttributes'] ); ?>">
										<?php echo $recipe['name']; ?>
									</a>
								</<?php echo $attributes['titleTag']; ?>>
								<?php if ( isset( $attributes['enableRecipeDescription'] ) && ! empty( $attributes['enableRecipeDescription'] ) ) : ?>
									<div class="wpd-recipe-content">
										<p>
											<?php
												$description = $recipe['recipe_description'];
												$description = strip_tags( $description );
											if ( strlen( $description ) > 150 ) {
												$description = substr( $description, 0, 150 );
												echo $description . '...';
											} else {
												echo $description;
											}
											?>
										</p>
									</div>
								<?php endif; ?>
								<div class="dr-entry-meta">
									<?php if ( $attributes['enableRecipeCookTime'] && isset( $recipe['total_time'] ) && ! empty( $recipe['total_time'] ) ) : ?>
										<span class='dr-title'>
											<svg class='icon' width="20" height="20" viewBox="0 0 20 20" fill="none" style="fill: none;" xmlns="http://www.w3.org/2000/svg">
												<path d="M9.99996 7.91699V11.2503L12.0833 12.5003M9.99996 4.16699C6.08794 4.16699 2.91663 7.33831 2.91663 11.2503C2.91663 15.1623 6.08794 18.3337 9.99996 18.3337C13.912 18.3337 17.0833 15.1623 17.0833 11.2503C17.0833 7.33831 13.912 4.16699 9.99996 4.16699ZM9.99996 4.16699V1.66699M8.33329 1.66699H11.6666M16.9408 4.66036L15.6908 3.41036L16.3158 4.03536M3.05914 4.66036L4.30914 3.41036L3.68414 4.03536" stroke="#F54748" stroke-width="1.67" stroke-linecap="round" stroke-linejoin="round" />
											</svg>
											<span class='dr-meta-title'><?php echo $recipe['total_time']; ?></span>
										</span>
									<?php endif; ?>
									<?php if ( $attributes['enableRecipeDifficulty'] && isset( $recipe['difficulty_level'] ) && ! empty( $recipe['difficulty_level'] ) ) : ?>
										<span class='dr-level'>
											<svg class='icon' width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
												<path d="M9.99959 8C9.68145 8 9.37635 8.10432 9.15139 8.29C8.92643 8.47568 8.80005 8.72752 8.80005 8.99012V17.4095C8.80005 17.6722 8.92648 17.9241 9.15152 18.1099C9.37656 18.2956 9.68179 18.4 10 18.4C10.3183 18.4 10.6235 18.2956 10.8486 18.1099C11.0736 17.9241 11.2 17.6722 11.2 17.4095V8.99012C11.2 8.86003 11.169 8.73122 11.1087 8.61104C11.0483 8.49087 10.9599 8.38168 10.8484 8.28973C10.7369 8.19778 10.6046 8.12486 10.4589 8.07515C10.3133 8.02544 10.1572 7.9999 9.99959 8Z" fill="#F54748" />
												<path d="M5.99959 10.4004C5.68145 10.4004 5.37634 10.5127 5.15139 10.7127C4.92643 10.9127 4.80005 11.1839 4.80005 11.4667V17.3336C4.80005 17.6166 4.92648 17.8879 5.15152 18.0879C5.37656 18.288 5.68179 18.4004 6.00005 18.4004C6.31831 18.4004 6.62353 18.288 6.84858 18.0879C7.07362 17.8879 7.20005 17.6166 7.20005 17.3336V11.4667C7.20005 11.3266 7.16899 11.1879 7.10865 11.0585C7.04831 10.929 6.95987 10.8115 6.84839 10.7124C6.7369 10.6134 6.60456 10.5349 6.45892 10.4813C6.31328 10.4278 6.1572 10.4003 5.99959 10.4004Z" fill="#F54748" />
												<path d="M1.99959 13.5996C1.68145 13.5996 1.37634 13.726 1.15139 13.951C0.926429 14.176 0.800049 14.4811 0.800049 14.7993V17.1995C0.800049 17.5178 0.926477 17.823 1.15152 18.0481C1.37656 18.2732 1.68179 18.3996 2.00005 18.3996C2.31831 18.3996 2.62353 18.2732 2.84858 18.0481C3.07362 17.823 3.20005 17.5178 3.20005 17.1995V14.7993C3.20005 14.6416 3.16899 14.4856 3.10865 14.34C3.04831 14.1944 2.95987 14.0621 2.84839 13.9507C2.7369 13.8392 2.60456 13.7509 2.45892 13.6907C2.31328 13.6304 2.15719 13.5995 1.99959 13.5996Z" fill="#F54748" />
												<path d="M13.9996 4C13.6815 4 13.3763 4.11234 13.1514 4.31231C12.9264 4.51228 12.8 4.7835 12.8 5.06631V17.3333C12.8 17.4734 12.8311 17.6121 12.8914 17.7415C12.9517 17.8709 13.0401 17.9885 13.1515 18.0876C13.263 18.1866 13.3952 18.2652 13.5408 18.3188C13.6864 18.3724 13.8425 18.4 14 18.4C14.1576 18.4 14.3137 18.3724 14.4593 18.3188C14.6049 18.2652 14.7371 18.1866 14.8486 18.0876C14.96 17.9885 15.0484 17.8709 15.1087 17.7415C15.169 17.6121 15.2 17.4734 15.2 17.3333V5.06631C15.2 4.92621 15.169 4.78748 15.1086 4.65806C15.0483 4.52864 14.9599 4.41105 14.8484 4.31203C14.7369 4.213 14.6046 4.13447 14.4589 4.08093C14.3133 4.0274 14.1572 3.99989 13.9996 4Z" fill="#F54748" />
												<path d="M17.9996 1.59961C17.6815 1.59961 17.3763 1.71757 17.1514 1.92754C16.9264 2.13751 16.8 2.4223 16.8 2.71924V17.2796C16.8 17.5766 16.9265 17.8615 17.1515 18.0716C17.3766 18.2816 17.6818 18.3996 18 18.3996C18.3183 18.3996 18.6235 18.2816 18.8486 18.0716C19.0736 17.8615 19.2 17.5766 19.2 17.2796V2.71924C19.2 2.57214 19.169 2.42647 19.1086 2.29058C19.0483 2.15468 18.9599 2.03122 18.8484 1.92724C18.7369 1.82326 18.6046 1.74081 18.4589 1.68459C18.3133 1.62837 18.1572 1.5995 17.9996 1.59961Z" fill="#F54748" />
											</svg>
											<span class='dr-meta-title'><?php echo ucfirst( $recipe['difficulty_level'] ); ?></span>
										</span>
									<?php endif; ?>
									<?php if ( $attributes['enableRecipeRating'] && isset( $recipe['rating'] ) && ! empty( $recipe['rating'] ) ) : ?>
										<span class='dr-rating'>
											<svg class='icon' width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
												<path d="M9 1.19375L11.2501 6.072C11.3958 6.3878 11.6951 6.60525 12.0404 6.64619L17.3752 7.27872L13.4311 10.9262C13.1757 11.1623 13.0614 11.5141 13.1292 11.8552L14.1762 17.1244L9.48844 14.5004C9.18497 14.3305 8.81503 14.3305 8.51156 14.5004L3.82382 17.1244L4.8708 11.8552C4.93858 11.5141 4.82426 11.1623 4.56892 10.9262L0.624763 7.27872L5.95957 6.64619C6.30493 6.60525 6.60422 6.3878 6.74989 6.072L9 1.19375Z" fill="#FFE28D" stroke="#FFC107" />
											</svg>
											<span class='dr-meta-title'>
												<?php echo $recipe['rating']; ?>
											</span>
										</span>
									<?php endif; ?>
								</div>
								<?php if ( $attributes['enableRecipeButton'] ) : ?>
									<div class="wpd-recipe-button-wrap">
										<a href="<?php echo esc_url( $recipe['permalink'] ); ?>" class="dr-btn btn-lg" target="<?php echo $attributes['openInNewTab'] ? '_blank' : ''; ?>" rel="<?php echo implode( ' ', $attributes['relAttributes'] ); ?>"><?php echo $attributes['buttonLabel']; ?></a>
									</div>
								<?php endif; ?>
							</div>
						</div>
					</div>
				<?php } ?>
			</div>
		</div>
		<?php
	}
}

$delicious_recipe_roundup = new Delicious_Recipe_Roundup();
