<?php

/**
 * Game & Data Importer from 4-Win.com
 */
defined( 'ABSPATH' ) || die( "Can't access directly" );
if ( isset( $_GET['importer'] ) ) {
    //define('DEBUG_FORCE', true);
    add_action( 'wp_loaded', 'arcade_game_importer' );
}
function arcade_game_importer() {
    // Importer enabled?
    if ( !get_theme_mod( 'importer', 1 ) ) {
        return;
    }
    // Reloader
    $force = false;
    if ( isset( $_GET['importer'] ) && current_user_can( 'manage_options' ) ) {
        $force = true;
    }
    $interval = 300;
    $last = abs( arcade_site_option( 'importer-time' ) );
    if ( $last + $interval * MINUTE_IN_SECONDS > time() ) {
        if ( !$force ) {
            return;
        }
    } else {
        arcade_site_option( 'importer-time', time() );
    }
    // Veriables
    $flushed = true;
    global $wpdb;
    $cache = ARCADE_TEMP . '/games.json';
    $post_ID = 0;
    $tags_allowed = array();
    $tags_blocked = array();
    // First: Check cached file
    if ( !file_exists( $cache ) ) {
        debug( "The json file must be cached before! Please refresh the page.", "red" );
        $flushed = arcade_flush_rss( $cache, true );
        wp_redirect( home_url( '?importer=' . uniqid( 'arcade-theme-' ) ) );
        exit;
    }
    // Read the local file
    $local_games = json_decode( file_get_contents( $cache ) );
    $sources = get_theme_mod( 'sources' );
    debug( "Arcade Theme - Game Importer", "h1" );
    $report = array();
    $current_number = 0;
    if ( count( $local_games ) ) {
        foreach ( $local_games as $k => $game ) {
            $current_number = $k + 1;
            $data = json_decode( $game->data );
            $data->image = $game->image;
            // Sources
            if ( !empty( $sources ) ) {
                if ( !in_array( $data->s, $sources ) ) {
                    continue;
                }
            }
            // Duplicate?
            $search = $wpdb->get_row( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'data' AND meta_value LIKE %s LIMIT 1", '%"ID":"' . $wpdb->esc_like( $data->ID ) . '"%' ) );
            if ( $search ) {
                continue;
            }
            // Check: Allowed Tags
            $skip = true;
            if ( !empty( $tags_allowed ) ) {
                foreach ( $tags_allowed as $find ) {
                    if ( array_search( $find, $game->tags ) ) {
                        $skip = false;
                        break;
                    }
                }
            } else {
                $skip = false;
            }
            // Check: Blocked Tags
            if ( !empty( $tags_blocked ) ) {
                foreach ( $tags_blocked as $find ) {
                    if ( array_search( $find, $game->tags ) ) {
                        $skip = true;
                        break;
                    }
                }
            }
            // Skip this?
            if ( $skip ) {
                continue;
            }
            // 1st Letter Fixing for Tags
            $last_key = -1;
            foreach ( $game->tags as $kk => $tt ) {
                $game->tags[$kk] = ucwords( $tt );
                $last_key = $kk;
            }
            // Download and Save Image
            $response = wp_remote_get( $game->image, array(
                'timeout'    => 30,
                'User-Agent' => esc_attr( 'Arcade Theme ' . ARCADE_THEME_VERSION ),
            ) );
            if ( is_array( $response ) && !is_wp_error( $response ) ) {
                $headers = wp_remote_retrieve_headers( $response );
                $body = wp_remote_retrieve_body( $response );
                // Content Type && Size Check
                if ( $headers['content-type'] != "image/webp" || $headers['content-length'] < 100 ) {
                    debug( "Thumb image mime type is not WebP", "red" );
                    continue;
                } else {
                    # Download and Save the Game image to local
                    $parsed = parse_url( $game->image );
                    $img_path = $parsed["path"];
                    if ( !preg_match( "@^/images/.+\\.webp\$@", $img_path ) ) {
                        debug( "Something went wrong. It could be the thumbnail image path.", "red" );
                        continue;
                    }
                    # Everything looks fine. Let's save the file.
                    $upload_dir = wp_upload_dir();
                    // Upload directory info
                    $save_img_to = $upload_dir['basedir'] . "/" . trim( $img_path, "/" );
                    if ( !file_exists( dirname( $save_img_to ) ) ) {
                        mkdir( dirname( $save_img_to ), 0755, true );
                    }
                    file_put_contents( $save_img_to, $body );
                    $report["img"] = "<img src='" . home_url( str_replace( ABSPATH, '', $save_img_to ) ) . "'>";
                    if ( !file_exists( $save_img_to ) ) {
                        continue;
                    }
                }
            } else {
                $error_message = ( is_wp_error( $response ) ? $response->get_error_message() : 'Unknown error' );
                debug( "Image download error for " . esc_url( $game->image ) . " - " . $error_message, "blue" );
                continue;
            }
            // Post Insertion
            $add_post = array(
                'post_title'    => esc_attr( $game->title ),
                'post_content'  => wp_kses_post( $game->content ),
                'post_status'   => get_theme_mod( 'post_status', 'publish' ),
                'post_author'   => get_theme_mod( 'post_author', 1 ),
                'post_category' => array(get_option( 'default_category' )),
                'tags_input'    => $game->tags,
                'meta_input'    => array(
                    'data' => json_encode( $data ),
                ),
            );
            $post_ID = wp_insert_post( $add_post, true );
            $report['title'] = esc_attr( $game->title );
            $report['ID'] = $post_ID;
            break;
        }
    }
    $percent = ( count( $local_games ) > 0 ? round( $current_number / count( $local_games ) * 100 ) : 0 );
    printf(
        '<div style="position:relative"><progress max="%1$s" value="%2$s">Progress: %3$s</progress></div>',
        count( $local_games ),
        $current_number,
        $percent
    );
    // All Posts Checked
    if ( !$post_ID ) {
        $flushed = arcade_flush_rss( $cache );
        //wp_die('Data refreshed. Please wait...', 'Arcade Theme Importer', ['response' => 200]);
        //exit;
    }
    if ( $force ) {
        if ( $flushed ) {
            # Refresh page!
            printf( '<meta http-equiv="refresh" content="0;url=%s" />', home_url( '?importer=' . uniqid( 'arcade-theme-' ) ) );
            printf( '<h1>✔️ %s (%s)</h1>', $report['title'], $percent . "%" );
            printf( '<p>%s</p>', $report['img'] );
            echo '<p><h2 style="color:gray; font-size: 1rem" >
            <svg style="
                width: 1rem;
                height: 1rem;
                vertical-align: middle;
                "
             width="38" height="38" viewBox="0 0 38 38" xmlns="http://www.w3.org/2000/svg" stroke="#000">
                <g fill="none" fill-rule="evenodd">
                    <g transform="translate(1 1)" stroke-width="2">
                        <circle stroke-opacity=".5" cx="18" cy="18" r="18"/>
                        <path d="M36 18c0-9.94-8.06-18-18-18">
                            <animateTransform
                                attributeName="transform"
                                type="rotate"
                                from="0 18 18"
                                to="360 18 18"
                                dur="1s"
                                repeatCount="indefinite"/>
                        </path>
                    </g>
                </g>
            </svg> Processing next game... Please wait.</h2> </p>';
        } else {
            if ( !$post_ID ) {
                # STOP refreshing!
                printf( '<h1>%s</h1>', __( 'All posts have been imported!', 'arcade' ) );
                if ( file_exists( $cache ) ) {
                    unlink( $cache );
                }
                echo '<script>alert("All data has been processed. New data will be requested within an hour at the latest from provider.");</script>';
            }
        }
        wp_die( '
        <style>
        progress {
            width: 100%;
            display: block;
            height: 90px;
        }
        .progress-number {
            font-size:1rem;
        }
        </style>
        <script>
        window.onload = function(e){
            window.scrollTo(0,document.body.scrollHeight);
        }
        </script>', $percent . "% - Arcade Theme Importer", [
            'response' => 200,
        ] );
    }
}

/**
 * Flush RSS
 * Download remote RSS data and save to local AGAIN!
 */
function arcade_flush_rss(  $cache = null, $force = false  ) {
    # File is new?
    $last = abs( arcade_site_option( "arcade_flush_rss_last_download" ) );
    if ( $last + HOUR_IN_SECONDS > time() && !$force ) {
        debug( "The game feed file was refreshed before 1 hour. ( Last control: " . date( "Y-m-d H:i", $last ) . ")", "red" );
        return false;
    }
    arcade_site_option( "arcade_flush_rss_last_download", time() );
    // START:
    debug( "Started: arcade_flush_rss", "green" );
    $dir = dirname( $cache );
    debug( "dir: {$dir}", "blue" );
    debug( "cache: {$cache}", "brown" );
    // Check folder
    if ( !file_exists( $dir ) ) {
        mkdir( $dir, 0755, true );
    }
    $feed = "https://4-win.com/feed/games.json";
    debug( "Downloading ... {$feed}", "black" );
    $response = wp_remote_get( $feed, [
        'timeout' => 30,
    ] );
    if ( is_wp_error( $response ) ) {
        debug( "Download Error: " . $response->get_error_message(), "red" );
        return false;
    }
    $data = wp_remote_retrieve_body( $response );
    if ( $data ) {
        if ( isJson( $data ) ) {
            # JSON
            $decode = json_decode( $data );
            $newitems = array();
            foreach ( $decode as $k => $v ) {
                $newitems[] = $v->title;
            }
            //printf("<ol><li>%s</li></ol>", implode("</li><li>", $newitems));
        } else {
            # GZIP
            $decode = gzdecode( $data );
            if ( !isJson( $decode ) ) {
                debug( "GZIP decoding failed or result is not valid JSON.", "red" );
                return false;
            }
            $decode = json_decode( $decode );
        }
        # Save .json file
        if ( $decode ) {
            if ( file_exists( $cache ) && strpos( $cache, ".json" ) ) {
                unlink( $cache );
            }
            file_put_contents( $cache, json_encode( $decode ) );
            debug( "File saved to {$cache}", "green" );
            return true;
        } else {
            debug( "Decoding Error", "red" );
        }
    } else {
        debug( "Download Error: Empty response body.", "red" );
    }
    return false;
}
