<?php 
/**
 * Theme functions related to structure.
 *
 * This file contains structural hook functions.
 *
 * @package newscope
 */

// Do not allow directly accessing this file.
if (! defined('ABSPATH')) {
    exit();
}
 // doctype html hook
 if ( ! function_exists( 'glamer_doctype' ) ) :
    /**
     * Doctype Declaration.
     *
     * @since 1.0.0
     */
    function glamer_doctype() {
        ?>
            <!DOCTYPE html>
            <html <?php language_attributes(); ?>>
        <?php
    }
endif;
add_action( 'glamer_action_doctype', 'glamer_doctype', 10 );

/**
* Theme Head Hook Function
*/
if ( ! function_exists( 'glamer_head' ) ) :
    /**
    * wp head Codes.
    * @since 1.0.0
    */
    function glamer_head() {
        ?>
        <meta charset="<?php bloginfo( 'charset' ); ?>">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="profile" href="http://gmpg.org/xfn/11">
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <?php if ( is_singular() && pings_open( get_queried_object() ) ) : ?>
        <link rel="pingback" href="<?php echo esc_url( get_bloginfo( 'pingback_url' ) ); ?>">
        <?php endif;

        // Fetch meta once
	    $GlamerMeta = (is_page() || is_singular('post')) ? get_post_meta(get_the_ID(), 'glamer_metabox', true) : array();
    }
endif;
add_action( 'glamer_action_head', 'glamer_head', 10 );

 // Body start hook
if ( ! function_exists( 'glamer_body_start' ) ) :
    /**
     * Outputs the opening <body> tag and other initial HTML.
     *
     * @since 1.0.0
     */
    function glamer_body_start() {
        ?>
        <body <?php body_class(); ?>>
        <?php wp_body_open(); ?>
        <div id="primary" class="site">
            <?php
            if ( defined( 'GLAMER_PRO' ) && function_exists( 'glamer_options' ) ) {
                // Preloader logic
                $glamer_enable_preloader = glamer_options( 'glamer_enable_preloader', true );
                if ( $glamer_enable_preloader ) {
                    $default_loader = glamer_options( 'glamer_select_preloader', 'default' );
                    $loader_style = glamer_options( 'glamer_default_preloader', 1 );
                    echo '<div class="theme-preloader-wrapper">';
                    if ( 'default' === $default_loader ) {
                        echo '<span class="loader' . esc_attr( $loader_style ) . '"></span>';
                    } else {
                        $custom_preloader = glamer_options( 'glamer_custom_preloader' );
                        if ( $custom_preloader ) {
                            echo '<img src="' . esc_url( $custom_preloader ) . '" alt="' . esc_html__( 'preloader', 'glamer' ) . '">';
                        }
                    }
                    echo '</div>';
                }
            } else {
                echo '<div class="theme-preloader-wrapper">';
                echo '<span class="loader1"></span>';
                echo '</div>';
            }
            ?>
            <a class="skip-link screen-reader-text" href="#primary"><?php esc_html_e( 'Skip to content', 'glamer' ); ?></a>
        <?php
    }
endif;
add_action( 'glamer_action_body_start', 'glamer_body_start', 10 );

// Theme Header Hook
if( ! function_exists( 'glamer_header_hook' ) ) {
    /**
     * Default Header function and html
     *
     * @since 1.0.0
     */
    function glamer_header_hook() {
        // Fetch meta once
	    $GlamerMeta = (is_page() || is_singular('post')) ? get_post_meta(get_the_ID(), 'glamer_metabox', true) : array();
        // Determine header style
        if (!empty($GlamerMeta['header_style_meta']) && $GlamerMeta['header_style_meta'] !== 'default') {
            $header_query = new WP_Query([
                'post_type'      => 'glamer_header',
                'posts_per_page' => -1,
                'p'              => $GlamerMeta['header_style_meta'],
            ]);
        } elseif (!empty(glamer_options('site_default_header'))) {
            $header_query = new WP_Query([
                'post_type'      => 'glamer_header',
                'posts_per_page' => -1,
                'p'              => glamer_options('site_default_header'),
            ]);
        } else {
            $header_query = null;
        }
        if (!empty($header_query) && $header_query->have_posts()){
            while ($header_query->have_posts()): $header_query->the_post();
                the_content();
            endwhile;
            wp_reset_postdata();
        }else{
            /**
            * Hook - glamer_action_default_header_hook.
            *
            * @hooked glamer_default_header_hook -  10
            */
            do_action( 'glamer_action_default_header_hook' );
            
        }
    }
}
add_action( 'glamer_action_header_hook', 'glamer_header_hook', 10 );

// 404 page Hook Function
if( ! function_exists( 'galmer_error_page_hook' ) ) {
    /**
     * 404 page HTML and function
     *
     * @since 1.0.0
     */
    function galmer_error_page_hook() {
        $glamer_error_image = glamer_options( 'glamer_error_image' );
        $glamer_not_found_text = glamer_options( 'glamer_not_found_text' );
        $glamer_go_back_home = glamer_options( 'glamer_go_back_home', true );
        $glamer_error_page_button_text = glamer_options( 'glamer_error_page_button_text', esc_html( 'Go Back Home', 'glamer' ) );
        echo'<main id="page" class="content-area">';
            echo'<div class="container not-found-content">';
                echo'<div class="row justify-content-center">';
                    echo'<div class="col-12 col-sm-12 col-md-10 col-xl-8 col-lg-8">';
                        echo'<div class="not-found-text-wrapper text-center">';
                            if ( !empty( $glamer_error_image['url'] ) ){
                                echo'<div class="error-image">';
                                echo'<img src="'.esc_url( $glamer_error_image['url'] ).'" alt="'.esc_attr( $glamer_error_image['alt'] ).'">';
                            echo'</div>';
                            }else{
                                echo'<div class="text-404">';
                                    echo'<h2>'.esc_html__( '404','glamer' ).'</h5>';
                                echo'</div>';
                            }
                            echo'<div class="error-dec pt-5">';
                                if (defined('GLAMER_PRO')){
                                    echo wp_kses( $glamer_not_found_text, glamer_allow_html() );
                                }else{
                                    echo'<h2>'.esc_html__( 'Oops!', 'glamer' ).'</h2>';
                                    echo'<h2>'.esc_html__('That page can not be found.','glamer').'</h2>';
                                    echo'<p>'.esc_html__( 'The page you are looking for is not available or doesnt belong to this website!', 'glamer' ).'</p>';
                                }
                            echo'</div>';
                            if ( $glamer_go_back_home == true ){
                                echo'<div class="error-button button">';
                                echo'<a class="glamer-btn" href="'.esc_url( home_url( '/' ) ).'"><span>'.esc_html( $glamer_error_page_button_text ).'</span></a>';
                                echo'</div>';
                            }
                        echo'</div><!-- .page-content -->';
                    echo'</div>';
                echo'</div>';
            echo'</div>';
        echo'</main><!-- #main -->';
    }
}
add_action( 'galmer_action_error_page_hook', 'galmer_error_page_hook', 10 );


// Archive Page Hook Function
if( ! function_exists( 'glamer_archive_hook' ) ) {
    /**
     * Archive Hook HTML
     *
     * @since 1.0.0
     */
    function glamer_archive_hook() {
        $glamer_archive_pagination = glamer_options( 'glamer_archive_pagination', true );
        $glamer_archiveLayout = isset($_GET['bs']) ? sanitize_text_field($_GET['bs']) : glamer_options('glamer_archive_layout', 'right-sidebar');
        echo'<main id="page" class="site-main content-area">';
            echo'<div class="container page-layout-'.esc_attr($glamer_archiveLayout).'">';
                if (in_array($glamer_archiveLayout, ['grid', 'grid-rs', 'grid-ls'])) {
                    get_template_part('template-parts/post/post-grid');
                } else {
                    get_template_part('template-parts/post/post-list');
                }
            echo'</div>';
        echo'</main><!-- #main -->';
    }
}
add_action( 'glamer_action_archive_hook', 'glamer_archive_hook', 10 );


// Author Page hook and function
if( ! function_exists( 'glamer_author_page_hook' ) ) {
    /**
     * author page Hook HTML
     *
     * @since 1.0.0
     */
    function glamer_author_page_hook() {
        // Fetch options
        $glamer_authors_banner = glamer_options('glamer_authors_banner', true);
        $glamer_breadcrumb_select_html = glamer_options('glamer_breadcrumb_select_html', 'h2');
        $glamer_authors_layout = glamer_options('glamer_authors_layout', 'right-sidebar');
        $glamer_authors_layouts = isset($_GET['bs']) ? sanitize_text_field($_GET['bs']) : glamer_options('glamer_authors_layout', 'right-sidebar');
        // Get current author ID
        $author_id = get_queried_object_id();
        global $post;

        // Fetch author meta
        $glamer_author_meta = get_the_author_meta('glamer_author_meta', $author_id) ?: array();
        $default_avatar = get_template_directory_uri() . '/assets/image/avatar.jpg'; // Ensure this path is correct

        // Fetch the custom user image from user meta
        $custom_user_image = get_user_meta($author_id, 'custom_user_image', true);


        $main_image_url = (is_array($custom_user_image) && isset($custom_user_image['url'])) ? esc_url($custom_user_image['url']) : $default_avatar;
        $author_avatar_url = !empty($main_image_url) ? $main_image_url : (get_avatar_url($author_id) ?: $default_avatar);

        echo'<div class="container mb-80">';
            echo'<div class="author-info-box">';
                echo'<div class="author-info-img-wrap">';
                    echo'<div class="author-info-img">';
                        echo'<img src="'.esc_url($author_avatar_url).'" alt="'.esc_attr(get_the_author_meta('display_name', $author_id)).'" loading="lazy">';
                    echo'</div>';
                echo'</div>';
                echo'<div class="author-info-content-wrap">';
                    echo'<h4 class="author-info-title">'.esc_html(get_the_author_meta('display_name', $author_id)).'</h4>';
                    echo'<p class="author-info-para">'.esc_html(get_the_author_meta('description', $author_id)).'</p>';
                    echo'<div class="footer-social-widget">';
                        echo'<ul>';
                            // Get user contact methods
                            $contact_methods = wp_get_user_contact_methods();
                            foreach ($contact_methods as $key => $value){
                                $contact_link = get_user_meta($author_id, $key, true);
                                if (!empty($contact_link)){
                                    echo'<li>';
                                    echo'<a data-toggle="tooltip" data-placement="top" data-original-title="'.esc_attr($value).'" href="'.esc_url($contact_link).'" target="_blank" rel="noopener noreferrer">';
                                        echo'<span class="fab fa-'.esc_attr($key).'"></span>';
                                    echo'</a>';
                                echo'</li>';
                                }
                            }
                        echo'</ul>';
                    echo'</div>';
                echo'</div>';
            echo'</div>';
        echo'</div>';

        echo'<main id="page" class="site-main author-content-area mb-80">';
            echo'<div class="container author-page-layout-'.esc_attr($glamer_authors_layouts).'">';
                if (in_array($glamer_authors_layouts, ['grid', 'grid-rs', 'grid-ls'])) {
                    get_template_part('template-parts/post/post-grid');
                } else {
                    get_template_part('template-parts/post/post-list');
                }
            echo'</div>';
        echo'</main><!-- #main -->';
    }
}
add_action( 'glamer_action_author_page_hook', 'glamer_author_page_hook', 10 );

// Blank Template Hook Function
if( ! function_exists( 'glamer_blank_template_hook' ) ) {
    /**
     * Blank Template Hook HTML
     *
     * @since 1.0.0
     */
    function glamer_blank_template_hook() {
        echo'<main id="page" class="site-main content-area">';
            the_content();
        echo'</main><!-- #main -->';
    }
}
add_action( 'glamer_action_blank_template_hook', 'glamer_blank_template_hook', 10 );

// Index Page Hook Function
if( ! function_exists( 'glamer_index_page_hook' ) ) {
    /**
     * Index Page Hook HTML
     *
     * @since 1.0.0
     */
    function glamer_index_page_hook() {
        $glamer_blog_layouts = isset($_GET['bs']) ? sanitize_text_field($_GET['bs']) : glamer_options('glamer_blog_layout', 'right-sidebar');
        echo'<main id="page" class="site-main content-area page-layout-'.esc_attr($glamer_blog_layouts).'">';
            echo'<div class="container">';
                if (in_array($glamer_blog_layouts, ['grid', 'grid-rs', 'grid-ls'])) {
                    get_template_part('template-parts/post/post-grid');
                } else {
                    get_template_part('template-parts/post/post-list');
                }
            echo'</div>';
        echo'</main>';
    }
}
add_action( 'glamer_action_index_page_hook', 'glamer_index_page_hook', 10 );

// Pages Hook Function
if( ! function_exists( 'glamer_pages_hook' ) ) {
    /**
     * Pages Page Hook HTML
     *
     * @since 1.0.0
     */
    function glamer_pages_hook() {
        // Retrieve common meta once
        $glamer_commonMeta = get_post_meta(get_the_ID(), 'glamer_metabox', true) ?: array();
        // Page layout logic
        $glamer_pageLayout = $glamer_commonMeta['glamer_layout_meta'] ?? 'full-width';
        // Sidebar logic
        $glamer_selectedSidebar = $glamer_commonMeta['glamer_sidebar_meta'] ?? 'sidebar';
        // Determine page column class based on layout and sidebar
        $glamer_pageColumnClass = ($glamer_pageLayout == 'left-sidebar' || $glamer_pageLayout == 'right-sidebar') && is_active_sidebar($glamer_selectedSidebar) ? 'col-12 col-sm-12 col-md-12 col-lg-12 col-xl-8' : 'col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12';
        // Theme options
        $glamer_enable_page_cmt = glamer_options('glamer_enable_page_cmt', true);
        echo'<main id="primary" class="site-main content-area">';
            echo'<div class="container '.esc_attr($glamer_pageLayout).'">';
                echo'<div class="page-layout">';
                    echo'<div class="row">';
                        if ($glamer_pageLayout == 'left-sidebar' && is_active_sidebar($glamer_selectedSidebar)){
                            get_sidebar();
                        }
                        echo'<div class="'.esc_attr($glamer_pageColumnClass).'">';
                            echo'<div class="all-posts-wrapper">';
                                while (have_posts()){
                                    the_post();
                                    get_template_part('template-parts/content', 'page');
                                }
                                // Display comments if enabled
                                if ($glamer_enable_page_cmt && (comments_open() || get_comments_number())){
                                    comments_template();
                                }
                            echo'</div>';
                        echo'</div>';

                        if ($glamer_pageLayout == 'right-sidebar' && is_active_sidebar($glamer_selectedSidebar)){
                            get_sidebar();
                        }
                    echo' </div>';
                echo'</div>';
            echo'</div>';
        echo'</main><!-- #main -->';
    }
}
add_action( 'glamer_action_pages_hook', 'glamer_pages_hook', 10 );

// Search Page Hook Function
if( ! function_exists( 'glamer_search_page_hook' ) ) {
    function glamer_search_page_hook() {
        $glamer_search_pagination = glamer_options('glamer_search_pagination', true);
        $glamer_searchLayouts = isset($_GET['bs']) ? sanitize_text_field($_GET['bs']) : glamer_options('glamer_search_layout', 'right-sidebar');
        echo'<main id="page" class="site-main content-area">';
            echo'<div class="container page-layout-'.esc_attr($glamer_searchLayouts).'">';
                if (in_array($glamer_searchLayouts, ['grid', 'grid-rs', 'grid-ls'])) {
                    get_template_part('template-parts/post/post-grid');
                } else {
                    get_template_part('template-parts/post/post-list');
                }
            echo'</div>';
        echo'</main><!-- #main -->';
    }
}
add_action( 'glamer_action_search_page_hook', 'glamer_search_page_hook', 10 );

// Sidebar Hook Function
if( ! function_exists( 'glamer_sidebar_hook' ) ) {
    function glamer_sidebar_hook() {
        if(is_page() || is_singular('post') && get_post_meta(get_the_ID(), 'glamer_metabox', true)) {
            $glamer_commonMeta = get_post_meta(get_the_ID(), 'glamer_metabox', true);
        } else {
            $glamer_commonMeta = array();
        }
        
        if(is_array($glamer_commonMeta) && array_key_exists('glamer_sidebar_meta', $glamer_commonMeta)){
            $glamer_selectedSidebar = $glamer_commonMeta['glamer_sidebar_meta'];
        }else{
            $glamer_selectedSidebar = 'sidebar';
        }
        
        if (is_array($glamer_commonMeta) && array_key_exists( 'glamer_sidebar_meta', $glamer_commonMeta ) && $glamer_commonMeta['glamer_sidebar_meta'] != '0' ) {
            $glamer_selectedSidebar = $glamer_commonMeta['glamer_sidebar_meta'];
        } else {
            $glamer_selectedSidebar = 'sidebar';
        }
        echo'<aside id="secondary" class="col-xl-4 col-lg-12 sidebar-widget-area">';
            echo'<div class="sidebar-sticky-area">';
                if( is_active_sidebar( 'sidebar2' ) && is_single() ){
                    dynamic_sidebar( 'sidebar2' );
                }else{
                    if( is_active_sidebar( $glamer_selectedSidebar ) ) {
                        dynamic_sidebar( $glamer_selectedSidebar );
                    }
                }
            echo'</div>';
        echo'</aside>';
    }
}
add_action( 'glamer_action_sidebar_hook', 'glamer_sidebar_hook', 10 );

// single page Hook Function
if( ! function_exists( 'glamer_single_page_hook' ) ) {
    function glamer_single_page_hook() {
        // Fetch common meta once
        $glamer_commonMeta = get_post_meta(get_the_ID(), 'glamer_metabox', true) ?: array();

        // Post layout logic (consider the 'bs' URL parameter for layout override)
        $default_post_layout = glamer_options('single_post_default_layout', 'right-sidebar');
        $glamer_postLayouts = isset($glamer_commonMeta['glamer_layout_meta']) && $glamer_commonMeta['glamer_layout_meta'] !== 'default' ? $glamer_commonMeta['glamer_layout_meta'] : $default_post_layout;

        // Allow layout override through the 'bs' URL parameter
        $glamer_postLayout = isset($_GET['bs']) ? sanitize_text_field($_GET['bs']) : $glamer_postLayouts;

        // Sidebar logic
        $glamer_selectedSidebar = isset($glamer_commonMeta['glamer_sidebar_meta']) && $glamer_commonMeta['glamer_sidebar_meta'] !== '0' ? $glamer_commonMeta['glamer_sidebar_meta'] : 'sidebar';

        // Determine page column class based on sidebar layout and activity
        $glamer_pageColumnClass = ($glamer_postLayout === 'left-sidebar' || $glamer_postLayout === 'right-sidebar') && is_active_sidebar($glamer_selectedSidebar) ? 'col-lg-12 col-md-12 col-xl-8' : 'col-lg-12 col-md-12';

        echo'<div id="page" class="content-area layout-'.esc_attr($glamer_postLayout).'">';
            echo '<div class="post-details-wrapper' 
            . (!has_post_thumbnail() ? ' no-post-thumbnail' : '') 
            . (glamer_options('single_post_default_layout') == 'full-width' ? ' single-post-full-width' : '') 
            . '">';
                echo'<div class="container">';
                    echo'<div class="row">';
                        // Display left sidebar if applicable
                        if ($glamer_postLayout === 'left-sidebar' && is_active_sidebar($glamer_selectedSidebar)) {
                            get_sidebar();
                        }
                        echo'<div class="'.esc_attr($glamer_pageColumnClass).'">';
                            // Start post loop
                            while (have_posts()){
                                the_post();
                                // Display post content
                                get_template_part('template-parts/content', get_post_type());
                                // Load comments template if comments are open or there's at least one comment
                                if (comments_open() || get_comments_number()){
                                    comments_template();
                                }
                            }
                        echo'</div>';
                        // Display right sidebar if applicable
                        if ($glamer_postLayout === 'right-sidebar' && is_active_sidebar($glamer_selectedSidebar)) {
                            get_sidebar();
                        }
                    echo'</div>';
                echo'</div>';
            echo'</div>';
        echo'</div><!-- #primary -->';
    }
}
add_action( 'glamer_action_single_page_hook', 'glamer_single_page_hook', 10 );

// Footer Hook Function
if( ! function_exists( 'glamer_footer_hook' ) ) {
    function glamer_footer_hook() {
    // Fetch meta only if on relevant post types
    $GlamerMeta = (is_page() || is_singular('post')) ? get_post_meta( get_the_ID(), 'glamer_metabox', true ) : array();

    // Determine footer style
    if (!empty($GlamerMeta['footer_style_meta']) && $GlamerMeta['footer_style_meta'] !== 'default') {
    $footer_query = new WP_Query([
        'post_type'      => 'glamer_footer',
        'posts_per_page' => -1,
        'p'              => $GlamerMeta['footer_style_meta'],
    ]);
    } elseif (!empty(glamer_options('site_default_footer'))) {
    $footer_query = new WP_Query([
        'post_type'      => 'glamer_footer',
        'posts_per_page' => -1,
        'p'              => glamer_options('site_default_footer'),
    ]);
    } else {
    $footer_query = null;
    }

    // Footer options
    $glamer_enable_top_to_bottom = glamer_options('glamer_enable_top_to_bottom', true);
    $glamer_enable_ttb_icon = glamer_options('glamer_enable_ttb_icon', 'fas fa-arrow-up');
    
    echo '<footer class="footer-layout3">';
        if (!empty($footer_query) && $footer_query->have_posts()){
            while ($footer_query->have_posts()) : $footer_query->the_post();
                the_content();
            endwhile;
            wp_reset_postdata();
        }else{
            /**
            * Hook - glamer_action_default_footer_hook.
            *
            * @hooked glamer_default_footer_hook -  10
            */
            do_action( 'glamer_action_default_footer_hook' );
        }
    echo '</footer><!-- #colophon -->';

    if ($glamer_enable_top_to_bottom){
        echo '<div class="bottom-to-top">';
        echo '<div class="to-top">';
        echo '<div class="to-top-icon"><span class="'.esc_attr($glamer_enable_ttb_icon).'"></span></div>';
        echo '</div>';
        echo '</div>';
    }
    }
}
add_action( 'glamer_action_footer_hook', 'glamer_footer_hook', 10 );

// Body end hook
if ( ! function_exists( 'glamer_body_end' ) ) :
    /**
     * Outputs the closing </body> and </html> tags.
     *
     * @since 1.0.0
     */
    function glamer_body_end() {
        
        echo'</div><!-- #primary -->';
        wp_footer();
        echo'</body>';
        echo'</html>';
    }
endif;
add_action( 'glamer_action_body_end', 'glamer_body_end', 10 );