<?php

defined( 'ABSPATH' ) || die( "Can't access directly" );
// Constants
define( 'ARCADE_THEME_DIR', get_template_directory() );
define( 'ARCADE_THEME_URI', get_template_directory_uri() );
define( 'ARCADE_THEME_VERSION', wp_get_theme( 'arcade-theme' )->get( 'Version' ) );
define( 'ARCADE_TEMP', trailingslashit( WP_CONTENT_DIR . '/uploads' ) . 'arcade-theme' );
define( 'ARCADE_IMG', trailingslashit( WP_CONTENT_DIR . '/uploads' ) . 'game-images' );
defined( 'WP_HOME' ) or define( 'WP_HOME', home_url( '/' ) );
/**
 * 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 arcade_setup() {
    /*
     * 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' );
    /*
     * Make theme available for translation.
     * Translations can be filed in the /languages/ directory.
     * If you're building a theme based on Arcade Theme, use a find and replace
     * to change 'arcade' to the name of your theme in all the template files.
     */
    load_theme_textdomain( 'arcade', ARCADE_THEME_DIR . '/languages' );
    // Set up the WordPress core custom background feature.
    $defaults = array(
        'default-color'          => '#4fc6f9',
        'default-image'          => '',
        'default-repeat'         => 'repeat',
        'default-position-x'     => 'left',
        'default-position-y'     => 'top',
        'default-size'           => 'auto',
        'default-attachment'     => 'scroll',
        'admin-head-callback'    => '',
        'admin-preview-callback' => '',
    );
    add_theme_support( 'custom-background', $defaults );
    // Custom logo.
    add_theme_support( 'custom-logo', array(
        'width'       => 180,
        'height'      => 48,
        'flex-width'  => true,
        'flex-height' => true,
    ) );
    // Register nav menu's.
    register_nav_menus( array(
        'main'   => __( 'Main Menu', 'arcade' ),
        'footer' => __( 'Footer Menu', 'arcade' ),
    ) );
}

add_action( 'after_setup_theme', 'arcade_setup' );
/**
 * Freemius Integration
 */
if ( !function_exists( 'at_fs' ) ) {
    // Create a helper function for easy SDK access.
    function at_fs() {
        global $at_fs;
        if ( !isset( $at_fs ) ) {
            // Include Freemius SDK.
            require_once dirname( __FILE__ ) . '/freemius/start.php';
            $at_fs = fs_dynamic_init( array(
                'id'               => '15939',
                'slug'             => 'arcade-theme',
                'premium_slug'     => 'arcade-theme-pro',
                'type'             => 'theme',
                'public_key'       => 'pk_8a20eb1d4bab35e8480a43bc98186',
                'is_premium'       => false,
                'premium_suffix'   => 'Lite',
                'has_addons'       => false,
                'has_paid_plans'   => true,
                'is_org_compliant' => false,
                'menu'             => array(
                    'slug'       => 'arcade_theme',
                    'first-path' => 'admin.php?page=arcade_theme',
                    'contact'    => false,
                    'support'    => false,
                ),
                'is_live'          => true,
            ) );
        }
        return $at_fs;
    }

    // Init Freemius.
    at_fs();
    // Signal that SDK was initiated.
    do_action( 'at_fs_loaded' );
}
/**
 * Admin Notices
 */
function arcade_admin_complete_setup() {
    if ( get_user_by( 'email', 'info@arcadetheme.com' ) ) {
        ?>
		<div class="notice notice-warning">
			<h3><?php 
        _e( 'Temporary User Detected', 'arcade' );
        ?></h3>
			<p><?php 
        _e( 'A user with the email address "info@arcadetheme.com" is registered in the system. This is a temporary user. Please create a different admin account and delete this temporary user.', 'arcade' );
        ?></p>
		</div>
	<?php 
    }
    if ( wp_count_posts()->publish < 10 ) {
        ?>
		<div class="notice notice-info is-dismissible">
			<h3><?php 
        _e( 'There are not enough games!', 'arcade' );
        ?></h3>
			<p><?php 
        _e( 'Your site has fewer than 10 games. You may want to enable the importer switch from the theme customizer to import demo content.', 'arcade' );
        ?></p>
			<p>
				<a class="button" href="<?php 
        echo admin_url( 'customize.php', 'https' );
        ?>"><?php 
        _e( 'Enable Importer', 'arcade' );
        ?></a>
			</p>
		</div>
	<?php 
    }
}

add_action( 'admin_notices', 'arcade_admin_complete_setup' );
/**
 * Enqueue scripts & styles.
 */
function arcade_scripts() {
    // jQuery
    if ( !is_admin() ) {
        wp_deregister_script( 'jquery' );
        wp_register_script(
            'jquery',
            '//cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js',
            array(),
            '3.5.1',
            true
        );
        wp_enqueue_script( 'jquery' );
    }
    // Main JS file.
    wp_enqueue_script(
        'arcade-site',
        ARCADE_THEME_URI . '/assets/site.js',
        array('jquery'),
        ARCADE_THEME_VERSION,
        true
    );
    // Theme Main Stylesheet
    wp_enqueue_style(
        'arcade-style',
        get_stylesheet_uri(),
        '',
        ARCADE_THEME_VERSION
    );
    // Comment reply.
    if ( is_singular() && comments_open() ) {
        wp_enqueue_script( 'comment-reply' );
    }
    if ( is_rtl() ) {
        // RTL.
        //wp_enqueue_style( 'arcade-rtl', ARCADE_THEME_URI . '/css/rtl-min.css', '', ARCADE_THEME_VERSION );
    }
}

add_action( 'wp_enqueue_scripts', 'arcade_scripts', 10 );
/**
 * Theme core functions
 */
require_once ARCADE_THEME_DIR . '/inc/core.php';
require_once ARCADE_THEME_DIR . '/inc/migration.php';
/**
 * Required plugins activator
 */
require_once ARCADE_THEME_DIR . '/inc/tgm-plugin-activation/activator.php';
/**
 * Theme Settings
 */
// Load Settings
if ( class_exists( 'Kirki' ) ) {
    require_once ARCADE_THEME_DIR . '/inc/settings.php';
}
// Use Google Fonts Server
if ( get_theme_mod( 'fonts_server' ) == "google" ) {
    add_filter( 'kirki_use_local_fonts', '__return_false' );
}
/**
 * Theme User CSS + Critical CSS
 */
require_once ARCADE_THEME_DIR . '/inc/css.php';
/**
 * Importer
 */
require_once ARCADE_THEME_DIR . '/inc/importer.php';
/**
 * Updater
 */
if ( at_fs()->is_free_plan() ) {
    require_once ARCADE_THEME_DIR . '/inc/updater.php';
}
/**
 * Crons
 */
require_once ARCADE_THEME_DIR . '/inc/cron.php';
/**
 * Handles JavaScript detection.
 * Adds a `js` class to the root `<html>` element when JavaScript is detected.
 * @since Twenty Seventeen 1.0
 */
function arcade_javascript_detection() {
    echo "<script>(function(html){html.className = html.className.replace(/\\bno-js\\b/,'js')})(document.documentElement);</script>\n";
}

add_action( 'wp_head', 'arcade_javascript_detection', 0 );
/**
 * Disable emojis in WordPress
 */
add_action( 'init', 'arcade_disable_emojis' );
function arcade_disable_emojis() {
    remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
    remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
    remove_action( 'wp_print_styles', 'print_emoji_styles' );
    remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
    remove_action( 'admin_print_styles', 'print_emoji_styles' );
    remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
    remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
}

/**
 * Disable Fedds
 */
function arcade_disable_feed() {
    wp_redirect( home_url( '/' ) );
    exit;
}

add_action( 'do_feed', 'arcade_disable_feed', 1 );
add_action( 'do_feed_rdf', 'arcade_disable_feed', 1 );
add_action( 'do_feed_rss', 'arcade_disable_feed', 1 );
add_action( 'do_feed_rss2', 'arcade_disable_feed', 1 );
add_action( 'do_feed_atom', 'arcade_disable_feed', 1 );
add_action( 'do_feed_rss2_comments', 'arcade_disable_feed', 1 );
add_action( 'do_feed_atom_comments', 'arcade_disable_feed', 1 );
/**
 * IMG SRC
 */
function arcade_img_src(  $post = null, $size = null, $data = null  ) {
    $post_id = ( is_numeric( $post ) ? $post : $post->ID );
    if ( !$data ) {
        $data = json_decode( get_post_meta( $post_id, 'data', true ) );
    }
    if ( isset( $data->image ) ) {
        if ( preg_match( "/^http/", $data->image ) ) {
            $parsed = parse_url( $data->image );
            $upload_dir = wp_upload_dir();
            arcade_check_image( array(
                "post_id" => $post_id,
                "data"    => $data,
            ) );
            return esc_url( $upload_dir['baseurl'] . $parsed['path'] );
        }
        return esc_url( home_url( $data->image ) );
    }
    return false;
}

/**
 * Check Game Image Again
 */
function arcade_check_image(  $args = []  ) {
    // Args
    $defaults = array(
        "post_id" => null,
        "data"    => null,
    );
    $args = wp_parse_args( $args, $defaults );
    // Process
    if ( !$args['post_id'] ) {
        return;
    }
    if ( $args['data'] == null ) {
        $data = json_decode( get_post_meta( $args['post_id'], 'data', true ) );
    } else {
        $data = $args['data'];
    }
    if ( isset( $data->image ) && preg_match( "/^http/", $data->image ) ) {
        $parsed = parse_url( $data->image );
        $upload_dir = wp_upload_dir();
        $file_path = $upload_dir['basedir'] . $parsed['path'];
        if ( !file_exists( $file_path ) ) {
            // Create folder if it doesn't exist
            $folder_path = dirname( $file_path );
            if ( !file_exists( $folder_path ) ) {
                if ( !mkdir( $folder_path, 0755, true ) ) {
                    debug( __( "Failed to create folder", "arcade" ) . ' : ' . $folder_path );
                    return false;
                }
            }
            // Download image and save
            $response = wp_remote_get( esc_url( $data->image ), array(
                'timeout'    => 30,
                'User-Agent' => esc_attr( 'Arcade Theme ' . ARCADE_THEME_VERSION ),
            ) );
            if ( is_wp_error( $response ) ) {
                $error_message = $response->get_error_message();
                return;
            } else {
                $body = wp_remote_retrieve_body( $response );
                file_put_contents( $file_path, $body );
                return true;
            }
        } else {
            return true;
        }
    }
}

/**
 * Pagination
 */
function arcade_pager() {
    $pagination_style = get_theme_mod( "pagination_style", "default" );
    /**
     * Style : Default
     */
    if ( $pagination_style == "default" ) {
        $pagination_layout = get_theme_mod( "pagination_default_layout", "default" );
        // Define the previous and next button HTML with translation
        $prev_text = sprintf( '<span class="btn btn-inline btn-color btn-yellow"><i class="fas fa-arrow-left"></i> %s</span>', get_theme_mod( "pagination_prev_button_label", __( 'Previous Page', 'arcade' ) ) );
        $next_text = sprintf( '<span class="btn btn-inline btn-color btn-yellow">%s <i class="fas fa-arrow-right"></i></span>', get_theme_mod( "pagination_next_button_label", __( 'Next Page', 'arcade' ) ) );
        // Generate the posts pagination with custom HTML for previous and next buttons
        $pagination_args = array(
            'end_size'           => 1,
            'mid_size'           => 5,
            'prev_text'          => ( $pagination_layout != 'only_page_numbers' ? $prev_text : '' ),
            'next_text'          => ( $pagination_layout != 'only_page_numbers' ? $next_text : '' ),
            'screen_reader_text' => __( 'Page Navigation', 'arcade' ),
            'add_fragment'       => '',
            'before_page_number' => '',
            'after_page_number'  => '',
        );
        // Retrieve and modify pagination HTML
        $pnav = get_the_posts_pagination( $pagination_args );
        $pnav = str_replace( array('<h2', '</h2>', 'page-numbers'), array('<cite', '</cite>', 'page-numbers'), $pnav );
        // Remove .page-numbers elements if $pagination_layout is "only_buttons"
        if ( $pagination_layout === 'only_buttons' ) {
            $pnav = preg_replace_callback( '/<a[^>]*class="[^"]*page-numbers[^"]*"[^>]*>.*?<\\/a>|<span[^>]*class="[^"]*page-numbers[^"]*"[^>]*>.*?<\\/span>/i', function ( $matches ) {
                // Check if "prev" or "next" is in the class attribute
                return ( preg_match( '/class="[^"]*(prev|next)[^"]*"/', $matches[0] ) ? $matches[0] : '' );
            }, $pnav );
        }
        // Wrap page numbers in styled button HTML
        $btn_wrapper = '><span class="btn btn-inline btn-color btn-yellow">$1</span><';
        $pnav = preg_replace( "@>([\\d]+)<@i", $btn_wrapper, $pnav );
        // Output the navigation
        echo '<div class="pager">' . $pnav . '</div>';
    }
    /**
     * Style : WP-PageNavi
     */
    if ( $pagination_style == "wp-pagenavi" ) {
        // Check if the plugin is enabled
        if ( function_exists( "wp_pagenavi" ) ) {
            echo '<div class="pager">';
            wp_pagenavi();
            echo '</div>';
        } else {
            printf( '<div class="btn-red"><i class="fa-solid fa-triangle-exclamation"></i> %s</div>', __( 'You want to use WP-PageNavi. But you have not activated this plugin. Please enable the plugin and refresh the page.', 'arcade' ) );
        }
    }
}

/**
 * Search-box
 */
if ( isset( $_GET['search-box'] ) ) {
    $search_by = get_theme_mod( 'search_by', 'wp' );
    if ( $search_by == 'wp' ) {
        echo '<div class="qsearch">';
        get_search_form();
        echo '</div>';
    } else {
        if ( $search_by == 'cse' ) {
            ?>
		<style>
			.gsc-control-cse {
				border-color: #FFFFFF00;
				background-color: #FFFFFF00;
			}

			.gsc-cursor .gsc-cursor-page {
				font-size: 3em;
				background: white;
				padding: 0.2em 0.4em;
				border-radius: 50%;
			}

			.gcsc-more-maybe-branding-root {
				display: none;
			}
		</style>
		<script async src="https://cse.google.com/cse.js?cx=<?php 
            echo get_theme_mod( 'cse_id', '' );
            ?>"></script>
		<div class="gcse-search"></div>
	<?php 
        }
    }
    exit;
}
/**
 * Sharer JS
 */
if ( isset( $_GET['share'] ) ) {
    ?>
	<style>
		#toggle {
			padding: 1em;
		}
	</style>
	<!-- AddToAny BEGIN -->
	<div class="a2a_kit a2a_kit_size_32 a2a_default_style" style="line-height: 32px;margin: 0 auto;width: max-content;">
		<a class="a2a_dd" href="https://www.addtoany.com/share"></a>
		<a class="a2a_button_facebook a2a_counter"></a>
		<a class="a2a_button_whatsapp"></a>
		<a class="a2a_button_pinterest"></a>
		<a class="a2a_button_facebook_messenger"></a>
		<a class="a2a_button_twitter a2a_counter"></a>
		<a class="a2a_button_google_gmail"></a>
		<a class="a2a_button_copy_link"></a>
		<a class="a2a_button_email"></a>
	</div>
	<script>
		var a2a_config = a2a_config || {};
		a2a_config.num_services = 10;
	</script>
	<script async src="https://static.addtoany.com/menu/page.js"></script>
	<!-- AddToAny END -->
<?php 
    exit;
}
/**
 * cookieconsent
 */
if ( isset( $_GET['cookieconsent'] ) ) {
    ?>
	<!-- cookie consent -->
	<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.css" />
	<script src="//cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js" data-cfasync="false"></script>
	<script>
		setTimeout(function() {
			window.cookieconsent.initialise({
				"palette": {
					"popup": {
						"background": "#ffffff",
						"text": "#636363"
					},
					"button": {
						"background": "#18b84e",
						"text": "#ffffff"
					}
				},
				"theme": "classic",
				"type": "opt-in",
				"content": {
					"message": "This website and our partners will collect data and use cookies for ad personalization and measurement."
				}
			});
		}, 1500);
	</script>
<?php 
    exit;
}
/**
 * Prevent WP from adding <p> tags on pages
 */
function arcade_disable_wp_auto_p(  $content  ) {
    if ( is_singular( 'post' ) ) {
        remove_filter( 'the_content', 'wpautop' );
        remove_filter( 'the_excerpt', 'wpautop' );
    }
    return $content;
}

add_filter( 'the_content', 'arcade_disable_wp_auto_p', 0 );
/**
 * Collect data to output in JSON-LD.
 *
 * @param array  $unsigned An array of data to output in json-ld.
 * @param JsonLD $unsigned JsonLD instance.
 */
add_filter(
    'rank_math/json_ld',
    function ( $json_ld, $json ) {
        if ( is_singular() && !isset( $json_ld['richSnippet'] ) ) {
            $json_ld['richSnippet'] = [
                '@context'            => 'https://schema.org',
                '@type'               => "VideoGame",
                'headline'            => $json->parts['title'],
                'description'         => $json->parts['desc'],
                'datePublished'       => $json->parts['published'],
                'dateModified'        => $json->parts['modified'],
                'mainEntityOfPage'    => [
                    '@type' => 'WebPage',
                    '@id'   => $json->parts['canonical'],
                ],
                'applicationCategory' => 'Game',
            ];
            $json->add_prop( 'thumbnail', $json_ld['richSnippet'] );
        }
        return $json_ld;
    },
    11,
    2
);
/**
 * Top Categories
 * for header...
 */
function arcade_top_categories() {
    $tags = get_tags( [
        'orderby' => 'count',
        'order'   => 'DESC',
        'number'  => 29,
    ] );
    if ( !$tags ) {
        return;
    }
    $li = array();
    foreach ( $tags as $tag ) {
        $li[] = sprintf( '<li><a href="%s">%s</a></li>', get_term_link( $tag->term_id ), esc_attr( $tag->name ) );
    }
    // To all cats
    $acp = get_theme_mod( 'all_categories_page', false );
    if ( $acp ) {
        $li[] = sprintf( '<li><a href="%s">%s</a></li>', get_permalink( $acp ), '<i class="fas fa-th"></i> ' . __( 'Show All', 'arcade' ) );
    }
    printf( '<ul id="tc" style="display:none" class="w gtc">%s</ul>', implode( '', $li ) );
}

/**
 * Footer Content Template
 */
function arcade_footer_content(  $mod = null  ) {
    $ID = abs( get_theme_mod( $mod, false ) );
    if ( !$ID ) {
        return;
    }
    $post = get_page( $ID );
    if ( !$post ) {
        return;
    }
    printf( '<div class="w footer-content">%s</div>', apply_filters( 'the_content', $post->post_content ) );
}

/**
 * Arcade Example AD Code
 */
function arcade_ex_ad(  $size = null  ) {
    return '<a href="https://arcadetheme.com/"><img loading="lazy" src="' . ARCADE_THEME_URI . '/assets/images/ad-sizes/' . $size . '.png" /></a>';
}

/**
 * Custom Logo SRCSET Fix
 */
function ssl_post_thumbnail_urls(  $url, $post_id  ) {
    //Skip file attachments
    if ( !wp_attachment_is_image( $post_id ) ) {
        return $url;
    }
    //Correct protocol for https connections
    list( $protocol, $uri ) = explode( '://', $url, 2 );
    if ( is_ssl() ) {
        if ( 'http' == $protocol ) {
            $protocol = 'https';
        }
    } else {
        if ( 'https' == $protocol ) {
            $protocol = 'http';
        }
    }
    return $protocol . '://' . $uri;
}

add_filter(
    'wp_get_attachment_url',
    'ssl_post_thumbnail_urls',
    10,
    2
);
/**
 * Delete DIR
 */
function recursive_remove_directory(  $directory = null  ) {
    foreach ( glob( "{$directory}/*" ) as $file ) {
        if ( is_dir( $file ) ) {
            recursive_remove_directory( $file );
        } else {
            unlink( $file );
            debug( "unlink({$file})", "yellow" );
        }
    }
    rmdir( $directory );
    debug( "rmdir({$directory})", "white" );
}

/**
 * Clear Old PNG files
 */
function clear_old_pngs() {
    $s = ABSPATH . "images/s";
    $m = ABSPATH . "images/m";
    if ( file_exists( $s ) ) {
        recursive_remove_directory( $s );
    }
    if ( file_exists( $m ) ) {
        recursive_remove_directory( $m );
    }
}

/***
 * ADS.TXT
 * Auto add ads.txt lines for Game Distribution and other networks
 * @param string $lines The lines to be added to the ads.txt file.
 */
function arcade_ads_txt_content(  $lines  ) {
    return $lines . "\n" . file_get_contents( get_parent_theme_file_path( '/ads.txt' ) );
}

if ( get_theme_mod( 'auto_add_ads_txt_lines', 1 ) ) {
    add_action( "advanced-ads-ads-txt-content", "arcade_ads_txt_content" );
}
/**
 * Menu Icons by ThemeIsle
 * Override menu item markup
 *
 * @param string  $markup  Menu item title markup.
 * @param integer $id      Menu item ID.
 * @param array   $meta    Menu item meta values.
 * @param string  $title   Menu item title.
 *
 * @return string
 */
function my_menu_icons_override_markup(
    $markup,
    $id,
    $meta,
    $title
) {
    return '<i>' . $markup . '</i>';
}

add_filter(
    'menu_icons_item_title',
    'my_menu_icons_override_markup',
    10,
    4
);
/**
 * TODO: Delete Game Thumbnails when game is deleted
 */
add_action( 'before_delete_post', 'arcade_delete_game_thumbnail' );
function arcade_delete_game_thumbnail(  $post_id  ) {
    return;
    $file_path = str_replace( get_home_url(), ABSPATH, arcade_img_src( $post_id ) );
    if ( file_exists( $file_path ) && is_file( $file_path ) ) {
        echo "...Deleting post thumb {$file_path}";
        unset($file_path);
    }
    echo "Deleting post thumb {$file_path}";
}
