<?php
/**
 * Theme functions and definitions
 * RoyalNews only works in WordPress 4.7 or later.
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 * @package RoyalNews
 */

if ( ! defined( '_ROYALNEWS_PREFIX' ) ) {
    define( '_ROYALNEWS_PREFIX', 'royalnews' );
}
if ( ! defined( '_ROYALNEWS_VERSION' ) ) {
    define( '_ROYALNEWS_VERSION', '1.3' );
}

require_once get_theme_file_path( 'includes/loader/enqueue.php' );

if ( ! function_exists( 'wp_body_open' ) ) {
    /**
     * Shim for wp_body_open, ensuring backwards compatibility with versions of WordPress older than 5.2.
     * @since 1.0
    */
    function wp_body_open() {
        do_action( 'wp_body_open' );
    }
}

if( !function_exists( 'royalnews_init_sidebar' ) ){
    /**
     * Init sidebar for RoyalNews
     * @since 1.0
     * @package RoyalNews
     */
    function royalnews_init_sidebar(){
        register_sidebar( array(
            'name'          => esc_html__( 'Sidebar', 'royalnews' ),
            'id'            => 'royalnews-main-sidebar',
            'description'   => esc_html__( 'Widgets in this area will be shown on side of the page.', 'royalnews' ),
            'before_widget' => '<section id="%1$s" class="widget %2$s">',
            'after_widget'  => '</section>',
            'before_title'  => '<h2 class="royalnews-widget-title">',
            'after_title'   => '</h2>',
        ));

        register_sidebar( array(
            'name'          => esc_html__( 'Footer Widget Area', 'royalnews' ),
            'id'            =>  'royalnews_footer_area',
            'before_widget' => '<section id="%1$s" class="widget %2$s">',
            'after_widget'  => '</section>',
            'before_title'  => '<h2 class="royalnews-widget-title">',
            'after_title'   => '</h2>',
        ));

        register_sidebar( array(
            'name'          => esc_html__( 'After Header Widget Area', 'royalnews' ),
            'id'            =>  'royalnews_after_header',
            'before_widget' => '<section id="%1$s" class="widget %2$s">',
            'after_widget'  => '</section>',
            'before_title'  => '<h2 class="royalnews-widget-title">',
            'after_title'   => '</h2>',
        ));

        register_sidebar( array(
            'name'          => esc_html__( 'Before footer Widget Area', 'royalnews' ),
            'id'            =>  'royalnews_before_footer',
            'before_widget' => '<section id="%1$s" class="widget %2$s">',
            'after_widget'  => '</section>',
            'before_title'  => '<h2 class="royalnews-widget-title">',
            'after_title'   => '</h2>',
        ));
    }
}
add_action( 'widgets_init', 'royalnews_init_sidebar' );

if( !function_exists( 'royalnews_essentials_theme_supports' ) ){  
    /**
     * Register different essentials things for theme
     * @since 1.0
     * @package RoyalNews
     */
    function royalnews_essentials_theme_supports(){
        /* Add theme support for Custom Logo. */
        $custom_logo_args = array(
            'width'       => 180,
            'height'      => 60,
            'flex-width'  => true,
            'flex-height' => true,
        );
        add_theme_support( 'custom-logo', $custom_logo_args );

        /* Switch default core markup for search form, comment form, and comments.
            to output valid HTML5.
        */
        $html5_args = array(
            'search-form',
            'comment-form',
            'comment-list',
            'gallery',
            'caption',
        );
        add_theme_support( 'html5', $html5_args );

        /* Gutenberg wide images. */
        add_theme_support( 'align-wide' );
        add_theme_support( 'wp-block-styles' );
        /* Add default posts and comments RSS feed links to head. */
        add_theme_support( 'automatic-feed-links' );

        /* Let WordPress manage the document title. */
        add_theme_support( 'title-tag' );

        /* Enable support for Post Thumbnails on posts and pages. */
        add_theme_support( 'post-thumbnails' );

        /* Add theme support for selective refresh for widgets. */
        add_theme_support( 'customize-selective-refresh-widgets' );

        /* Post formats. */
        add_theme_support(
            'post-formats',
            array(
                'gallery',
                'image',
                'link',
                'quote',
                'video',
                'audio',
                'status',
                'aside',
            )
        );

        add_theme_support( 'responsive-embeds' );

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


        /* Customize Selective Refresh Widgets. */
        add_theme_support( 'customize-selective-refresh-widgets' );
        add_theme_support( 'post-thumbnails' );

        /**
         * 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( 'content_width_setup', 640 );

        /**
         * Make theme available for translation.
         * Translations can be filed in the /languages/ directory.
         */
        load_theme_textdomain( 'royalnews', get_theme_file_uri( 'languages' ) );
        /**
        * Register Menus
        * @since 1.0
        * @package RoyalNews
        */
        register_nav_menus(
            array(
                'primary-menu' => esc_html__( 'Primary Menu', 'royalnews' ),
                'social-menu-header' => esc_html__( 'Social Menu Header', 'royalnews' )
            )
        );

        # header image options
        add_theme_support( 'custom-header', apply_filters( 'royalnews_header_media_args' , array(
            'default-text-color' => '000000',
            'width'              => 1366,
            'height'             => 400,
            'flex-height'        => true,
            'default-image'      => '',
        )));

        /**
         * Support to new page template wp 5.8
         */
        add_theme_support( 'block-templates' );
    }
}

add_action( 'after_setup_theme', 'royalnews_essentials_theme_supports' );

/**
 * Modified excerpt length
 * @since 1.0
 * @package RoyalNews
 */
function royalnews_excerpt_length( $length ){
    if( is_admin() ){
        return $length;
    }
    $length = royalnews_value( 'excerpt_length' );
    return $length;
}
add_filter( 'excerpt_length', 'royalnews_excerpt_length' );

/**
 * Modified excerpt readmore
 * @since 1.0
 * @package RoyalNews
 */
function royalnews_excerpt_more( $text ){
    if( is_admin() ){
        return $text;
    }   
            
    $more = sprintf( '...<div class="royalnews-readmore-wrap"><a href="%1$s" class="royalnews-readmore">%2$s <i class="far fa-hand-point-right"></i></a></div>',
        esc_url( get_the_permalink() ),
        royalnews_value( 'read_more_text' )
    );

    return $more;
}
add_filter( 'excerpt_more', 'royalnews_excerpt_more' );

/**
 * Return Body class
 * @since 1.0
 * @package RoyalNews
 */
function royalnews_body_classes( $classes ){
    if( royalnews_value( 'sticky-header' ) ){
        $classes[] = _ROYALNEWS_PREFIX.'-sticky-header';
    }

    if( royalnews_value( 'enable_sidebar' ) ){
        $classes[] = 'royalnews-sidebar-enable';
    }else{
        $classes[] = 'royalnews-sidebar-disabled';  
    }

    if( !royalnews_value( 'enable-social' ) ){
        $classes[] = 'royalnews-social-menu-disabled';
    }

    $post_per_row = royalnews_value( 'post_per_row' );
    if( '1' == $post_per_row ){
        $classes[] = 'royalnews-blog-one';
    }elseif( '2' == $post_per_row ){
        $classes[] = 'royalnews-blog-two';    
    }elseif( '3' == $post_per_row ){
        $classes[] = 'royalnews-blog-three';
    }

    if( 'enable' == royalnews_value( 'dark_mode' ) ){
        $classes[] = 'royalnews-dark-mode';
    }
    
    return $classes;
}
add_action( 'body_class', 'royalnews_body_classes' );

function royalnews_meta_field(){
    $post_types = array( 'page' );
    foreach ( $post_types as $type ) {
        $post = new RoyalNews_Meta_Fields( $type );
        if( 'page' == $type ){
            $options = array(
                'disable-banner' => array(
                    'type'  => 'checkbox',
                    'label' => esc_html__( 'Disable Banner', 'royalnews' ),
                )
            );

        }

        $post->add_meta_box( esc_html__( 'RoyalNews Settings', 'royalnews' ), $options );
    }
}
add_action( 'init', 'royalnews_meta_field' );

function royalnews_customize_register( $wp_customize ){
    /**
     * modify customizer options
     * @since 1.0
     * @package RoyalNews
     */
    $wp_customize->get_control( 'header_textcolor' )->section = 'title_tagline';
    $wp_customize->get_control( 'header_textcolor' )->label = esc_html__( 'Site Identity Color', 'royalnews' );

    $wp_customize->get_section( 'header_image' )->title = esc_html__( 'Banner Options', 'royalnews' );
    $wp_customize->get_section( 'header_image' )->panel = 'royalnews_options';

    # change background color section
    $wp_customize->get_control( 'background_color' )->section = 'general_options';

    # change background image panel
    $wp_customize->get_section( 'background_image' )->panel = 'royalnews_options';

    if( !class_exists( 'Kirki' ) ){         

        $wp_customize->add_section( 'kirki_plugin_msg' , array(
          'title' => esc_html__( 'To enable features, install Kirki Customizer Framework Plugin', 'royalnews' ),
          'priority' => 0,
        ));

        $wp_customize->add_setting( 'kirki_plugin_hidden_control', array(
          'default' => '',
          'sanitize_callback' => 'text',
        ));

        $wp_customize->add_control( 'kirki_plugin_hidden_control', array(
          'label' => esc_html__( 'Hidden Control', 'royalnews' ),
          'type' => 'text',
          'section' => 'kirki_plugin_msg',
        ));
    }

}
add_action( 'customize_register', 'royalnews_customize_register' );

/**
 * Add darkmode toggler
 * @since 1.0
 * @package RoyalNews
 */
function royalnews_add_dark_mode_toggler(){ 
    if( 'toggle' == royalnews_value( 'dark_mode' ) ){ ?>
        <div class="royalnews-darkmode-toggle-wrapper">        
            <label class="royalnews-switch">
              <input type="checkbox">
              <span class="royalnews-slider round"></span>
            </label>
        </div>
    <?php }
}

add_action( 'royalnews-after-nav', 'royalnews_add_dark_mode_toggler' );

/**
 * Add cart icon if woocommerce active
 * @since 1.0
 * @package RoyalNews
 */
function royalnews_add_cart_icon() {
    if ( !class_exists( 'WooCommerce' ) ) {
        return;
    }
    if ( is_cart() || is_checkout() ) {
        return;
    }
    $count = WC()->cart->cart_contents_count;
    $string  = wc_get_cart_url(); ?>
    <div class="royalnews-woocommerce-cart"> 
        <a href="<?php echo esc_url( $string ); ?>" class="cart-icon">
            <i class="fas fa-shopping-cart"></i>
            <span><?php echo ( $count > 0 ) ? esc_html( $count ) : 0; ?></span>
        </a>
    </div>
<?php }

add_action( 'royalnews-after-nav', 'royalnews_add_cart_icon', 20 );

if( !function_exists( 'royalnews_get_posts_by_type' ) ){
    /**
     * Returns post by type
     * @since 1.0
     * @package RoyalNews
     */
    function royalnews_get_posts_by_type( $type, $cat_id, $post_to_display = false ){
        $posts = array();
        if( 'post' == $type ){
            $recent_posts = wp_get_recent_posts(array(
                'numberposts' => $post_to_display ? $post_to_display : -1,
                'post_status' => 'publish'
            ));

            foreach ( $recent_posts as $post) {
                $posts[] = $post[ 'ID' ]; 
            }
        }elseif( 'category' == $type ){         
            $args = array(
                'post_type' => 'post',
                'posts_per_page' => $post_to_display ? $post_to_display : -1,
                'orderby' => 'date',
                'order' => 'DESC',
                'ignore_sticky_posts' => 1,
            );
            if( $cat_id ){
                $args[ 'cat' ] = $cat_id; 
            }

            $query = new WP_Query( $args );
            if ( $query->have_posts() ) {
                while ( $query->have_posts() ) {
                    $query->the_post();
                    $posts[] = get_the_ID();
                }
            }
            wp_reset_postdata();                    
        }
        if( empty( $posts ) ){
            return false;
        }else{
            return $posts;
        }
    }
}


/**
 * Plugin recommendation
 * @since 1.0
 * @package RoyalNews
 */
function royalnews_required_plugins(){
    $plugins = array(
        array(
            'name'     => esc_html__( 'Kirki Customizer Framework', 'royalnews' ),
            'slug'     => 'kirki',
            'description' => esc_html__( 'Please Install Kirki to use options', 'royalnews' ),
            'required' => true,
        )
    );

    tgmpa( $plugins );
}
add_action( 'tgmpa_register', 'royalnews_required_plugins' );