<?php
/**
 * Shapely functions and definitions.
 *
 * @link    https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package Shapely
 *
 * Theme metadata (version, Requires at least, Tested up to, Requires PHP) lives
 * in style.css, which is the only file WordPress reads it from. It was also
 * duplicated here, and the two copies had already drifted apart -- do not
 * reintroduce it.
 */

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

// Ensure WordPress is loaded
if ( ! function_exists( 'add_action' ) ) {
	die( 'WordPress is not loaded properly.' );
}

if ( ! defined( 'SHAPELY_VERSION' ) ) {
	$shapely_theme = wp_get_theme( get_template() );
	/**
	 * Theme version, used to bust asset caches on update.
	 *
	 * Every enqueue previously omitted a version, so WordPress fell back to its
	 * own release number and browsers kept serving stale CSS/JS after a theme
	 * update.
	 */
	define( 'SHAPELY_VERSION', $shapely_theme->get( 'Version' ) ? $shapely_theme->get( 'Version' ) : '1.0.0' );
	unset( $shapely_theme );
}

/*
 * Load required files. Each of these was previously required twice (here and
 * again at the bottom of this file); require_once made the second pass a no-op,
 * so the duplicate block has been removed.
 *
 * Custom customizer controls are loaded from within inc/customizer.php.
 */
require_once get_template_directory() . '/inc/template-tags.php';
require_once get_template_directory() . '/inc/extras.php';
require_once get_template_directory() . '/inc/customizer.php';
require_once get_template_directory() . '/inc/jetpack.php';
require_once get_template_directory() . '/inc/class-wp-bootstrap-navwalker.php';
require_once get_template_directory() . '/inc/socialnav.php';
require_once get_template_directory() . '/inc/class-shapely-related-posts.php';
require_once get_template_directory() . '/inc/class-shapely.php';
require_once get_template_directory() . '/inc/class-shapely-builder.php';
require_once get_template_directory() . '/inc/block-editor.php';
require_once get_template_directory() . '/inc/class-shapely-migrations.php';

if ( ! defined( 'SHAPELY_SETUP_LOADED' ) ) {
	define( 'SHAPELY_SETUP_LOADED', true );
}

// Initialize theme setup
if ( ! function_exists( 'shapely_setup' ) ) :
	/**
	 * Sets up theme defaults and registers support for various WordPress features.
	 *
	 * Note that this function is hooked into the after_setup_theme hook, which
	 * runs before the init hook. The init hook is too late for some features, such
	 * as indicating support for post thumbnails.
	 */
	function shapely_setup() {
		/*
		 * Make theme available for translation.
		 * Translations can be filed in the /languages/ directory.
		 */
		load_theme_textdomain( 'shapely', get_template_directory() . '/languages' );

		// Add default posts and comments RSS feed links to head.
		add_theme_support( 'automatic-feed-links' );

		/**
		 * Add support for the custom logo functionality
		 */
		add_theme_support(
			'custom-logo',
			array(
				'height'      => 55,
				'width'       => 135,
				'flex-width'  => true,
				'flex-height' => true,
			)
		);

		add_theme_support(
			'custom-header',
			apply_filters(
				'shapely_custom_header_args',
				array(
					'default-image'      => '',
					'default-text-color' => '000000',
					'width'              => 1900,
					'height'             => 225,
					'flex-width'         => true,
				)
			)
		);

		/*
		 * Let WordPress manage the document title.
		 * By adding theme support, we declare that this theme does not use a
		 * hard-coded <title> tag in the document head, and expect WordPress to
		 * provide it for us.
		 */
		add_theme_support( 'title-tag' );

		/*
		 * Enable support for Post Thumbnails on posts and pages.
		 *
		 * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
		 */
		add_theme_support( 'post-thumbnails' );

		// This theme uses wp_nav_menu() in one location.
		register_nav_menus(
			array(
				'primary'     => esc_html__( 'Primary', 'shapely' ),
				'social-menu' => esc_html__( 'Social Menu', 'shapely' ),
			)
		);

		/*
		 * Switch default core markup for search form, comment form, and comments
		 * to output valid HTML5.
		 */
		add_theme_support(
			'html5',
			array(
				'search-form',
				'comment-form',
				'comment-list',
				'gallery',
				'caption',
				// Drop the legacy type="text/css" / type="text/javascript" attributes.
				'style',
				'script',
				'navigation-widgets',
			)
		);

		/*
		 * Block editor support. Without responsive-embeds, embedded iframes
		 * overflow their column on narrow viewports.
		 */
		add_theme_support( 'responsive-embeds' );
		add_theme_support( 'align-wide' );

		/*
		 * Core's default block styles. Without this, blocks that rely on them
		 * -- separators, the gallery, quote variations -- fall back to
		 * unstyled markup on the front end.
		 */
		add_theme_support( 'wp-block-styles' );

		/*
		 * Make the editor canvas resemble the front end. Enqueued rather than
		 * inlined so it is cached and overridable by a child theme.
		 */
		add_editor_style( 'assets/css/editor-style.css' );

		// Set up the WordPress core custom background feature.
		add_theme_support(
			'custom-background',
			apply_filters(
				'shapely_custom_background_args',
				array(
					'default-color' => 'ffffff',
					'default-image' => '',
				)
			)
		);

		/**
		 * Enable support for Post Thumbnails on posts and pages.
		 *
		 * @link http://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails
		 */
		add_theme_support( 'post-thumbnails' );
		add_image_size( 'shapely-full', 1110, 530, true );
		add_image_size( 'shapely-featured', 730, 350, true );
		add_image_size( 'shapely-grid', 350, 300, true );

		add_theme_support( 'woocommerce' );
		add_theme_support( 'wc-product-gallery-zoom' );
		add_theme_support( 'wc-product-gallery-lightbox' );
		add_theme_support( 'wc-product-gallery-slider' );

		add_theme_support( 'customize-selective-refresh-widgets' );

		// Enable Shortcodes in widgets
		add_filter( 'widget_text', 'do_shortcode' );
	}
endif;
add_action( 'after_setup_theme', 'shapely_setup' );

/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 *
 * Priority 0 to make it available to lower priority callbacks.
 *
 * @global int $content_width
 */
function shapely_content_width() {
	$GLOBALS['content_width'] = apply_filters( 'shapely_content_width', 1140 );
}

add_action( 'after_setup_theme', 'shapely_content_width', 0 );

/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function shapely_widgets_init() {
	register_sidebar(
		array(
			'id'            => 'sidebar-1',
			'name'          => esc_html__( 'Sidebar', 'shapely' ),
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		)
	);

	register_sidebar(
		array(
			'id'            => 'sidebar-home',
			'name'          => esc_html__( 'Homepage', 'shapely' ),
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		)
	);

	for ( $i = 1; $i < 5; $i ++ ) {
		register_sidebar(
			array(
				'id'            => 'footer-widget-' . $i,
				'name'          => sprintf( esc_html__( 'Footer Widget %s', 'shapely' ), $i ),
				'description'   => esc_html__( 'Used for footer widget area', 'shapely' ),
				'before_widget' => '<div id="%1$s" class="widget %2$s">',
				'after_widget'  => '</div>',
				'before_title'  => '<h2 class="widget-title">',
				'after_title'   => '</h2>',
			)
		);
	}

	if ( shapely_is_woocommerce_activated() ) {
		register_sidebar(
			array(
				'id'            => 'shop-sidebar',
				'name'          => esc_html__( 'Shop Sidebar', 'shapely' ),
				'before_widget' => '<div id="%1$s" class="widget %2$s">',
				'after_widget'  => '</div>',
				'before_title'  => '<h2 class="widget-title">',
				'after_title'   => '</h2>',
			)
		);
	}

}

add_action( 'widgets_init', 'shapely_widgets_init' );

/**
 * Hides the custom post template for pages on WordPress 4.6 and older
 *
 * @param array $post_templates Array of page templates. Keys are filenames, values are translated names.
 *
 * @return array Filtered array of page templates.
 */
function shapely_exclude_page_templates( $post_templates ) {

	if ( version_compare( $GLOBALS['wp_version'], '4.7', '<' ) ) {
		unset( $post_templates['page-templates/full-width.php'] );
		unset( $post_templates['page-templates/no-sidebar.php'] );
		unset( $post_templates['page-templates/sidebar-left.php'] );
		unset( $post_templates['page-templates/sidebar-right.php'] );
	}

	return $post_templates;
}

add_filter( 'theme_page_templates', 'shapely_exclude_page_templates' );

/**
 * Enqueue scripts and styles.
 */
function shapely_scripts() {
	$uri = get_template_directory_uri();

	// Add Bootstrap default CSS
	wp_enqueue_style( 'shapely-bootstrap', $uri . '/assets/css/bootstrap.min.css', array(), '3.3.7' );

	/*
	 * Registered under a theme-specific handle rather than the generic
	 * 'font-awesome'. WordPress deduplicates by handle, so whichever plugin
	 * registers 'font-awesome' first wins and every later enqueue is silently
	 * a no-op. Elementor ships Font Awesome 4.7 under exactly that handle, so
	 * on any site running it the theme's Font Awesome 6 never loaded at all --
	 * and the theme's fa-brands / fa-solid classes do not exist in 4.x, which
	 * is why the social, search and menu icons rendered as blank boxes.
 *
 * Versioned with SHAPELY_VERSION, not the Font Awesome version. The latter
 * never changes when the bundled file does, and this stylesheet is served
 * cache-control: immutable for a year -- a corrected copy would not have
 * reached a single returning visitor or CDN edge.
	 */
	wp_enqueue_style( 'shapely-font-awesome', $uri . '/assets/css/fontawesome6/all.min.css', array(), SHAPELY_VERSION );

	// Add Google Fonts
	wp_enqueue_style( 'shapely-fonts', 'https://fonts.googleapis.com/css?family=Raleway:100,300,400,500,600,700&display=swap', array(), null );

	// Add slider CSS
	wp_enqueue_style( 'shapely-flexslider', $uri . '/assets/css/flexslider.css', array(), SHAPELY_VERSION );

	//Add custom theme css
	wp_enqueue_style( 'shapely-style', get_stylesheet_uri(), array(), SHAPELY_VERSION );

	//Add custom placeholder image css
	wp_enqueue_style( 'shapely-custom', $uri . '/assets/css/custom.css', array(), SHAPELY_VERSION );

	// rtl.css is emitted automatically by core's locale_stylesheet() on wp_head.

	wp_enqueue_script( 'shapely-skip-link-focus-fix', $uri . '/assets/js/skip-link-focus-fix.js', array(), SHAPELY_VERSION, true );

	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}

	if ( post_type_exists( 'jetpack-portfolio' ) ) {
		wp_enqueue_script( 'jquery-masonry' );
	}

	/*
	 * Restores the .bind()/.unbind()/.delegate()/.undelegate() aliases that
	 * jQuery 4 removes and FlexSlider 2.x still calls. No-op on jQuery 3.x.
	 */
	wp_enqueue_script( 'shapely-jquery-compat', $uri . '/assets/js/jquery-compat.js', array( 'jquery' ), SHAPELY_VERSION, true );

	// Add slider JS
	wp_enqueue_script( 'shapely-flexslider', $uri . '/assets/js/flexslider.min.js', array( 'jquery', 'shapely-jquery-compat' ), '2.7.2', true );

	if ( is_page_template( 'page-templates/template-home.php' ) || is_page_template( 'page-templates/template-widget.php' ) ) {
		wp_enqueue_script( 'shapely-parallax', $uri . '/assets/js/parallax.min.js', array( 'jquery' ), SHAPELY_VERSION, true );
	}
	/**
	 * OwlCarousel Library
	 */
	wp_enqueue_script( 'shapely-owl-carousel', $uri . '/assets/js/owl-carousel/owl.carousel.min.js', array( 'jquery' ), '2.3.4', true );
	wp_enqueue_style( 'shapely-owl-carousel', $uri . '/assets/js/owl-carousel/owl.carousel.min.css', array(), '2.3.4' );
	wp_enqueue_style( 'shapely-owl-carousel-theme', $uri . '/assets/js/owl-carousel/owl.theme.default.css', array(), '2.3.4' );

	wp_enqueue_script(
		'shapely-scripts', $uri . '/assets/js/shapely-scripts.js', array(
			'jquery',
			'imagesloaded',
		), SHAPELY_VERSION, true
	);

	/**
	 * @since 1.2.2
	 */
	wp_localize_script(
		'shapely-scripts', 'ShapelyAdminObject',
		array(
			'sticky_header' => get_theme_mod( 'shapely_sticky_header', 1 ),
		)
	);
}

add_action( 'wp_enqueue_scripts', 'shapely_scripts' );

/**
 * Warm up the Google Fonts connection before the stylesheet is requested.
 *
 * Saves a DNS + TLS round trip on the render-blocking font request.
 */
function shapely_resource_hints( $hints, $relation_type ) {
	if ( 'preconnect' === $relation_type && wp_style_is( 'shapely-fonts', 'enqueued' ) ) {
		$hints[] = array(
			'href'        => 'https://fonts.gstatic.com',
			'crossorigin' => 'anonymous',
		);
	}

	return $hints;
}

add_filter( 'wp_resource_hints', 'shapely_resource_hints', 10, 2 );

/*
 * Bootstrap the theme classes.
 *
 * The block that previously sat here re-required all nine inc/ files (already
 * loaded with require_once at the top of this file) and then instantiated
 * Shapely a second and third time -- once on `init` and once inside
 * shapely_init_plugins(). Each extra instance re-registered every admin hook
 * and spun up another Epsilon_Framework, so the customizer assets were
 * enqueued three times over.
 *
 * shapely_init_plugins() itself was dead: it looped $recommended_plugins
 * looking for a 'callback' key that no entry has ever defined.
 */

// Initialize the builder class
if ( class_exists( 'Shapely_Builder' ) ) {
	add_action(
		'after_setup_theme',
		function () {
			Shapely_Builder::get_instance();
		},
		5
	);
}

// Init the Shapely class (admin / customizer only -- see Shapely::__construct).
if ( class_exists( 'Shapely' ) ) {
	add_action(
		'init',
		function () {
			$GLOBALS['shapely'] = Shapely::get_instance();
		},
		0
	);
}
