<?php
/**
 * Felicityhealth's functions and definitions
 *
 * @package Felicityhealth
 * @since Felicityhealth 1.0
 */
 
/**
 * First, let's set the maximum content width based on the theme's design and stylesheet.
 * This will limit the width of all uploaded images and embeds.
 */
if ( ! isset( $content_width ) )
    $content_width = 800; /* pixels */

function felicity_setup() {
    //Registering ZuluRED primary navigation
    /**
     * Add support for two custom navigation menus.
     */
    register_nav_menus(array(
        'primary-menu-left' => __('Primary Menu Left','felicityhealth'),
        'quick-links-menu' => __('Quick Links','felicityhealth'),
        'footer-menu' => __('Footer Menu','felicityhealth'),
        'footer-nav-outline-menu' => __('Footer Nav Outline Links Menu','felicityhealth'),
        'footer-bottom-links' => __('Footer Bottom Links Menu','felicityhealth'),
    ));
        
    //adding theme support for the document title tag
    add_theme_support('title-tag');
    
    /**
     * Make theme available for translation.
     * Translations can be placed in the /languages/ directory.
     */
    load_theme_textdomain( 'felicityhealth', get_template_directory() . '/languages' );
 
    /**
     * Add default posts and comments RSS feed links to <head>.
     */
    add_theme_support( 'automatic-feed-links' );
 
    /**
     * Enable support for post thumbnails and featured images.
     */
    add_theme_support( 'post-thumbnails' );
 
    
    /**
     * Enable support for the following post formats:
     * aside, gallery, quote, image, and video
     */
    add_theme_support( 'post-formats', array ( 'aside', 'gallery', 'quote', 'image', 'video' ) );
     
}
add_action('after_setup_theme','felicity_setup');
// Enable Excerpt on Pages
add_post_type_support( 'page', 'excerpt' );
//Loading Scripts
function enqueue_felicity_scripts() {
    // JAVASCRIPTS (Load javascripts at bottom, this will reduce page load time) -->
    // Global Vendor -->
    // wp_enqueue_script( 'Jquery',get_template_directory_uri() .'/assets/vendors/jquery.min.js', array ('jquery'), 1.1, true);    
    // Vendor  -->
    wp_enqueue_script( 'bootstrap', get_template_directory_uri() .'/assets/vendors/bootstrap/dist/js/bootstrap.bundle.min.js',array (), 1.1, true);
    // wp_enqueue_script( 'smooth-scroll', get_template_directory_uri() .'/assets/vendors/smooth-scroll/dist/js/smooth-scroll.polyfills.min.js',array (), 1.1, true);
    // wp_enqueue_script( 'jarallax', get_template_directory_uri() .'/assets/vendors/jarallax/dist/jarallax.min.js',array (), 1.1, true);
    // wp_enqueue_script( 'jarallax-element', get_template_directory_uri() .'/assets/vendors/jarallax/dist/jarallax-element.min.js',array (), 1.1, true);
    // wp_enqueue_script( 'swiper', get_template_directory_uri() .'/assets/vendors/swiper/swiper-bundle.min.js',array (), 1.1, true);
    // wp_enqueue_script( 'lightgallery', get_template_directory_uri() .'/assets/vendors/lightgallery.js/dist/js/lightgallery.min.js',array (), 1.1, true);
    // wp_enqueue_script( 'lg-video', get_template_directory_uri() .'/assets/vendors/lg-video.js/dist/lg-video.min.js',array (), 1.1, true);
    // wp_enqueue_script( 'lg-fullscreen', get_template_directory_uri() .'/assets/vendors/lg-fullscreen.js/dist/lg-fullscreen.min.js',array (), 1.1, true);
    // wp_enqueue_script( 'lg-zoom', get_template_directory_uri() .'/assets/vendors/lg-zoom.js/dist/lg-zoom.min.js',array (), 1.1, true);
    // wp_enqueue_script( 'lg-thumbnail', get_template_directory_uri() .'/assets/vendors/lg-thumbnail.js/dist/lg-thumbnail.min.js',array (), 1.1, true);
    wp_enqueue_script( 'splitting', get_template_directory_uri() .'/assets/js/splitting.min.js',array (), 1.1, true);
    wp_enqueue_script( 'packery', get_template_directory_uri() .'/assets/js/packery.pkgd.min.js',array (), 1.1, true);
    wp_enqueue_script( 'theme', get_template_directory_uri() .'/assets/js/theme.js',array (), 1.1, true);
    // wp_enqueue_script( 'main-js', get_template_directory_uri() .'/assets/js/main.js',array (), 1.1, true);
    //If comments are enabled by the user, and we are on a post page, then the comment reply script will be loaded. Otherwise, it will not.
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
    // *** Stylesheets ***//
    // *** Vendor CSS ***//
    //animate CSS, Slick
    wp_enqueue_style( 'boxicons', get_template_directory_uri() . '/assets/vendors/boxicons/css/boxicons.min.css', false, '1.1', 'all');
    wp_enqueue_style( 'swiper', get_template_directory_uri() . '/assets/vendors/swiper/swiper-bundle.min.css', false, '1.1', 'all');
    wp_enqueue_style( 'lightgallery.js-css', get_template_directory_uri() . '/assets/vendors/lightgallery.js/dist/css/lightgallery.min.css', false, '1.1', 'all');
    //Styles
    // wp_enqueue_style( 'theme-style', get_template_directory_uri() . '/assets/css/theme.min.css',false,'1.1','all');
    // wp_enqueue_style( 'main-style', get_template_directory_uri() . '/assets/css/main.css',false,'1.1','all');
    // wp_enqueue_style( 'Falconview-style', get_template_directory_uri() . '/styles.css',false,'1.1','all');
    wp_enqueue_style( 'Falconview-style', get_stylesheet_uri() );

}
add_action( 'wp_enqueue_scripts', 'enqueue_felicity_scripts' );

function felicity_custom_logo_setup() {
    $defaults = array(
        'height'      => 100,
        'width'       => 400,
        'flex-height' => true,
        'flex-width'  => true,
        'header-text' => array( 'site-title', 'site-description' ),
    );
    add_theme_support( 'custom-logo', $defaults );
}
add_action( 'after_setup_theme', 'felicity_custom_logo_setup' );

/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function felicity_widgets() {
    register_sidebar( array(
        'name'          => __( 'Sidebar', 'felicityhealth' ),
        'id'            => 'sidebar-1',
        'description'   => __( 'Add widgets here to appear in the sidebar', 'felicityhealth' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>'
    ) );
    register_sidebar(
        array(
            'id'            => 'primary',
            'name'          => __( 'Primary Sidebar' ),
            'description'   => __( 'A short description of the sidebar.' ),
            'before_widget' => '<div id="%1$s" class="widget %2$s">',
            'after_widget'  => '</div>',
            'before_title'  => '<h3 class="widget-title">',
            'after_title'   => '</h3>',
        )
    );
   
}
add_action( 'widgets_init', 'felicity_widgets' );


// Setting Up ZuluRED Menu Controls
function felicity_menu() {
    add_theme_page( 'Akos Theme Options','ZuluRED Options', 'manage_options', 'akos-theme-options', 'felicity_options');
    add_theme_page( 'Akos Theme Demos Data','ZuluRED Demo', 'manage_options', 'akos-theme-demo', 'felicity_options');
}

function felicity_options() {
    if ( !current_user_can( 'manage_options' ) ) {
        wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
    }
    echo 'Coming Soon';
    echo '</div><pre>';
}
add_action( 'admin_menu', 'felicity_menu' );
// End Admin Menu Setup

// function akos_shortcode( $atts, $content = null ) {
// 	return '<span class="caption">' . $content . '</span>';
// }
// add_shortcode( 'caption', 'akos_shortcode' );
//disable the Wordpress auto p in editor
// remove_filter('the_content','wpautop');

// Register Custom Navigation Walker
// require_once get_template_directory() . '/walkers/wp-bootstrap-navwalker.php';
require_once get_template_directory() . '/walkers/mainMenuLeftNavwalker.php';
require_once get_template_directory() . '/walkers/footer-menu-walker.php';
require_once get_template_directory() . '/walkers/footer-nav-outline-walker.php';
require_once get_template_directory() . '/walkers/legallinks-footer-menu-walker.php';
require_once get_template_directory() . '/walkers/footerbottom-menu-walker.php';

/**
* Widgets File.
*/
require get_template_directory() . '/inc/widgets.php';


// Include custompostypes
require get_template_directory() . '/inc/product-post-type.php';
require get_template_directory() . '/inc/investor-post-type.php';
require get_template_directory() . '/inc/career-post-type.php';
require get_template_directory() . '/inc/service-post-type.php';
require get_template_directory() . '/inc/course-post-type.php';
require get_template_directory() . '/inc/leaders-post-type.php';
require get_template_directory() . '/inc/partner-post-type.php';
require get_template_directory() . '/inc/globalBlocks-post-type.php';
require get_template_directory() . '/inc/review-post-type.php';
require get_template_directory() . '/inc/faq-post-type.php';
require get_template_directory() . '/inc/featuredPost-post-type.php';


add_action( 'pre_get_posts', 'change_Leaders_sort_order'); 
function change_Leaders_sort_order($query){
    if(is_post_type_archive('leaders')):
        //If you wanted it for the archive of a custom post type use: is_post_type_archive( $post_type )
        //Set the order ASC or DESC
        $query->set( 'order', 'DESC' );
        //Set the orderby
        $query->set( 'orderby', 'title' );
    endif;    
};

add_filter( 'get_the_archive_title', function ( $title ) {
    if( is_category() ) {
        $title = single_cat_title( '', false );
    }
    return $title;

});


add_action( 'add_meta_boxes', 'featuredPost_meta_box');
function featuredPost_meta_box(){
  add_meta_box( 'my-meta-box-id', __( 'Feature post', 'felicityhealth' ), 'featured_postmarkup_function', 'post', 'side', 'high' );
}


function featured_postmarkup_function($post) {

  $values = get_post_custom( $post->ID );
  //retrieve the meta data values if they exist
  $selected = isset( $values['featured_post_select'] ) ? esc_attr( $values['featured_post_select'][0] ) : '';
  // We'll use this nonce field later on when saving.
  wp_nonce_field( 'featuredPost_meta_box_nonce', 'meta_box_nonce' );
  ?>
<p>Select yes below to make post featured</p>
<p>
    <label for="featured_post_select">Featured: </label>
    <select name="featured_post_select">
        <option value="no" <?php selected( $selected, 'no' ); ?>>No</option>
        <option value="yes" <?php selected( $selected, 'yes' ); ?>>Yes</option>
    </select>
</p>
<?php
}

//hook to save the meta box data
add_action( 'save_post', 'featured_post_save_meta' );
function featured_post_save_meta( $post_id ) {

    // Bail if we're doing an auto save
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
     
    // if our nonce isn't there, or we can't verify it, bail
    if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'featuredPost_meta_box_nonce' ) ) return;
     
    // if our current user can't edit this post, bail
    if( !current_user_can( 'edit_post' ) ) return;
   
    // now we can actually save the data
    // Make sure your data is set before trying to save it
    if( isset( $_POST['featured_post_select'] ) )
        update_post_meta( $post_id, 'featured_post_select', esc_attr( $_POST['featured_post_select'] ) );
}

// Custom function
function get_post_id_by_slug( $slug, $post_type = "Homepage" ) {
    $query = new WP_Query(
        array(
            'name'   => $slug,
            'post_type'   => $post_type,
            'numberposts' => 1,
            'fields'      => 'ids',
            'no_found_rows' => true
        ));
    $posts = $query->get_posts();
    return array_shift( $posts );
}
 
// function my_custom_columns_list($columns) {

//     $columns['order_no']     = 'Order';
     
//     return $columns;
// }
// add_filter( 'manage_leaders_posts_columns', 'my_custom_columns_list' );


add_filter( 'manage_leaders_posts_columns', 'set_custom_edit_leader_columns' );
add_action( 'manage_leaders_posts_custom_column' , 'custom_leader_column', 10, 2 );
 
function set_custom_edit_leader_columns($columns) {
    unset( $columns['date'] );
    $columns['order_no'] = __( 'Order', 'felicityhealth' );
    return $columns;
}
 
function custom_leader_column( $column, $post_id ) {
    switch ( $column ) {
        case 'order_no' :
            echo get_post_meta( $post_id , 'order_no' , true ); 
            break;
    }
}



// Polylang Shortcode - https://wordpress.org/plugins/polylang/
// Put shortcode [polylang] to post/page for display flags

// function polylang_shortcode() {
// 	ob_start();
// 	pll_the_languages(array(
//         'dropdown' => 1,
//         'show_flags'=>0,
//         'show_names'=>1
//         )
//     );
// 	$flags = ob_get_clean();
// 	return $flags;
// }
// add_shortcode( 'polylang', 'polylang_shortcode' );

 
/**
 * Polylang Shortcode - https://wordpress.org/plugins/polylang/
 * Add this code in your functions.php
 * Put shortcode [polylang_langswitcher] to post/page for display flags
 *
 * @return string
 */
function custom_polylang_langswitcher() {
	$output = '';
	if ( function_exists( 'pll_the_languages' ) ) {
		$args   = [
			'show_flags' => 1,
			'show_names' => 1,
			'echo'       => 0,
            'hide_if_empty' => 1,
		];
		$output = '<ul class="polylang_langswitcher language-list">'.pll_the_languages( $args ). '</ul>';
	}

	return $output;
}

add_shortcode( 'polylang_langswitcher', 'custom_polylang_langswitcher' );



// add_action('init', function() {
//     pll_register_string('felicity-course_description', 'Course description');
// });

add_filter('get_the_archive_title', function ($title) {
    if (is_category()) {
        $title = single_cat_title('', false);
    } elseif (is_tag()) {
        $title = single_tag_title('', false);
    } elseif (is_author()) {
        $title = '<span class="vcard">' . get_the_author() . '</span>';
    } elseif (is_tax()) { //for custom post types
        $title = sprintf(__('%1$s'), single_term_title('', false));
    } elseif (is_post_type_archive()) {
        $title = post_type_archive_title('', false);
    }
    return $title;
});

function felicity_comment($comment, $args, $depth) {
    if ( 'div' === $args['style'] ) {
        $tag       = 'div';
        $add_below = 'comment';
    } else {
        $tag       = 'li';
        $add_below = 'div-comment';
    }?>
     <div class="py-4">
        <<?php echo $tag; ?> <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent'.' d-flex align-items-center justify-content-between pb-2 mb-1' ); ?> id="comment-<?php comment_ID() ?>"><?php 
            
            if ( $args['has_children'] ) { ?>
                <!-- <span class="position-absolute top-0 start-0 w-1 h-100 bg-primary"></span> -->
            <?php  } ?>

            <?php if ( 'div' != $args['style'] ) { ?>
                <div id="div-comment-<?php comment_ID() ?>" class="comment-body">
            <?php  } ?>
            <div class="comment-author vcard d-flex align-items-center me-3">
                <?php 
                    if ( $args['avatar_size'] != 0 ) {
                        echo get_avatar( $comment, $args['avatar_size'], '', '', array( 'class' => 'rounded-circle' ) ); 
                    } 
                ?>
                <div class="ps-3">
                    <?php 
                        printf( __( ' <h6 class="fw-semibold mb-0">%s</h6>' ), get_comment_author_link() ); 
                    ?>
                    <span class="fs-sm text-muted">
                        <a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ); ?>"><?php
                            /* translators: 1: date, 2: time */
                            printf( 
                                __('%1$s at %2$s'), 
                                get_comment_date(),  
                                get_comment_time() 
                            ); ?>
                        </a>
                    </span>
                </div>
            </div>
            <div class="comment-meta commentmetadata d-flex justify-content-center align-items-center">
                <div class="reply me-2">
                <?php 
                    comment_reply_link( 
                        array_merge( 
                            $args, 
                            array( 
                                'reply_text' => '<i class="bx bx-share fs-lg me-2"></i> '.__( 'Reply', 'felicityhealth' ),
                                'after' => '',
                                'add_below' => $add_below, 
                                'depth'     => $depth, 
                                'max_depth' => $args['max_depth'] 
                            ) 
                        ) 
                    ); 
                ?>
                </div>
                <?php edit_comment_link( '<i class="bx bx-edit fs-lg me-2"></i> '.__( 'Edit', 'felicityhealth' ), '  ', '' ); ?>
            </div>
        </div>
        <div class="mb-0 pb-2"><?php comment_text(); ?></div>
        <p class="mb-0 pb-2">
            <?php if ( $comment->comment_approved == '0' ) { ?>
                <em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.' ); ?></em><br/>
                <?php }?>
        </p>
        <?php 
        $replies = get_comments( array( 'parent' => $comment->comment_ID, 'status' => 'approve', 'order' => 'ASC' ) );
        // print_r($replies);
        ?>
        <!-- Comment reply -->
        <?php foreach ($replies as $comment):?>
            <div class="position-relative ps-4 mt-4">
                <span class="position-absolute top-0 start-0 w-1 h-100 bg-primary"></span>
                <div class="d-flex align-items-center justify-content-between ps-3 pb-2 mb-1">
                    <div class="comment-author vcard d-flex align-items-center me-3">
                        <?php 
                            if ( $args['avatar_size'] != 0 ) {
                                echo get_avatar( $comment, $args['avatar_size'], '', '', array( 'class' => 'rounded-circle' ) ); 
                            } 
                        ?>
                        <div class="ps-3">
                            <?php 
                                printf( __( ' <h6 class="fw-semibold mb-0">%s</h6>' ), get_comment_author_link() ); 
                            ?>
                            <span class="fs-sm text-muted">
                                <a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ); ?>"><?php
                                    /* translators: 1: date, 2: time */
                                    printf( 
                                        __('%1$s at %2$s'), 
                                        get_comment_date(),  
                                        get_comment_time() 
                                    ); ?>
                                </a>
                            </span>
                        </div>
                    </div>
                    <div class="comment-meta commentmetadata d-flex justify-content-center align-items-center">
                        <div class="reply me-2">
                        <?php 
                            comment_reply_link( 
                                array_merge( 
                                    $args, 
                                    array( 
                                        'reply_text' => '<i class="bx bx-share fs-lg me-2"></i> '.__( 'Reply', 'felicityhealth' ),
                                        'after' => '',
                                        'add_below' => $add_below, 
                                        'depth'     => $depth, 
                                        'max_depth' => $args['max_depth'] 
                                    ) 
                                ) 
                            ); 
                        ?>
                        </div>
                        <?php edit_comment_link( '<i class="bx bx-edit fs-lg me-2"></i> '.__( 'Edit', 'felicityhealth' ), '  ', '' ); ?>
                    </div>
                </div>
                <p class="ps-3 mb-0"><a href="#" class="fw-semibold text-decoration-none">@<?= $comment->comment_author;?></a>
                    <?= $comment->comment_content;?> </p>
            </div>
            <?php endforeach ?>
        
 
        <?php  if ( 'div' != $args['style'] ) : ?> </div> <?php endif;?>
        </div>
        <hr class="my-2">
    <?php } ?>
<?php
    function felicity_comment_reply_link_class( $class ) {
        $class = str_replace( "class='comment-reply-link", "class='comment-reply-link nav-link fs-sm px-0", $class );
        return $class;
    }
    add_filter( 'comment_reply_link', 'felicity_comment_reply_link_class' );

    function felicity_comment_edit_link_class( $class ) {
        $class = str_replace( 'class="comment-edit-link"', 'class="comment-edit-link nav-link fs-sm px-0"', $class );
        return $class;
    }
    add_filter( 'edit_comment_link', 'felicity_comment_edit_link_class' );


    function felicity_cancel_comment_reply_link_class( $class ) {
        $class = str_replace( 'id="cancel-comment-reply-link"', 'id="cancel-comment-reply-link" style="float: right;" class="nav-link fs-sm px-0"', $class );
        return $class;
    }
    add_filter( 'cancel_comment_reply_link', 'felicity_cancel_comment_reply_link_class' );

    // define the comment_form_before callback 
    function action_comment_form_before( $array ) { 
        echo ('<section class="container mb-4 pb-2 mb-md-5 pb-lg-5">
                <div class="row gy-5">
                    <!-- Comment form -->
                    <div class="col-lg-9">
                    <div class="card p-md-5 p-4 border-0 bg-secondary">
                        <div class="card-body w-100 mx-auto px-0" style="max-width: 746px;">');
            }; 
    // define the comment_form_after callback 
    function action_comment_form_after( $array ) { 
        echo ('</section>
                </div>
                    <!-- Comment form -->
                    </div>
                    </div">
                        </div>');
            }; 
            
    // add the action 
    add_action( 'comment_form_before', 'action_comment_form_before', 10, 1 ); 
    add_action( 'comment_form_after', 'action_comment_form_after', 10, 1 ); 

    // overide the comment form markup
    function validate_comment_form($args){
        ob_start();
        comment_form($args);
        echo str_replace('<form','<form novalidate ',ob_get_clean());
    }
    function custom_excerpt_length( $length ) {
        return 20;
    }
    add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

 
    // Get subpages of a particular page

    function has_children() {
      global $post;
      
      $pages = get_pages('child_of=' . $post->ID);
      
      if (count($pages) > 0):
        // echo 'has subpages';
        return true;
      else:
        // echo 'no subpages';
        return false;
      endif;
    }
    
    function is_top_level() {

      global $post, $wpdb;
      $current_page = $wpdb->get_var("SELECT post_parent FROM $wpdb->posts WHERE ID = " . $post->ID);
      
      return $current_page;
    }
    
   