<?php
/**
 * Main theme functions.
 * is_rtl() ? esc_html__( 'Left', 'nevo' ) : esc_html__( 'Right', 'nevo' ),
 * @package Nevo
 */

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

class Nevo {

	static $_instance;
	static $version;
	static $theme_url;
	static $theme_name;
	static $theme_author;
	static $path;

	/**
	 * @var Nevo_Customizer
	 */
	public $customizer = null;

	/**
	 * Add functions to hooks
	 */
	function init_hooks() {
		add_action( 'after_setup_theme', array( $this, 'theme_setup' ) );
		add_action( 'widgets_init', array( $this, 'register_sidebars' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'scripts' ) );
		add_filter( 'excerpt_more', array( $this, 'excerpt_more' ) );
	}

	/**
	 * Filter the excerpt "read more" string.
	 *
	 * @param string $more "Read more" excerpt string.
	 *
	 * @return string (Maybe) modified "read more" excerpt string.
	 */
	function excerpt_more( $more ) {
		if ( is_admin() ) {
			return $more;
		} else {
			return ' &hellip;';
		}
	}

	/**
	 * Main Nevo Instance.
	 *
	 * Ensures only one instance of Nevo is loaded or can be loaded.
	 *
	 * @return Nevo Main instance.
	 */
	static function get_instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance    = new self();
			$theme              = wp_get_theme();
			self::$version      = $theme->get( 'Version' );
			self::$theme_url    = $theme->get( 'ThemeURI' );
			self::$theme_name   = $theme->get( 'Name' );
			self::$theme_author = $theme->get( 'Author' );
			self::$path         = get_template_directory();

			self::$_instance->init();
		}

		return self::$_instance;
	}

	/**
	 * Get data from method of property
	 *
	 * @param string $key
	 *
	 * @return bool|mixed
	 */
	function get( $key ) {
		if ( method_exists( $this, 'get_' . $key ) ) {
			return call_user_func_array( array( $this, 'get_' . $key ), array() );
		} elseif ( property_exists( $this, $key ) ) {
			return $this->{$key};
		}

		return false;
	}


	/**
	 * 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 content_width() {
		$GLOBALS['content_width'] = apply_filters( 'nevo_content_width', 843 );
	}
	
	/**
	 * Check if WooCommerce plugin activated
	 *
	 * @see WooCommerce
	 * @see wc
	 *
	 * @return bool
	 */
	function is_woocommerce_active() {
		return class_exists( 'WooCommerce' ) || function_exists( 'wc' );
	}

	/**
	 * 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 theme_setup() {
		/*
		 * Make theme available for translation.
		 * Translations can be filed in the /languages/ directory.
		 * If you're building a theme based on nevo, use a find and replace
		 * to change 'nevo' to the name of your theme in all the template files.
		 */
		load_theme_textdomain( 'nevo', get_template_directory() . '/languages' );

		// Add theme support for various features.
		add_theme_support( 'automatic-feed-links' );
		add_theme_support( 'post-thumbnails' );
		add_theme_support( 'post-formats', array( 'aside', 'image', 'video', 'quote', 'link', 'status' ) );
		add_theme_support( 'woocommerce' );
		add_theme_support( 'title-tag' );
		add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption', 'script', 'style' ) );
		add_theme_support( 'customize-selective-refresh-widgets' );
		add_theme_support( 'align-wide' );
		add_theme_support( 'responsive-embeds' );
		// Make theme available for translation.
		load_theme_textdomain( 'nevo' );
		// Add support for starter content ( wp preview ).
		if ( apply_filters( 'nevo_starter_content', false ) ) {
			$nevo_starter_content = new Nevo_Starter_Content();
			add_theme_support( 'starter-content', $nevo_starter_content->get() );
		}

		$color_palette = '';//nevo_get_editor_color_palette();

		if ( ! empty( $color_palette ) ) {
			add_theme_support( 'editor-color-palette', $color_palette );
		}

		add_theme_support(
			'custom-logo',
			array(
				'height' => 70,
				'width' => 250,
				'flex-height' => true,
				'flex-width' => true,
			)
		);

		// Register primary menu.
		register_nav_menus(
			array(
				'primary' 	=> __( 'Primary Menu', 'nevo' ),
				'mobile' 	=> __( 'Mobile Menu', 'nevo' ),
				'footer' 	=> __( 'Footer Menu', 'nevo' ),
			)
		);

		/**
		 * Set the content width to something large
		 * We set a more accurate width in nevo_smart_content_width()
		 */
		global $content_width;
		if ( ! isset( $content_width ) ) {
			$content_width = 1200; /* pixels */
		}
		// Enable block styles.
		add_theme_support( 'wp-block-styles' );
		
		// Add editor styles to the block editor.
		add_theme_support( 'editor-styles' );

		$editor_styles = apply_filters(
			'nevo_editor_styles',
			array(
				'assets/css/admin/block-editor.css',
			)
		);
		add_editor_style( $editor_styles );
	}

	/**
	 * Register sidebars area.
	 *
	 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
	 */
	function register_sidebars() {
		$widgets = array(
			'sidebar-1' => __( 'Right Sidebar', 'nevo' ),
			'sidebar-2' => __( 'Left Sidebar', 'nevo' ),
			'footer-1' => __( 'Footer Widget 1', 'nevo' ),
			'footer-2' => __( 'Footer Widget 2', 'nevo' ),
			'footer-3' => __( 'Footer Widget 3', 'nevo' ),
			'footer-4' => __( 'Footer Widget 4', 'nevo' ),
			'footer-5' => __( 'Footer Widget 5', 'nevo' ),
			'footer-6' => __( 'Footer Widget 6', 'nevo' ),
		);
		if ( class_exists( 'Nevo_Pro' ) ) {
			$widgets['home-sidebar-1'] = __( 'Homepage Right Sidebar', 'nevo' );
			$widgets['home-sidebar-2'] = __( 'Homepage Left Sidebar', 'nevo' );
		}
		foreach ( $widgets as $id => $name ) {
			register_sidebar(
				array(
					'name'          => $name,
					'id'            => $id,
					'before_widget' => '<aside id="%1$s" class="widget inner-padding %2$s">',
					'after_widget'  => '</aside>',
					'before_title'  => apply_filters( 'nevo_start_widget_title', '<div class="heading-title"><h2 class="widget-title general-title">' ),
					'after_title'   => apply_filters( 'nevo_end_widget_title', '</h2></div>' ),
				)
			);
		}
		register_widget( 'Nevo_Advertisement_Image' );
		register_widget( 'nevo_recent_comments_widget' );
		register_widget( 'nevo_posts_list_featured_widget' );
	}
	
	/**
	 * Get asset suffix `.min` or empty if WP_DEBUG enabled
	 *
	 * @return string
	 */
	function get_asset_suffix() {
		$suffix = '.min';
		
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG && apply_filters( 'nevo_empty_suffix', false ) ) {
			$suffix = '';
		}

		return $suffix;
	}

	/**
	 * Enqueue scripts and styles.
	 */
	function scripts() {
				
		$dir_uri = get_template_directory_uri();
		
		$suffix = $this->get_asset_suffix();

		if ( ! class_exists( 'Nevo_Font_Icons' ) ) {
			require_once get_template_directory() . '/inc/classes/class-customizer-icons.php';
		}
		if ( apply_filters( 'nevo_load_bootstrap_icons', false ) ) {
			Nevo_Font_Icons::get_instance()->enqueue();
		}
		
		do_action( 'nevo/load/scripts' );
		
		$rtl = '';
		$css_file = $dir_uri . "/assets/css/main{$suffix}.css";
		if ( is_rtl() ) {
			$rtl 	  = '-rtl';
			$css_file = $dir_uri . "/assets/css/main-rtl{$suffix}.css";
		}
		
		$css_files = apply_filters(
			'nevo/theme/css',
			array(
				'google-font' => Nevo_Customizer_Auto_CSS::get_instance()->get_font_url(),
				'style'       => $css_file,
			)
		);
		foreach ( $css_files as $id => $url ) {
			$deps = array();
			if ( is_array( $url ) ) {
				$arg = wp_parse_args(
					$url,
					array(
						'deps' => array(),
						'url'  => '',
						'ver'  => self::$version,
					)
				);
				wp_enqueue_style( 'nevo-' . $id, $arg['url'], $arg['deps'], $arg['ver'] );
			} elseif ( $url ) {
				wp_enqueue_style( 'nevo-' . $id, $url, $deps, self::$version );
			}
		}
		$js_files = apply_filters(
			'nevo/theme/js',
			array(
				'nevo-theme' => array(
					'url' => esc_url( $dir_uri ) . '/assets/js/main' . $suffix . '.js',
					'ver' => self::$version,
				),
			)
		);
		foreach ( $js_files as $id => $arg ) {
			$deps = array();
			$ver  = '';
			if ( is_array( $arg ) ) {
				$arg = wp_parse_args(
					$arg,
					array(
						'deps' => '',
						'url'  => '',
						'ver'  => '',
					)
				);

				$deps = $arg['deps'];
				$url  = $arg['url'];
				$ver  = $arg['ver'];
			} else {
				$url = $arg;
			}

			if ( ! $ver ) {
				$ver = self::$version;
			}

			wp_enqueue_script( $id, $url, $deps, $ver, true );
		}
		
		if ( is_child_theme() && apply_filters( 'nevo_load_child_theme_stylesheet', true ) ) {
			wp_enqueue_style( 'nevo-child', get_stylesheet_uri(), array( 'nevo-style' ), filemtime( get_stylesheet_directory() . '/style.css' ), 'all' );
		}

		if ( is_singular() && ( comments_open() || '0' != get_comments_number() ) ) {
			wp_enqueue_style( 'nevo-comments', $dir_uri . "/assets/css/components/comments{$rtl}{$suffix}.css", array(), self::$version, 'all' );
		}
		if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
			$translation = array(
				'lang' => apply_filters('nevo_comment_length_message', esc_html__('Please enter at least 10 characters before submitting the comment.', 'nevo')),
				'ajaxurl' => admin_url('admin-ajax.php')
			);
			wp_enqueue_script( 'comment-reply' );
			wp_enqueue_script( 'comment-input', $dir_uri . "/assets/js/comment{$suffix}.js", array(), self::$version, true );
			wp_localize_script('comment-input', 'translation', $translation);
		}
		// Localize script
		wp_localize_script( 'nevo-theme', 'Nevo_JS', apply_filters( 'nevo_frontend_localize_script', array(
			'css_media_queries' => Nevo_Customizer_Auto_CSS::get_instance()->media_queries,
			'is_rtl'            => is_rtl(),
			'breakpoints' => array(
				'mobile'  => 576,
				'tablet'  => 768,
				'desktop' => 992,
			),
		) ) );
		
		wp_add_inline_style( 'nevo-style', Nevo_Customizer_Auto_CSS::get_instance()->auto_css() );
		
		do_action( 'nevo/theme/scripts' );
	}

	private function includes() {
		$files = array(
			'/inc/main.php',
			
			// Builder
			'/inc/classes/class-customizer-builder.php',
			'/inc/classes/class-header-builder.php',
			'/inc/classes/class-footer-builder.php',
			
			'/inc/widgets/abstract-nevo-widget.php',
			'/inc/widgets/recent-comments.php',
			'/inc/widgets/advertisement-image.php',
			'/inc/widgets/posts-list-featured-image.php',
			/**
			 * Load our theme structure
			 */
			'/inc/structure/header.php',
			'/inc/structure/loops.php',
			'/inc/structure/archives.php',
			'/inc/structure/post-meta.php',
			'/inc/structure/sidebars.php',
			'/inc/structure/no-results.php',
			'/inc/structure/404.php',
			'/inc/structure/comments.php',
			'/inc/structure/footer.php',
			/**
			 * Load our theme classes
			 */
			'/inc/classes/class-html-attributes.php',
			'/inc/classes/class-customizer.php',
			'/inc/classes/class-svg-icons.php',
			'/inc/classes/class-related-posts.php',
			'/inc/classes/class-widget-visibility.php',
			
			/**
			 * Load our theme functions
			 */
			'/inc/functions/general.php',
			'/inc/functions/helpers.php',
			'/inc/functions/markup.php',
			'/inc/functions/menu.php',
			'/inc/functions/post.php',
			'/inc/functions/social.php',
			'/inc/functions/compat.php',
			'/inc/functions/comments.php',
		);

		foreach ( $files as $file ) {
			require_once self::$path . $file;
		}

		$this->load_configs();
		$this->load_compatibility();
		$this->admin_includes();
		// Custom categories walker class.
		if ( ! is_admin() ) {
			require_once self::$path . '/inc/classes/class-categories-walker.php';
		}
		
	}

	/**
	 * Load admin files
	 *
	 * @since 0.0.1
	 *
	 * @return void
	 */
	private function admin_includes() {
		if ( ! is_admin() ) {
			return;
		}
		global $pagenow;
		
		$files = array(
			'/inc/admin/dashboard.php',
			'/inc/admin/block-editor.php',
			'/inc/admin/class-nevo-fields.php',
		);
		if ( in_array( $pagenow, array( 'post.php', 'post-new.php', 'edit-tags.php', 'term.php' ) ) ) {
			$files[] = '/inc/admin/class-nevo-metabox.php';
		}

		foreach ( $files as $file ) {
			require_once self::$path . $file;
		}

	}

	/**
	 * Load configs
	 */
	private function load_configs() {

		$config_files = array(
			'layouts',
			'upsell',
			'blogs',
			'color',
			'styling',
			'typography',
			'breadcrumb',
			'other-page',
			'page-header',
			'blogs-single',
			'related-posts',
			
			'header/mobile-menu',
			'header/header-top',
			'header/header-main',
			'header/header-bottom',
			'header/logo',
			'header/account',
			'header/button',
			'header/html',
			'header/toggle-menu',
			'header/search',
			'header/social-icons',
			
			'footer/footer-top',
			'footer/footer-middle',
			'footer/footer-bottom',
			'footer/footer-social',
			'footer/button',
			'footer/html',
			'footer/copyright',
			'footer/scrolltop',

		);

		$path = get_template_directory();
		
		// Load site configs.
		foreach ( $config_files as $f ) {
			$file = $path . "/inc/configs/{$f}.php";
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

	}

	/**
	 * Load site compatibility supports
	 */
	private function load_compatibility() {
		$compatibility_files = array();
		if ( $this->is_woocommerce_active() ) {
			$compatibility_files = array(
				'/inc/woocommerce/class-nevo-woocommerce.php',
			);
		}
		$path = get_template_directory();
		
		foreach ( $compatibility_files as $f ) {
			require_once self::$path . $f;
		}
	}

	function is_using_post() {
		$use = false;
		if ( is_singular() ) {
			$use = true;
		} else {
			if ( is_front_page() && is_home() ) {
				$use = false;
			} elseif ( is_front_page() ) {
				// static homepage.
				$use = true;
			} elseif ( is_home() ) {
				// blog page.
				$use = true;
			} else {
				if ( $this->is_woocommerce_active() ) {
					if ( is_shop() ) {
						$use = true;
					}
				}
			}
		}

		return $use;
	}

	function is_blog() {
		$is_blog = false;
		if ( is_front_page() && is_home() ) {
			$is_blog = true;
		} elseif ( is_front_page() ) { //phpcs:ignore
			// static homepage.
		} elseif ( is_home() ) {
			$is_blog = true;
		}

		return $is_blog;
	}

	function get_current_post_id() {
		$id = get_the_ID();
		if ( is_front_page() && is_home() ) {
			$id = false;
		} elseif ( is_front_page() ) {
			// Static homepage.
			$id = get_option( 'page_on_front' );
		} elseif ( is_home() ) {
			// Blog page.
			$id = get_option( 'page_for_posts' );
		} else {
			if ( $this->is_woocommerce_active() ) {
				if ( is_shop() ) {
					$id = wc_get_page_id( 'shop' );
				}
			}
		}

		return $id;
	}

	function init() {
		$this->init_hooks();
		$this->includes();
		$this->customizer = Nevo_Customizer::get_instance();
		$this->customizer->init();
		do_action( 'nevo_init' );
	}

	function get_setting( $id, $device = 'desktop', $key = null ) {
		return Nevo_Customizer::get_instance()->get_setting( $id, $device, $key );
	}

	function get_media( $value, $size = null ) {
		return Nevo_Customizer::get_instance()->get_media( $value, $size );
	}

	function get_setting_tab( $name, $tab = null ) {
		return Nevo_Customizer::get_instance()->get_setting_tab( $name, $tab );
	}

	function get_post_types( $_builtin = true ) {
		if ( 'all' === $_builtin ) {
			$post_type_args = array(
				'publicly_queryable' => true,
			);
		} else {
			$post_type_args = array(
				'publicly_queryable' => true,
				'_builtin'           => $_builtin,
			);
		}

		$_post_types = get_post_types( $post_type_args, 'objects' );

		$post_types = array();

		foreach ( $_post_types as $post_type => $object ) {
			$post_types[ $post_type ] = array(
				'name'          => $object->label,
				'singular_name' => $object->labels->singular_name,
			);
		}

		return $post_types;
	}
}