<?php
/**
 * NewsNation functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package NewsNation
 */
if (!defined('NEWSNATION_VERSION')) {
    // Replace the version number of the theme on each release.
    define('NEWSNATION_VERSION', '1.0.7');
}
if (!function_exists('newsnation_after_theme_support')):

    /**
     * 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 newsnation_after_theme_support()
    {

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

        // Custom background color.
        add_theme_support('custom-background', apply_filters('newsnation_custom_background_args', array(
            'default-color' => 'ffffff',
            'default-image' => '',
        )));

        // This variable is intended to be overruled from themes.
        // Open WPCS issue: {@link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/1043}.
        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
        $GLOBALS['content_width'] = apply_filters('newsnation_content_width', 1140);
        /*
         * 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');

        add_theme_support(
            'custom-logo',
            array(
                'height' => 120,
                'width' => 90,
                'flex-height' => true,
                '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');

        /*
         * 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',
                'script',
                'style',
            )
        );

        /*
         * Posts Format.
         *
         * https://wordpress.org/support/article/post-formats/
         */
        add_theme_support('post-formats', array(
            'video',
            'audio',
            'gallery',
            'quote',
            'image'
        ));

        // Woocommerce Support
        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');

        /*
         * Make theme available for translation.
         * Translations can be filed in the /languages/ directory.
         * If you're building a theme based on NewsNation, use a find and replace
         * to change 'newsnation' to the name of your theme in all the template files.
         */
        load_theme_textdomain('newsnation', get_template_directory() . '/languages');

        // Add support for full and wide align images.
        add_theme_support('align-wide');

        add_theme_support('responsive-embeds');

        add_theme_support('wp-block-styles');

    }
endif;
add_action('after_setup_theme', 'newsnation_after_theme_support');

/**
 * Register and Enqueue Styles.
 */
function newsnation_register_styles()
{

    $theme_version = wp_get_theme()->get('Version');

    $fonts_url = newsnation_fonts_url();
    if ($fonts_url) {

        require_once get_theme_file_path('assets/lib/custom/css/wptt-webfont-loader.php');
        wp_enqueue_style(
            'newsnation-google-fonts',
            wptt_get_webfont_url($fonts_url),
            array(),
            $theme_version
        );
    }

    wp_enqueue_style('sidr-nav', get_template_directory_uri() . '/assets/lib/sidr/css/jquery.sidr.dark.css');
    wp_enqueue_style('slick', get_template_directory_uri() . '/assets/lib/slick/css/slick.min.css');
    wp_enqueue_style('newsnation-style', get_stylesheet_uri(), array(), $theme_version);
    wp_style_add_data('newsnation-style', 'rtl', 'replace');

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

    wp_enqueue_script('imagesloaded');
    wp_enqueue_script('masonry');

    wp_enqueue_script('jquery-sidr', get_template_directory_uri() . '/assets/lib/sidr/js/jquery.sidr.min.js', array('jquery'), '', 1);
    wp_enqueue_script('slick', get_template_directory_uri() . '/assets/lib/slick/js/slick.min.js', array('jquery'), '', 1);
    wp_enqueue_script('marquee', get_template_directory_uri() . '/assets/lib/marquee/jquery.marquee.min.js', array('jquery'), '', 1);
    wp_enqueue_script('newsnation-ajax', get_template_directory_uri() . '/assets/lib/custom/js/ajax.js', array('jquery'), '', 1);
    wp_enqueue_script('newsnation-custom', get_template_directory_uri() . '/assets/lib/custom/js/custom.js', array('jquery'), '', 1);
    wp_enqueue_script('newsnation-pagination', get_template_directory_uri() . '/assets/lib/custom/js/pagination.js', array('jquery'), '', 1);

    $ajax_nonce = wp_create_nonce('newsnation_ajax_nonce');

    wp_localize_script(
        'newsnation-ajax',
        'newsnation_ajax',
        array(
            'ajax_url' => esc_url(admin_url('admin-ajax.php')),
            'ajax_nonce' => $ajax_nonce,

        )
    );

    // Global Query
    if (is_front_page()) {

        $posts_per_page = absint(get_option('posts_per_page'));
        $c_paged = (get_query_var('page')) ? absint(get_query_var('page')) : 1;
        $posts_args = array(
            'posts_per_page' => $posts_per_page,
            'paged' => $c_paged,
        );
        $posts_qry = new WP_Query($posts_args);
        $max = $posts_qry->max_num_pages;

    } else {
        global $wp_query;
        $max = $wp_query->max_num_pages;
        $c_paged = (get_query_var('paged') > 1) ? get_query_var('paged') : 1;
    }

    $newsnation_default = newsnation_get_default_theme_options();
    $newsnation_pagination_layout = get_theme_mod('newsnation_pagination_layout', $newsnation_default['newsnation_pagination_layout']);

    // Pagination Data
    wp_localize_script(
        'newsnation-pagination',
        'newsnation_pagination',
        array(
            'paged' => absint($c_paged),
            'maxpage' => absint($max),
            'nextLink' => next_posts($max, false),
            'ajax_url' => esc_url(admin_url('admin-ajax.php')),
            'loadmore' => esc_html__('Load More Posts', 'newsnation'),
            'nomore' => esc_html__('No More Posts', 'newsnation'),
            'loading' => esc_html__('Loading...', 'newsnation'),
            'pagination_layout' => esc_html($newsnation_pagination_layout),
            'ajax_nonce' => $ajax_nonce,
        )
    );

    global $post;
    $single_post = 0;
    $newsnation_ed_post_reaction = '';
    if (isset($post->ID) && isset($post->post_type) && $post->post_type == 'post') {

        $newsnation_ed_post_reaction = esc_html(get_post_meta($post->ID, 'newsnation_ed_post_reaction', true));
        $single_post = 1;

    }
    wp_localize_script(
        'newsnation-custom',
        'newsnation_custom',
        array(
            'single_post' => absint($single_post),
            'newsnation_ed_post_reaction' => esc_html($newsnation_ed_post_reaction),
            'next_svg' => newsnation_theme_svg('chevron-right', true),
            'prev_svg' => newsnation_theme_svg('chevron-left', true),
            'play' => newsnation_theme_svg('play', $return = true),
            'pause' => newsnation_theme_svg('pause', $return = true),
            'mute' => newsnation_theme_svg('mute', $return = true),
            'unmute' => newsnation_theme_svg('unmute', $return = true),
            'play_text' => esc_html__('Play', 'newsnation'),
            'pause_text' => esc_html__('Pause', 'newsnation'),
            'mute_text' => esc_html__('Mute', 'newsnation'),
            'unmute_text' => esc_html__('Unmute', 'newsnation'),
        )
    );

}

add_action('wp_enqueue_scripts', 'newsnation_register_styles');

/**
 * Admin enqueue script
 */
function newsnation_admin_scripts($hook)
{

    $current_screen = get_current_screen();
    wp_enqueue_style('newsnation-admin', get_template_directory_uri() . '/assets/lib/custom/css/admin.css');
    if ($current_screen->id != "widgets") {

        wp_enqueue_media();
        wp_enqueue_style('wp-color-picker');

        wp_enqueue_script('newsnation-admin', get_template_directory_uri() . '/assets/lib/custom/js/admin.js', array('jquery', 'wp-color-picker'), '', 1);

        $ajax_nonce = wp_create_nonce('newsnation_ajax_nonce');

        wp_localize_script(
            'newsnation-admin',
            'newsnation_admin',
            array(
                'ajax_url' => esc_url(admin_url('admin-ajax.php')),
                'ajax_nonce' => $ajax_nonce,
                'upload_image' => esc_html__('Choose Image', 'newsnation'),
                'use_image' => esc_html__('Select', 'newsnation'),
                'active' => esc_html__('Active', 'newsnation'),
                'deactivate' => esc_html__('Deactivate', 'newsnation'),
            )
        );

    }

    if ($current_screen->id === "widgets") {

        // Enqueue Script Only On Widget Page.
        wp_enqueue_media();
        wp_enqueue_script('newsnation-widget', get_template_directory_uri() . '/assets/lib/custom/js/widget.js', array('jquery'), '', 1);
    }

}

add_action('admin_enqueue_scripts', 'newsnation_admin_scripts');


if (!function_exists('newsnation_js_no_js_class')):

    // js no-js class toggle
    function newsnation_js_no_js_class()
    { ?>

        <script>document.documentElement.className = document.documentElement.className.replace('no-js', 'js');</script>

        <?php
    }

endif;

add_action('wp_head', 'newsnation_js_no_js_class');

/**
 * Register navigation menus uses wp_nav_menu in five places.
 */
function newsnation_menus()
{

    $locations = array(
        'newsnation-primary-menu' => esc_html__('Primary Menu', 'newsnation'),
        'newsnation-social-menu' => esc_html__('Social Menu', 'newsnation'),
    );

    register_nav_menus($locations);
}

add_action('after_setup_theme', 'newsnation_menus');


/**
 * Recommended Plugins
 */
require get_template_directory() . '/assets/lib/tgmpa/recommended-plugins.php';
require get_template_directory() . '/classes/class-svg-icons.php';
require get_template_directory() . '/inc/customizer/customizer.php';
require get_template_directory() . '/classes/class-walker-menu.php';
require get_template_directory() . '/inc/mega-menu/megamenu-custom-fields.php';
require get_template_directory() . '/assets/lib/custom/css/style.php';
require get_template_directory() . '/inc/mega-menu/walkernav.php';
require get_template_directory() . '/inc/custom-header.php';
require get_template_directory() . '/inc/single-related-posts.php';
require get_template_directory() . '/inc/custom-functions.php';
require get_template_directory() . '/inc/template-tags.php';
require get_template_directory() . '/classes/body-classes.php';
require get_template_directory() . '/inc/widgets/widgets.php';
require get_template_directory() . '/inc/metabox.php';
require get_template_directory() . '/inc/term-meta.php';
require get_template_directory() . '/inc/pagination.php';
require get_template_directory() . '/assets/lib/breadcrumbs/breadcrumbs.php';
require get_template_directory() . '/template-parts/section/video-slider.php';
require get_template_directory() . '/template-parts/section/must-read-section.php';
require get_template_directory() . '/template-parts/section/tiles-section.php';
require get_template_directory() . '/template-parts/section/tab-section.php';
require get_template_directory() . '/template-parts/section/advertise-section.php';
require get_template_directory() . '/template-parts/section/latest-posts.php';
require get_template_directory() . '/template-parts/section/home-widget-section.php';
require get_template_directory() . '/template-parts/section/recommended-section.php';
require get_template_directory() . '/template-parts/section/default-banner.php';


/**
 * Calling in the admin area for the Welcome Page as well as for the new theme notice too.
 */
if (is_admin()) {
    require get_template_directory() . '/inc/dashboard/class-admin.php';
    require get_template_directory() . '/inc/dashboard/class-dashboard.php';
    require get_template_directory() . '/inc/dashboard/class-welcome-notice.php';
    require get_template_directory() . '/inc/dashboard/class-theme-review-notice.php';
}

require get_template_directory() . '/inc/dashboard/class-changelog-parser.php';

if (!class_exists('NewsNation_Constants')) {

    /**
     * NewsNation_Constants class.
     */
    class NewsNation_Constants
    {

        /**
         * The single instance of the class.
         *
         * @var NewsNation_Constants
         */
        private static $instance = null;

        /**
         * Constants array.
         *
         * @var array
         */
        private $constants = array();

        /**
         * Constructor.
         */
        private function __construct()
        {

            // Define constants here.
            $this->constants = array(
                /**
                 * Define URL Location Constants
                 */
                'NEWSNATION_PARENT_URL' => get_template_directory_uri(),
            );

            foreach ($this->constants as $name => $value) {
                $this->define_constant($name, $value);
            }
        }

        /**
         * Gets the single instance of the class.
         *
         * @return NewsNation_Constants
         */
        public static function get_instance()
        {
            if (null === self::$instance) {
                self::$instance = new self();
            }
            return self::$instance;
        }

        /**
         * Define constant safely.
         *
         * @param string $name Constant name.
         * @param mixed $value Constant value.
         *
         * @return void
         */
        private function define_constant($name, $value)
        {
            if (!defined($name)) {
                define($name, $value);
            }
        }
    }
}

// Initialize the class instance.
NewsNation_Constants::get_instance();

add_action('wp_ajax_install_plugin', 'newsnation_plugin_action_callback');
add_action('wp_ajax_activate_plugin', 'newsnation_plugin_action_callback');

function newsnation_plugin_action_callback()
{
    if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'newsnation_install_plugin_nonce')) {
        wp_send_json_error(array('message' => 'Security check failed.'));
    }
    if (!current_user_can('install_plugins')) {
        wp_send_json_error(array('message' => 'You are not allowed to perform this action.'));
    }

    $plugin = sanitize_text_field($_POST['plugin']);
    $plugin_slug = sanitize_text_field($_POST['slug']);

    if (newsnation_is_plugin_installed($plugin)) {
        if (is_plugin_active($plugin)) {
            wp_send_json_success(array('message' => 'Plugin is already activated.'));
        } else {
            // Activate the plugin
            $result = activate_plugin($plugin);

            if (is_wp_error($result)) {
                wp_send_json_error(array('message' => 'Error activating the plugin.'));
            } else {
                wp_send_json_success(array('message' => 'Plugin activated successfully!'));
            }
        }
    } else {
        // Install and activate the plugin
        include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
        include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        $plugin_info = plugins_api('plugin_information', array('slug' => $plugin_slug));
        $upgrader = new Plugin_Upgrader(new WP_Ajax_Upgrader_Skin());
        $result = $upgrader->install($plugin_info->download_link);

        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => 'Error installing the plugin.'));
        }

        $result = activate_plugin($plugin);

        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => 'Error activating the plugin.'));
        } else {
            wp_send_json_success(array('message' => 'Plugin installed and activated successfully!'));
        }
    }
}

function newsnation_is_plugin_installed($plugin_path)
{
    $plugins = get_plugins();
    return isset($plugins[$plugin_path]);
}


