<?php

defined( 'ABSPATH' ) || exit;

use IGD\App;
use IGD\Enqueue;
use IGD\Permissions;
use IGD\Shortcode;

$direct_file = get_query_var( 'direct_file' );

$file = igd_sanitize_array( json_decode( base64_decode( $direct_file ), true ) );

if ( empty( $file['id'] ) ) {
    wp_die( 'Invalid file ID', 400 );
}

$file_id    = $file['id'];
$account_id = $file['accountId'] ?? '';

// Retrieve the file and check permissions
$file        = App::instance( $account_id )->get_file_by_id( $file_id );
$permissions = Permissions::instance( $account_id );

if ( ! igd_is_dir( $file ) && ! $permissions->has_permission( $file ) ) {
    $permissions->set_permission( $file );
}

$is_dir = igd_is_dir( $file );

add_filter( 'show_admin_bar', '__return_false' );

// Remove all WordPress actions
remove_all_actions( 'wp_head' );
remove_all_actions( 'wp_print_styles' );
remove_all_actions( 'wp_print_head_scripts' );
remove_all_actions( 'wp_footer' );

// Handle `wp_head`
add_action( 'wp_head', 'wp_enqueue_scripts', 1 );
add_action( 'wp_head', 'wp_print_styles', 8 );
add_action( 'wp_head', 'wp_print_head_scripts', 9 );
add_action( 'wp_head', 'wp_site_icon' );

// Handle `wp_footer`
add_action( 'wp_footer', 'wp_print_footer_scripts', 20 );

// Handle `wp_enqueue_scripts`
remove_all_actions( 'wp_enqueue_scripts' );

// Also remove all scripts hooked into after_wp_tiny_mce.
remove_all_actions( 'after_wp_tiny_mce' );

Enqueue::instance()->frontend_scripts();

$type = $is_dir ? 'browser' : 'embed';

?>

    <!doctype html>
    <html lang="<?php language_attributes(); ?>" class="igd-direct-content-html">
    <head>
        <meta charset="<?php bloginfo( 'charset' ); ?>">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title><?php echo esc_html( $file['name'] ); ?></title>

        <?php wp_enqueue_style( 'google-font-roboto', 'https://fonts.googleapis.com/css?family=Roboto:400,500,700&display=swap' ); ?>

        <?php do_action( 'wp_head' ); ?>

    </head>
    <body>

    <div id="igd-direct-content" class="type-<?php echo esc_attr( $type ); ?>">
        <?php

        $data = [
                'folders'            => [ $file ],
                'type'               => $type,
                'allowPreviewPopout' => false,
        ];

        echo Shortcode::instance()->render_shortcode( [], $data );

        ?>
    </div>

    <?php do_action( 'wp_footer' ); ?>

    </body>
    </html>

<?php
exit();
