<?php
/**
 * Custom template tags for this theme.
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 * @package videoclub
 */

/**
 * Search Filter 
 */
if ( ! function_exists( 'videoclub_search_filter' ) && ( ! is_admin() ) ) :

function videoclub_search_filter($query) {
    if ($query->is_search) {
        $query->set('post_type', 'post');
    }
    return $query;
}

add_filter('pre_get_posts','videoclub_search_filter');

endif;

/**
 * Filter the except length to 40 characters.
 *
 * @param int $length Excerpt length.
 * @return int (Maybe) modified excerpt length.
 */
if ( ! function_exists( 'videoclub_custom_excerpt_length' ) ) :

function videoclub_custom_excerpt_length( $length ) {
    if ( is_admin() ) {
        return $length;
    } else {
       return '40'; 
    }
}
add_filter( 'excerpt_length', 'videoclub_custom_excerpt_length', 999 );

endif;

/**
 * Customize excerpt more.
 */
if ( ! function_exists( 'videoclub_excerpt_more' ) ) :

function videoclub_excerpt_more( $more ) {
    if ( is_admin() ) {
        return $more;
    } else {
        return '... ';
    }
}
add_filter( 'excerpt_more', 'videoclub_excerpt_more' );

endif;

/**
 * Display the first (single) category of post.
 */
if ( ! function_exists( 'videoclub_first_category' ) ) :
function videoclub_first_category() {
    $category = get_the_category();
    if ($category) {
      echo '<a href="' . esc_url( get_category_link( $category[0]->term_id ) ) . '">' . esc_html( $category[0]->name ) .'</a> ';
    }    
}
endif;

/**
 * Returns true if a blog has more than 1 category.
 *
 * @return bool
 */
if ( ! function_exists( 'videoclub_categorized_blog' ) ) :

function videoclub_categorized_blog() {
    if ( false === ( $all_the_cool_cats = get_transient( 'videoclub_categories' ) ) ) {
        // Create an array of all the categories that are attached to posts.
        $all_the_cool_cats = get_categories( array(
            'fields'     => 'ids',
            'hide_empty' => 1,
            // We only need to know if there is more than one category.
            'number'     => 2,
        ) );

        // Count the number of categories that are attached to the posts.
        $all_the_cool_cats = count( $all_the_cool_cats );

        set_transient( 'videoclub_categories', $all_the_cool_cats );
    }

    if ( $all_the_cool_cats > 1 ) {
        // This blog has more than 1 category so videoclub_categorized_blog should return true.
        return true;
    } else {
        // This blog has only 1 category so videoclub_categorized_blog should return false.
        return false;
    }
}

endif;

/**
 * Flush out the transients used in videoclub_categorized_blog.
 */
if ( ! function_exists( 'videoclub_category_transient_flusher' ) ) :

function videoclub_category_transient_flusher() {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    // Like, beat it. Dig?
    delete_transient( 'videoclub_categories' );
}
add_action( 'edit_category', 'videoclub_category_transient_flusher' );
add_action( 'save_post',     'videoclub_category_transient_flusher' );

endif;


/**
 * Fix skip link focus in IE11.
 *
 * This does not enqueue the script because it is tiny and because it is only for IE11,
 * thus it does not warrant having an entire dedicated blocking script being loaded.
 *
 * @link https://git.io/vWdr2
 */
function videoclub_skip_link_focus_fix() {
    // The following is minified via `terser --compress --mangle -- js/skip-link-focus-fix.js`.
    ?>
    <script>
    /(trident|msie)/i.test(navigator.userAgent)&&document.getElementById&&window.addEventListener&&window.addEventListener("hashchange",function(){var t,e=location.hash.substring(1);/^[A-z0-9_-]+$/.test(e)&&(t=document.getElementById(e))&&(/^(?:a|select|input|button|textarea)$/i.test(t.tagName)||(t.tabIndex=-1),t.focus())},!1);
    </script>
    <?php
}
add_action( 'wp_print_footer_scripts', 'videoclub_skip_link_focus_fix' );


/**
 * Twenty Twenty SVG Icon helper functions
 *
 * @package videoclub
 * @subpackage videoclub
 * @since VideoClub 1.0
 */

if ( ! function_exists( 'videoclub_the_theme_svg' ) ) {
    /**
     * Output and Get Theme SVG.
     * Output and get the SVG markup for an icon in the VideoClub_SVG_Icons class.
     *
     * @param string $svg_name The name of the icon.
     * @param string $group The group the icon belongs to.
     * @param string $color Color code.
     */
    function videoclub_the_theme_svg( $svg_name, $group = 'ui', $color = '' ) {
        echo videoclub_get_theme_svg( $svg_name, $group, $color ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped in videoclub_get_theme_svg().
    }
}

if ( ! function_exists( 'videoclub_get_theme_svg' ) ) {

    /**
     * Get information about the SVG icon.
     *
     * @param string $svg_name The name of the icon.
     * @param string $group The group the icon belongs to.
     * @param string $color Color code.
     */
    function videoclub_get_theme_svg( $svg_name, $group = 'ui', $color = '' ) {

        // Make sure that only our allowed tags and attributes are included.
        $svg = wp_kses(
            VideoClub_SVG_Icons::get_svg( $svg_name, $group, $color ),
            array(
                'svg'     => array(
                    'class'       => true,
                    'xmlns'       => true,
                    'width'       => true,
                    'height'      => true,
                    'viewbox'     => true,
                    'aria-hidden' => true,
                    'role'        => true,
                    'focusable'   => true,
                ),
                'path'    => array(
                    'fill'      => true,
                    'fill-rule' => true,
                    'd'         => true,
                    'transform' => true,
                ),
                'polygon' => array(
                    'fill'      => true,
                    'fill-rule' => true,
                    'points'    => true,
                    'transform' => true,
                    'focusable' => true,
                ),
            )
        );

        if ( ! $svg ) {
            return false;
        }
        return $svg;
    }
}


/**
 * Miscellaneous
 */

/**
 * Toggles animation duration in milliseconds.
 *
 * @return int Duration in milliseconds
 */
function videoclub_toggle_duration() {
    /**
     * Filters the animation duration/speed used usually for submenu toggles.
     *
     * @since VideoClub 1.0
     *
     * @param int $duration Duration in milliseconds.
     */
    $duration = apply_filters( 'videoclub_toggle_duration', 250 );

    return $duration;
}


/**
 * Menus
 */

/**
 * Filters classes of wp_list_pages items to match menu items.
 *
 * Filter the class applied to wp_list_pages() items with children to match the menu class, to simplify.
 * styling of sub levels in the fallback. Only applied if the match_menu_classes argument is set.
 *
 * @param string[] $css_class    An array of CSS classes to be applied to each list item.
 * @param WP_Post  $page         Page data object.
 * @param int      $depth        Depth of page, used for padding.
 * @param array    $args         An array of arguments.
 * @param int      $current_page ID of the current page.
 * @return array CSS class names.
 */
function videoclub_filter_wp_list_pages_item_classes( $css_class, $page, $depth, $args, $current_page ) {

    // Only apply to wp_list_pages() calls with match_menu_classes set to true.
    $match_menu_classes = isset( $args['match_menu_classes'] );

    if ( ! $match_menu_classes ) {
        return $css_class;
    }

    // Add current menu item class.
    if ( in_array( 'current_page_item', $css_class, true ) ) {
        $css_class[] = 'current-menu-item';
    }

    // Add menu item has children class.
    if ( in_array( 'page_item_has_children', $css_class, true ) ) {
        $css_class[] = 'menu-item-has-children';
    }

    return $css_class;

}

add_filter( 'videoclub_page_css_class', 'videoclub_filter_wp_list_pages_item_classes', 10, 5 );

/**
 * Adds a Sub Nav Toggle to the Expanded Menu and Mobile Menu.
 *
 * @param stdClass $args  An object of wp_nav_menu() arguments.
 * @param WP_Post  $item  Menu item data object.
 * @param int      $depth Depth of menu item. Used for padding.
 * @return stdClass An object of wp_nav_menu() arguments.
 */
function videoclub_add_sub_toggles_to_main_menu( $args, $item, $depth ) {

    // Add sub menu toggles to the Expanded Menu with toggles.
    if ( isset( $args->show_toggles ) && $args->show_toggles ) {

        // Wrap the menu item link contents in a div, used for positioning.
        $args->before = '<div class="ancestor-wrapper">';
        $args->after  = '';

        // Add a toggle to items with children.
        if ( in_array( 'menu-item-has-children', $item->classes, true ) ) {

            $toggle_target_string = '.menu-modal .menu-item-' . $item->ID . ' > .sub-menu';
            $toggle_duration      = videoclub_toggle_duration();

            // Add the sub menu toggle.
            $args->after .= '<button class="toggle sub-menu-toggle fill-children-current-color" data-toggle-target="' . $toggle_target_string . '" data-toggle-type="slidetoggle" data-toggle-duration="' . absint( $toggle_duration ) . '" aria-expanded="false"><span class="screen-reader-text">' . __( 'Show sub menu', 'videoclub' ) . '</span>' . videoclub_get_theme_svg( 'chevron-down' ) . '</button>';

        }

        // Close the wrapper.
        $args->after .= '</div><!-- .ancestor-wrapper -->';

        // Add sub menu icons to the primary menu without toggles.
    } elseif ( 'left' === $args->theme_location ) {
        if ( in_array( 'menu-item-has-children', $item->classes, true ) ) {
            $args->after = '<span class="icon"></span>';
        } else {
            $args->after = '';
        }
    }

    return $args;

}

add_filter( 'nav_menu_item_args', 'videoclub_add_sub_toggles_to_main_menu', 10, 3 );

/*
 * Customize archive title
 */
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() ) {
            $title = single_term_title( '', false );
        } elseif (is_post_type_archive()) {
            $title = post_type_archive_title( '', false );
        }
    return $title;    
});

/*
 * Check if post content has embed code.
 */
function videoclub_has_embed_code() {

    $content = get_the_content();

    $has_embed =false;

    preg_match  ('/<iframe(.+)\"/', $content, $matches);
    if (!empty($matches)) {
        return true;
    }

    preg_match  ('/<object(.+)\"/', $content, $matches);
    if (!empty($matches)) {
        return true;
    }

    preg_match  ('/<embed(.+)\"/', $content, $matches);
    if (!empty($matches)) {
        return true;
    }

    if (strpos($content, '[embed]') !== false) {
        return true;
    }

    preg_match  ('/<video(.+)\"/', $content, $matches);
    if (!empty($matches)) {
        return true;
    }
    
}

/**
 * Detect if post content has video embed.
 */
if ( ! function_exists( 'videoclub_has_embed' ) ) :

function videoclub_has_embed( $post_id = false ) {
    if( !$post_id )
        $post_id = get_the_ID();
    else
        $post_id = absint( $post_id );
    if( !$post_id )
        return false;
 
    $post_meta = get_post_custom_keys( $post_id );
 	
 	if (!empty($post_meta )) {
	    foreach( $post_meta as $meta ) {
	        if( '_oembed' != substr( trim( $meta ) , 0 , 7 ) )
	            continue;
	        return true;
	    }
	}
    return false;
}

endif;

/* Set posts per page */
if (get_option('posts_per_page') == 10) {
    add_action( 'pre_get_posts',  'set_posts_per_page'  );
}

function set_posts_per_page( $query ) {

  global $wp_the_query;

  if ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_home() ) && ( !is_active_sidebar( 'home' ) ) ) {
    $query->set( 'posts_per_page', 40 );
  }
  if ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_search() ) ) {
    $query->set( 'posts_per_page', 40 );
  }
  elseif ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_archive() ) ) {
    $query->set( 'posts_per_page', 40 );
  }
  // Etc..

  return $query;
}

/**
 * Pro upgrade notice
 */
function videoclub_pro_upgrade_admin_notice() {

    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }
    ?>
    <div class="notice notice-info is-dismissible videoclub-pro-notice videoclub-pro-animate">
        <div class="">

            <div class="videoclub-pro-header">
                <span class="dashicons dashicons-star-filled"></span>
                <strong class="videoclub-pro-title">
                    <?php esc_html_e( 'Upgrade to VideoClub Pro', 'videoclub' ); ?>
                </strong>
            </div>
            <p class="videoclub-pro-desc">
                <?php esc_html_e( 'You are currently using the free version of the VideoClub theme. Upgrade to the Pro version to unlock additional features:', 'videoclub' ); ?>
            </p>
            <ul class="videoclub-pro-features">
                <li><?php esc_html_e( 'Theme Options Panel', 'videoclub' ); ?></li>
                <li><?php esc_html_e( 'One Click Demo Import', 'videoclub' ); ?></li>
                <li><?php esc_html_e( 'Migrate Videos From Other Video Themes', 'videoclub' ); ?></li>
                <li><?php esc_html_e( 'Unlimited Color Schemes', 'videoclub' ); ?></li>
                <li><?php esc_html_e( 'Video Views Count & Video Duration', 'videoclub' ); ?></li>
                <li><?php esc_html_e( 'Post Ratings (Thumbs Up/Down)', 'videoclub' ); ?></li>
                <li><?php esc_html_e( 'Priority Theme Support and More', 'videoclub' ); ?></li>                
            </ul>

            <div class="cta-button">
                <?php 
                    $theme = wp_get_theme();
                ?>
                <a href="<?php echo esc_url( $theme->get( 'AuthorURI' ) . '/themes/videoclub-pro' ); ?>"
                   class="button button-primary videoclub-pro-btn"
                   target="_blank"
                   rel="noopener noreferrer">
                    <?php esc_html_e( 'Upgrade to VideoClub Pro', 'videoclub' ); ?>
                </a>
            </div>

        </div>
    </div>
    <?php
}
add_action( 'admin_notices', 'videoclub_pro_upgrade_admin_notice' );

add_action( 'admin_enqueue_scripts', function () {
    wp_add_inline_style(
        'wp-admin',
        '
        .videoclub-pro-notice {
            padding: 0;
            border-left: none;
            background: transparent;
        }

        .videoclub-pro-animate {
            position: relative;
            padding: 14px 18px 16px;
            background: #fffaf3;
            border-radius: 4px;
        }

        .videoclub-pro-animate::before {
            content: "";
            position: absolute;
            inset: 0;
            border-left: 6px solid #ff9800;
            animation: videoclubBorderPulse 2.2s ease-in-out infinite;
        }

        .videoclub-pro-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 6px;
            position: relative;
            z-index: 1;
        }

        .videoclub-pro-header .dashicons {
            color: #ff9800;
            font-size: 22px;
        }

        .videoclub-pro-title {
            font-size: 14px;
        }

        /* Clean list styling */
        .videoclub-pro-features {
            list-style: none;
            margin: 0 0 10px;
            padding: 0;
            position: relative;
            z-index: 1;
        }

        .videoclub-pro-features li {
            font-size: 13px;
            color: #555;
            padding-left: 20px;
            margin: 2px 0;
            position: relative;
        }

        .videoclub-pro-features li::before {
            content: "\f147"; /* dashicons-yes */
            font-family: dashicons;
            position: absolute;
            left: 0;
            top: 0;
            color: #46b450;
            font-size: 16px;
        }

        .cta-button {
            position: relative;
            z-index: 1;
        }

        @keyframes videoclubBorderPulse {
            0%   { box-shadow: 0 0 0 0 rgba(255,152,0,.35); }
            70%  { box-shadow: 0 0 0 10px rgba(255,152,0,0); }
            100% { box-shadow: 0 0 0 0 rgba(255,152,0,0); }
        }
        '
    );
});

/* Admin Style */
function videoclub_admin_init() {
    if ( is_admin() ) {
        wp_enqueue_style("videoclub-admin-css", get_template_directory_uri() . "/assets/css/admin-style.css", false, "1.0.1", "all");
    }
}
add_action( 'admin_enqueue_scripts', 'videoclub_admin_init' );