<?php

add_action('pre_get_posts', 'alter_query');
function alter_query($query)
{
    if ($query->is_main_query() && is_home())
        $query->set('orderby', 'rand'); //Set the order to random
}

function set_posts_per_page($query)
{
    if ($query->is_main_query() && is_home())
        $query->set('posts_per_page', 12);
    return $query;
}
add_action('pre_get_posts', 'set_posts_per_page', 11);



/**
 * mangosm functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package mangosm
 */

if (!function_exists('mangosm_setup')):
    /**
     * 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 mangosm_setup()
    {
        /*
         * Make theme available for translation.
         * Translations can be filed in the /languages/ directory.
         * If you're building a theme based on mangosm, use a find and replace
         * to change 'mangosm' to the name of your theme in all the template files.
         */
        load_theme_textdomain('mangosm', get_template_directory() . '/languages');

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

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

        /* add_theme_support('custom-logo', [
            'height' => 61,
            'width' => 60,
            'flex-height' => true,
            'flex-width' => true,
            'header-text' => ['site-title', 'site-description'],
        ]); */
        /*
         * 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');

        // This theme uses wp_nav_menu() in one location.
        register_nav_menus([
            'menu-1' => esc_html__('Primary', 'mangosm'),
        ]);

        /*
         * Switch default core markup for search form, comment form, and comments
         * to output valid HTML5.
         */
        add_theme_support('html5', [
            'comment-form',
            'comment-list',
            'caption',
        ]);


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

        /**
         * Add support for core custom logo.
         *
         * @link https://codex.wordpress.org/Theme_Logo
         */
        /*
         * This theme styles the visual editor to resemble the theme style,
         * specifically font, colors, and column width.
         */
        add_editor_style('assets/css/editor.css');

        /**
         * Image Size
         */
        add_image_size('mangosm-default', 392, 260, true);
    }
endif;
add_action('after_setup_theme', 'mangosm_setup');

/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 *
 * Priority 0 to make it available to lower priority callbacks.
 *
 * @global int $content_width
 */
function mangosm_content_width()
{
    // 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('mangosm_content_width', 640);
}
add_action('after_setup_theme', 'mangosm_content_width', 0);

/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function mangosm_widgets_init()
{
    register_sidebar([
        'name' => esc_html__('Sidebar', 'mangosm'),
        'id' => 'sidebar-1',
        'description' => esc_html__('Add widgets here.', 'mangosm'),
        '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(
            'name' => esc_html__('Footer 1', 'mangosm'),
            'id' => 'mangosm_footer_section_1',
            'description' => esc_html__('Add widgets in your first footer of theme.', 'mangosm'),
            'before_widget' => '<aside id="%1$s" class="widget %2$s">',
            'after_widget' => '</aside>',
            'before_title' => '<h2 class="widget-title">',
            'after_title' => '</h2>',
        )
    );
    register_sidebar(
        array(
            'name' => esc_html__('Footer 2', 'mangosm'),
            'id' => 'mangosm_footer_section_2',
            'description' => esc_html__('Add widgets in your second footer of  theme.', 'mangosm'),
            'before_widget' => '<aside id="%1$s" class="widget %2$s">',
            'after_widget' => '</aside>',
            'before_title' => '<h2 class="widget-title">',
            'after_title' => '</h2>',
        )
    );
    register_sidebar(
        array(
            'name' => esc_html__('Footer 3', 'mangosm'),
            'id' => 'mangosm_footer_section_3',
            'description' => esc_html__('Add widgets in your third footer of  theme.', 'mangosm'),
            'before_widget' => '<aside id="%1$s" class="widget %2$s">',
            'after_widget' => '</aside>',
            'before_title' => '<h2 class="widget-title">',
            'after_title' => '</h2>',
        )
    );
    register_sidebar(
        array(
            'name' => esc_html__('Footer 4', 'mangosm'),
            'id' => 'mangosm_footer_section_4',
            'description' => esc_html__('Add widgets in your fourth footer of  theme.', 'mangosm'),
            'before_widget' => '<aside id="%1$s" class="widget %2$s">',
            'after_widget' => '</aside>',
            'before_title' => '<h2 class="widget-title">',
            'after_title' => '</h2>',
        )
    );
}
add_action('widgets_init', 'mangosm_widgets_init');


/**
 * Enqueue scripts and styles.
 */
function mangosm_scripts()
{   

    wp_dequeue_style( 'wp-block-library' );
    wp_dequeue_style( 'wp-block-library-theme' );


    wp_enqueue_style('bootstrap', get_template_directory_uri() . '/assets/css/bootstrap.css');
    wp_enqueue_style('mangosm-style', get_stylesheet_uri());

    if (is_page_template('template-manga-homepage.php')) {

        wp_enqueue_style('manga-homepage-css', get_template_directory_uri() . '/css/manga-homepage.css');
        wp_register_script('custom-manga-script', get_template_directory_uri() . '/js/custom-manga-page.js', array(), '1.0', true);

        wp_enqueue_script('custom-manga-script');
    }

    if (is_singular('comic')) {
        wp_enqueue_style('comic-custom-style', get_template_directory_uri() . '/css/single-comic.css');
        wp_enqueue_script('comic-custom-script', get_template_directory_uri() . '/js/single-chapter.js', [], null, true);
    }
        
    wp_enqueue_script('mangosm-custom-js', get_template_directory_uri() . '/assets/js/custom.js', [], false, true);    

    wp_enqueue_script('custom-loader-js', get_template_directory_uri() . '/js/custom-loader.js', [], null, true);


    

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

/**
 * Implement the Custom Header feature.
 */
require get_template_directory() . '/inc/custom-header.php';

/**
 * Custom template tags for this theme.
 */
require get_template_directory() . '/inc/template-tags.php';

/**
 * Functions which enhance the theme by hooking into WordPress.
 */
require get_template_directory() . '/inc/template-functions.php';

/**
 * Customizer additions.
 */
require get_template_directory() . '/inc/customizer.php';

/**
 * Load plugin recommendations.
 */
require get_template_directory() . '/inc/tgm/tgm.php';

/**
 * Load Jetpack compatibility file.
 */
if (defined('JETPACK__VERSION')) {
    require get_template_directory() . '/inc/jetpack.php';
}


if (!function_exists('mangosm_pro_custom_query_vars')):

    /**
     * Update Query
     *
     * @param $query
     * @return mixed
     */
    function mangosm_custom_query_vars($query)
    {
        if (!is_admin() && is_home() && is_front_page() && $query->is_main_query()) {
            $mangosm_pro_paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
            $query->set('posts_per_page', 16);
            $query->set('paged', $mangosm_pro_paged);
        }

        return $query;
    }
    add_action('pre_get_posts', 'mangosm_custom_query_vars');

endif;


//mangosm footer count function
if (!function_exists('mangosm_footer_count')):

    function mangosm_footer_count()
    {
        $mangosm_count = 0;
        if (is_active_sidebar('mangosm_footer_section_1'))
            $mangosm_count++;

        if (is_active_sidebar('mangosm_footer_section_2'))
            $mangosm_count++;

        if (is_active_sidebar('mangosm_footer_section_3'))
            $mangosm_count++;

        if (is_active_sidebar('mangosm_footer_section_4'))
            $mangosm_count++;

        return $mangosm_count;
    }

endif;


/* Registering Comic POst Type */
function create_comic_post_type()
{
    $labels = array(
        'name' => _x('Comics', 'Post type general name', 'textdomain'),
        'singular_name' => _x('Comic', 'Post type singular name', 'textdomain'),
        'menu_name' => _x('Comics', 'Admin Menu text', 'textdomain'),
        'name_admin_bar' => _x('Comic', 'Add New on Toolbar', 'textdomain'),
        'add_new' => __('Add New', 'textdomain'),
        'add_new_item' => __('Add New Comic', 'textdomain'),
        'new_item' => __('New Comic', 'textdomain'),
        'edit_item' => __('Edit Comic', 'textdomain'),
        'view_item' => __('View Comic', 'textdomain'),
        'all_items' => __('All Comics', 'textdomain'),
        'search_items' => __('Search Comics', 'textdomain'),
        'parent_item_colon' => __('Parent Comics:', 'textdomain'),
        'not_found' => __('No comics found.', 'textdomain'),
        'not_found_in_trash' => __('No comics found in Trash.', 'textdomain'),
        'featured_image' => _x('Comic Cover Image', 'Overrides the “Featured Image” phrase for this post type. Added in 4.3', 'textdomain'),
        'set_featured_image' => _x('Set comic cover image', 'Overrides the “Set featured image” phrase for this post type. Added in 4.3', 'textdomain'),
        'remove_featured_image' => _x('Remove comic cover image', 'Overrides the “Remove featured image” phrase for this post type. Added in 4.3', 'textdomain'),
        'use_featured_image' => _x('Use as comic cover image', 'Overrides the “Use as featured image” phrase for this post type. Added in 4.3', 'textdomain'),
        'archives' => _x('Comic archives', 'The post type archive label used in nav menus. Default “Post Archives”. Added in 4.4', 'textdomain'),
        'insert_into_item' => _x('Insert into comic', 'Overrides the “Insert into post”/”Insert into page” phrase (used when inserting media into a post). Added in 4.4', 'textdomain'),
        'uploaded_to_this_item' => _x('Uploaded to this comic', 'Overrides the “Uploaded to this post”/”Uploaded to this page” phrase (used when viewing media attached to a post). Added in 4.4', 'textdomain'),
        'filter_items_list' => _x('Filter comics list', 'Screen reader text for the filter links heading on the post type listing screen. Default “Filter posts list”/”Filter pages list”. Added in 4.4', 'textdomain'),
        'items_list_navigation' => _x('Comics list navigation', 'Screen reader text for the pagination heading on the post type listing screen. Default “Posts list navigation”/”Pages list navigation”. Added in 4.4', 'textdomain'),
        'items_list' => _x('Comics list', 'Screen reader text for the items list heading on the post type listing screen. Default “Posts list”/”Pages list”. Added in 4.4', 'textdomain'),

    );

    $args = array(
        'labels' => $labels,
        'public' => true,
        'show_in_rest' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'query_var' => true,
        'rewrite' => array('slug' => 'comic'), // Custom slug
        'capability_type' => 'post',
        'has_archive' => true,
        'hierarchical' => false,
        'supports' => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'tags'), // Added tags support
        'taxonomies' => array('post_tag'), // Enable tags
        'menu_icon' => 'dashicons-book',
        'menu_position' => 4,
    );

    register_post_type('comic', $args);
}
add_action('init', 'create_comic_post_type');



/* Adding breadcrumbs */
function comic_breadcrumbs()
{
    // Settings
    $home_title = 'Home';

    // Get the query & post information
    global $post;

    // Do not display on the homepage
    if (!is_front_page()) {
        echo '<ul class="list-unstyled row" id="comic-breadcrumbs">';

        // Home page
        echo '<li class="item-home "><a class="bread-link bread-home" href="' . get_home_url() . '" title="' . $home_title . '">' . $home_title . '</a></li>';

        if (is_singular('comic')) {
            // Custom post type archive link
            echo '<li class="item-archive comic-breadcrumbs-item"><a class="bread-archive" href="' . get_post_type_archive_link('comic') . '" title="Comic">Comics</a></li>';

            // Display the post title
            echo '<li class="item-current comic-breadcrumbs-item item-' . $post->ID . '"><span class="bread-current bread-' . $post->ID . '" title="' . get_the_title() . '">' . get_the_title() . '</span></li>';
        }

        echo '</ul>';
    }
}


/* Setting Up chapter order */


add_action('save_post_comic', 'set_comic_menu_order', 10, 3);

function set_comic_menu_order($post_id, $post, $update)
{
    // Check if it's a new post and not an update
    if ('comic' !== get_post_type($post_id)) {
        return;
    }

    // Check if this is a REST API request or an admin request
    $is_rest_api_request = defined('REST_REQUEST') && REST_REQUEST;
    $is_admin_request = is_admin();

    // If it's a REST API request or an admin request and it's a new post
    if (($is_rest_api_request || $is_admin_request) && !$update) {
        global $wpdb;

        // Get the latest menu order
        $latest_menu_order = (int) $wpdb->get_var(
            "SELECT MAX(menu_order) FROM $wpdb->posts WHERE post_type = 'comic'"
        );

        // Increment the menu order for new comic posts
        $latest_menu_order++;

        // Update the post in the database
        $wpdb->update(
            $wpdb->posts,
            array('menu_order' => $latest_menu_order),
            array('ID' => $post_id)
        );

        // No need to update the option since we're directly updating the database

        // Optional: Update post modified time to trigger correct ordering in queries
        #wp_update_post(array('ID' => $post_id));

        // Flush rewrite rules to ensure proper ordering
        flush_rewrite_rules();
    }
}





/* Custom Home Page Settings */
// Add meta boxes
function add_manga_meta_boxes()
{
    add_meta_box(
        'manga_meta_box',
        'Manga Details',
        'manga_meta_box_html',
        'page',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'add_manga_meta_boxes');

// HTML content for meta boxes
function manga_meta_box_html($post)
{
    $rating = get_post_meta($post->ID, 'rating', true);
    $genre = get_post_meta($post->ID, 'genre', true);
    $description = get_post_meta($post->ID, 'description', true);
    $alternative = get_post_meta($post->ID, 'alternative', true);
    $manga_title = get_post_meta($post->ID, 'manga_title', true);
    $authors = get_post_meta($post->ID, 'authors', true);
    $artists = get_post_meta($post->ID, 'artists', true);
    $release_year = get_post_meta($post->ID, 'release_year', true);
    $status = get_post_meta($post->ID, 'status', true);
    $type = get_post_meta($post->ID, 'type', true);
    $cover_image = get_post_meta($post->ID, 'cover_image', true);

    ?>
    <table>
        <tr>
            <td><label for="manga_title">Manga Title:</label></td>
            <td><input type="text" id="manga_title" name="manga_title" value="<?php echo esc_attr($manga_title); ?>" /></td>
        </tr>

        <tr>
            <td><label for="alternative">Alternative Title:</label></td>
            <td><input type="text" id="alternative" name="alternative" value="<?php echo esc_attr($alternative); ?>" /></td>
        </tr>

        <tr>
            <td><label for="genre">Genres (comma separated):</label></td>
            <td><input type="text" id="genre" name="genre" value="<?php echo esc_attr($genre); ?>" /></td>
        </tr>

        <tr>
            <td><label for="description">Description:</label></td>
            <td><textarea id="description" cols="80" rows="8"
                    name="description"><?php echo esc_textarea($description); ?></textarea></td>
        </tr>

        <tr>
            <td><label for="authors">Author(s):</label></td>
            <td><input type="text" id="authors" name="authors" value="<?php echo esc_attr($authors); ?>" /></td>
        </tr>

        <tr>
            <td><label for="artists">Artist(s):</label></td>
            <td><input type="text" id="artists" name="artists" value="<?php echo esc_attr($artists); ?>" /></td>
        </tr>

        <tr>
            <td><label for="release_year">Release Year:</label></td>
            <td><input type="number" id="release_year" name="release_year" value="<?php echo esc_attr($release_year); ?>" />
            </td>
        </tr>

        <tr>
            <td><label for="rating">Rating (0-5):</label></td>
            <td><input type="number" id="rating" name="rating" value="<?php echo esc_attr($rating); ?>" min="0" max="5"
                    step="0.5" /></td>
        </tr>

        <tr>
            <td><label for="status">Status:</label></td>
            <td>
                <select id="status" name="status">
                    <option value="ongoing" <?php selected($status, 'ongoing'); ?>>Ongoing</option>
                    <option value="completed" <?php selected($status, 'completed'); ?>>Completed</option>
                    <option value="upcoming" <?php selected($status, 'upcoming'); ?>>Upcoming</option>
                    <option value="dropped" <?php selected($status, 'dropped'); ?>>Dropped</option>
                    <option value="hiatus" <?php selected($status, 'hiatus'); ?>>Hiatus</option>
                </select>
            </td>
        </tr>

        <tr>
            <td><label for="type">Type:</label></td>
            <td>
                <select id="type" name="type">
                    <option value="Manga" <?php selected($type, 'Manga'); ?>>Manga</option>
                    <option value="Manhwa" <?php selected($type, 'Manhwa'); ?>>Manhwa</option>
                    <option value="Manhua" <?php selected($type, 'Manhua'); ?>>Manhua</option>
                    <option value="comic" <?php selected($type, 'comic'); ?>>Comic</option>
                </select>
            </td>
        </tr>

        <tr>
            <td><label style="vertical-align:text-top;" for="cover_image">Cover Image:</label></td>
            <td>
                <input type="hidden" id="cover_image" name="cover_image" value="<?php echo esc_url($cover_image); ?>" />
                <img id="cover_image_preview" src="<?php echo esc_url($cover_image); ?>"
                    style="max-width: 100%; height: auto;" />
                <br>
                <button type="button" id="upload_cover_image_button" class="button">Upload Cover Image</button>
            </td>
        </tr>
    </table>

    <?php
}

// Save meta box data
function save_manga_meta_box_data($post_id)
{
    if (array_key_exists('rating', $_POST)) {
        update_post_meta($post_id, 'rating', sanitize_text_field($_POST['rating']));
    }
    if (array_key_exists('genre', $_POST)) {
        update_post_meta($post_id, 'genre', sanitize_textarea_field($_POST['genre']));
    }
    if (array_key_exists('description', $_POST)) {
        update_post_meta($post_id, 'description', sanitize_textarea_field($_POST['description']));
    }
    if (array_key_exists('alternative', $_POST)) {
        update_post_meta($post_id, 'alternative', sanitize_text_field($_POST['alternative']));
    }
    if (array_key_exists('manga_title', $_POST)) {
        update_post_meta($post_id, 'manga_title', sanitize_text_field($_POST['manga_title']));
    }
    if (array_key_exists('authors', $_POST)) {
        update_post_meta($post_id, 'authors', sanitize_text_field($_POST['authors']));
    }
    if (array_key_exists('artists', $_POST)) {
        update_post_meta($post_id, 'artists', sanitize_text_field($_POST['artists']));
    }
    if (array_key_exists('release_year', $_POST)) {
        update_post_meta($post_id, 'release_year', sanitize_text_field($_POST['release_year']));
    }
    if (array_key_exists('status', $_POST)) {
        update_post_meta($post_id, 'status', sanitize_text_field($_POST['status']));
    }
    if (array_key_exists('type', $_POST)) {
        update_post_meta($post_id, 'type', sanitize_text_field($_POST['type']));
    }
    if (array_key_exists('cover_image', $_POST)) {
        update_post_meta($post_id, 'cover_image', esc_url_raw($_POST['cover_image']));
    }
}
add_action('save_post', 'save_manga_meta_box_data');


function enqueue_custom_meta_box_script()
{
    wp_enqueue_script('custom-meta-box', get_template_directory_uri() . '/js/custom-meta-box.js', array('jquery'), null, true);
}
add_action('admin_enqueue_scripts', 'enqueue_custom_meta_box_script');


/* Star Rating generation function */
function get_star_rating_html($rating)
{
    // If rating is above 5, divide it by 2
    if ($rating > 5) {
        $rating /= 2;
    }

    $full_star = '<i class="icon-star"></i>';
    $half_star = '<i class="icon-star-half-empty"></i>';
    $empty_star = '<i class="icon-star-o"></i>';
    $output = '';

    if ($rating == ''){
        $output .= str_repeat($empty_star, 5);
        return $output;
    }
    // Number of full stars
    $full_stars = floor($rating);
    // Number of half stars
    $half_stars = ceil($rating - $full_stars);
    // Number of empty stars
    $empty_stars = 5 - $full_stars - $half_stars;

    $output .= str_repeat($full_star, $full_stars);
    $output .= str_repeat($half_star, $half_stars);
    $output .= str_repeat($empty_star, $empty_stars);

    return $output;
}



/* Extract Chapter number from title */
function extract_chapter_title($title)
{
    // Use regular expression to find "Chapter" or "chapter" and anything after it
    if (preg_match('/(Chapter|chapter)\s[0-9]+.*/', $title, $matches)) {
        return $matches[0];
    }
    // If no match is found, return the full title as a fallback
    return $title;
}



// Add custom columns to admin post list
add_filter('manage_edit-comic_columns', 'custom_comic_columns');

function custom_comic_columns($columns)
{
    // Add a new column for menu_order after the title column
    $columns['menu_order'] = 'Menu Order';

    return $columns;
}

// Populate custom column with menu_order value
add_action('manage_comic_posts_custom_column', 'custom_comic_column_content', 10, 2);

function custom_comic_column_content($column_name, $post_id)
{
    if ($column_name === 'menu_order') {
        // Get the menu_order value for the post
        $menu_order = get_post_field('menu_order', $post_id);
        echo $menu_order;
    }
}

// Modify the query to order by menu_order in the admin for the comic post type
add_action('pre_get_posts', 'sort_comic_posts_by_menu_order');

function sort_comic_posts_by_menu_order($query) {
    // Check if we are in the admin area and the current post type is 'comic'
    if (is_admin() && $query->is_main_query() && $query->get('post_type') === 'comic') {
        // Set the query to order by menu_order
        $query->set('orderby', 'menu_order');
        $query->set('order', 'DESC'); // Change to 'DESC' for descending order
    }
}



// Custom Recent Posts Widget for Mangosm
class Custom_Recent_Posts_Widget extends WP_Widget
{

    public function __construct()
    {
        parent::__construct(
            'custom_recent_posts_widget', // Base ID
            __('Mangosm Custom Recent Comics', 'text_domain'), // Name
            array('description' => __('A Custom Recent Comics Widget for Mangosm', 'text_domain'), ) // Args
        );
    }

    public function widget($args, $instance)
    {
        echo $args['before_widget'];
        if (!empty($instance['title'])) {
            echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
        }

        // Custom query to get recent posts
        $query_args = array(
            'post_type' => 'comic', // Change this to your custom post type
            'posts_per_page' => !empty($instance['number']) ? $instance['number'] : 5,
            'order' => 'DESC',
            'orderby' => 'menu_order'
        );

        $recent_posts = new WP_Query($query_args);

        if ($recent_posts->have_posts()) {
            echo '<ul>';
            while ($recent_posts->have_posts()) {
                $recent_posts->the_post();
                echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
            }
            echo '</ul>';
        } else {
            echo '<p>' . __('No posts found.', 'text_domain') . '</p>';
        }

        wp_reset_postdata();

        echo $args['after_widget'];
    }

    public function form($instance)
    {
        $title = !empty($instance['title']) ? $instance['title'] : __('Recent Posts', 'text_domain');
        $number = !empty($instance['number']) ? $instance['number'] : 5;
        ?>
        <p>
            <label
                for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_attr_e('Title:', 'text_domain'); ?></label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>"
                name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text"
                value="<?php echo esc_attr($title); ?>">
        </p>
        <p>
            <label
                for="<?php echo esc_attr($this->get_field_id('number')); ?>"><?php esc_attr_e('Number of posts to show:', 'text_domain'); ?></label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('number')); ?>"
                name="<?php echo esc_attr($this->get_field_name('number')); ?>" type="number"
                value="<?php echo esc_attr($number); ?>">
        </p>
        <?php
    }

    public function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        $instance['number'] = (!empty($new_instance['number'])) ? strip_tags($new_instance['number']) : '';
        return $instance;
    }
}

function register_custom_recent_posts_widget()
{
    register_widget('Custom_Recent_Posts_Widget');
}
add_action('widgets_init', 'register_custom_recent_posts_widget');

// Custom About Widget for Mangosm
class Custom_About_Widget extends WP_Widget
{

    public function __construct()
    {
        parent::__construct(
            'custom_about_widget', // Base ID
            __('Mangosm Custom About Widget', 'text_domain'), // Name
            array('description' => __('A Custom About Widget for Mangosm', 'text_domain'), ) // Args
        );
    }

    public function widget($args, $instance)
    {
        echo $args['before_widget'];
        if (!empty($instance['title'])) {
            echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
        }

        if (!empty($instance['text'])) {
            echo '<p>' . apply_filters('widget_text', $instance['text']) . '</p>';
        }

        echo $args['after_widget'];
    }

    public function form($instance)
    {
        $title = !empty($instance['title']) ? $instance['title'] : __('About', 'text_domain');
        $text = !empty($instance['text']) ? $instance['text'] : '';
        ?>
        <p>
            <label
                for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_attr_e('Title:', 'text_domain'); ?></label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>"
                name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text"
                value="<?php echo esc_attr($title); ?>">
        </p>
        <p>
            <label
                for="<?php echo esc_attr($this->get_field_id('text')); ?>"><?php esc_attr_e('Text:', 'text_domain'); ?></label>
            <textarea class="widefat" id="<?php echo esc_attr($this->get_field_id('text')); ?>"
                name="<?php echo esc_attr($this->get_field_name('text')); ?>"><?php echo esc_attr($text); ?></textarea>
        </p>
        <?php
    }

    public function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        $instance['text'] = (!empty($new_instance['text'])) ? $new_instance['text'] : '';
        return $instance;
    }
}

function register_custom_about_widget()
{
    register_widget('Custom_About_Widget');
}
add_action('widgets_init', 'register_custom_about_widget');


// Redirect archive pages to the home page
function redirect_archive_pages()
{
    if (
        (is_category() || is_tag() || is_date() || is_author() || is_post_type_archive()) &&
        !is_post_type_archive('character')
    ) {
        wp_redirect(home_url(), 301);
        exit();
    }
}
add_action('template_redirect', 'redirect_archive_pages');



function get_adjacent_post_by_menu_order($current_post_id, $direction = 'next')
{
    global $wpdb;

    // Determine the operator and order based on direction
    $operator = $direction === 'next' ? '>' : '<';
    $order = $direction === 'next' ? 'ASC' : 'DESC';

    // Get the current post's menu_order value
    $current_menu_order = get_post_field('menu_order', $current_post_id);

    // Prepare the query
    $query = $wpdb->prepare("
        SELECT p.ID
        FROM $wpdb->posts p
        WHERE p.menu_order $operator %d
        AND p.post_type = %s
        AND p.post_status = %s
        ORDER BY p.menu_order $order
        LIMIT 1
    ", $current_menu_order, get_post_type($current_post_id), 'publish');

    // Execute the query and get the result
    $result = $wpdb->get_var($query);

    // Return the post object if a result is found
    return $result ? get_post($result) : null;
}


/* add_filter('get_custom_logo', function() {
    $logo = '<a href="' . esc_url(home_url('/')) . '" class="custom-logo-link" rel="home">';
    $logo .= '<img width="60" height="61" src="' . get_template_directory_uri() . '/assets/images/mangosm-logo.webp" 
                   alt="' . get_bloginfo('name') . '" >';
    $logo .= '</a>';
    return $logo;
}); */

//reddirect search results to home page
add_action( 'template_redirect', function() {
    if ( is_search() ) {
        wp_redirect( home_url() );
        exit;
    }
});

add_filter('document_title_parts', function ($title) {
    if (is_post_type_archive('character')) {
        $title['title'] = 'All Characters'; // Browser tab title
    }

    return $title;
});


//Load tsparticles script in footer
add_action('wp_footer', 'custom_tsparticles_footer_script', 9999);
function custom_tsparticles_footer_script() {
    ?>
    <script src="<?php echo get_template_directory_uri(); ?>/js/tsparticles.bundle.min.js" defer></script>
    <?php
}

add_theme_support('title-tag');