<?php
/**
 * Shortcodes template file.
 * Brief description of the styles in this file
 *
 * @since   3.0.4
 * @package AdvancedAds\Pro
 * @author  Advanced Ads <info@wpadvancedads.com>
 */

namespace AdvancedAds\Pro;

use Advanced_Ads_Pro_Utils;
use AdvancedAds\Framework\Interfaces\Integration_Interface;

defined( 'ABSPATH' ) || exit;

/**
 * Shortcodes class.
 */
class Shortcodes implements Integration_Interface {

	/**
	 * Hook into WordPress.
	 *
	 * @return void
	 */
	public function hooks(): void {
		add_action( 'wp_loaded', [ $this, 'remove_shortcodes' ] );
		add_action( 'wp_loaded', [ $this, 'add_shortcodes' ] );
	}

	/**
	 * Remove free plugin's shortcodes
	 *
	 * @return void
	 */
	public function remove_shortcodes() {
		remove_shortcode( 'the_ad' );
		remove_shortcode( 'the_ad_group' );
		remove_shortcode( 'the_ad_placement' );
	}

	/**
	 * Add new shortcodes
	 *
	 * @return void
	 */
	public function add_shortcodes() {
		add_shortcode( 'the_ad', [ $this, 'render' ] );
		add_shortcode( 'the_ad_group', [ $this, 'render' ] );
		add_shortcode( 'the_ad_placement', [ $this, 'render' ] );
	}

	/**
	 * Shortcode to include ad in frontend
	 *
	 * @param array       $atts shortcode attributes.
	 * @param string|null $content content between the shortcode tags.
	 * @param string|null $shortcode shortcode name.
	 *
	 * @return string content as generated by the shortcode.
	 */
	public function render( $atts, $content = null, $shortcode = null ) {
		$hash = [
			'the_ad'           => 'render_ad',
			'the_ad_group'     => 'render_group',
			'the_ad_placement' => 'render_placement',
		];

		$shortcode = $hash[ $shortcode ] ?? 'render_ad';

		return $this->do_shortcode( $atts, $shortcode );
	}

	/**
	 * Create shortcode output.
	 *
	 * @param array  $atts Shortcode attributes.
	 * @param string $func Function to be executed by the shortcode.
	 *
	 * @return string content as generated by the shortcode.
	 */
	private function do_shortcode( $atts, $func ) {
		$blog_id = absint( $atts['blog_id'] ?? 0 );

		if ( $blog_id && is_multisite() && get_current_blog_id() !== $blog_id ) {
			if ( ! Advanced_Ads_Pro_Utils::blog_exists( $blog_id ) ) {
				return '';
			}

			switch_to_blog( $blog_id );
			$result = call_user_func( [ wp_advads()->shortcodes, $func ], $atts );
			restore_current_blog();

			return $result;
		}

		return call_user_func( [ wp_advads()->shortcodes, $func ], $atts );
	}
}
