<?php
/**
 * @author WP Cloud Plugins
 * @copyright Copyright (c) 2023, WP Cloud Plugins
 *
 * @since       3.0
 * @see https://www.wpcloudplugins.com
 */

namespace TheLion\ShareoneDrive\Modules;

use TheLion\ShareoneDrive\App;
use TheLion\ShareoneDrive\Modules;
use TheLion\ShareoneDrive\Processor;
use TheLion\ShareoneDrive\Settings;

defined('ABSPATH') || exit;

class Embed
{
    public static $supported_extensions = [];

    /**
     * Get the list of items to embed.
     *
     * @return array sorted list of items to embed
     */
    public static function get_list()
    {
        // Get the module ID from the shortcode options
        $module_id = Processor::instance()->get_shortcode_option('id');

        // Retrieve items for the module
        $items = Modules::get_items($module_id);

        // Return sorted list of items
        return Processor::instance()->sort_filelist($items);
    }

    /**
     * Render the embedded items on the page.
     *
     * @param mixed $attributes
     */
    public static function render($attributes = [])
    {
        // Get the maximum width from the shortcode options
        $maxwidth = Processor::instance()->get_shortcode_option('maxwidth');
        \ob_start();
        ?>
<div class='wpcp-module ShareoneDrive wpcp-embed' data-token='<?php echo Processor::instance()->get_listtoken(); ?>'>
    <div style="width:<?php echo $maxwidth; ?>;max-width:<?php echo $maxwidth; ?>; position:relative;">
        <?php Password::render();

        // Get the list of items to embed
        $items = self::get_list();

        // Render each item
        foreach ($items as $item) {
            if ($item['is_dir']) {
                continue;
            }

            self::render_item($item);
        }
        ?>
    </div>
</div>
<?php

        echo \ob_get_clean();
    }

    /**
     * Render the item on the page.
     *
     * @param array $item item details to render
     */
    public static function render_item($item)
    {
        // Shortcode Options
        $embed_type = Processor::instance()->get_shortcode_option('embed_type');
        $embed_ratio = str_replace(':', '/', Processor::instance()->get_shortcode_option('embed_ratio'));
        $direct_embed = Processor::instance()->get_shortcode_option('embed_direct_media');
        $show_filenames = Processor::instance()->get_shortcode_option('show_filenames');

        // Item details
        $entry_id = $item['id'];
        $account_id = App::get_current_account()->get_uuid();
        $embed_url = $item['embed_url'];

        // PDF files: route through the plugin PDF viewer when the admin setting requests it,
        // or when the account is forced to use it.
        if ('pdf' === $item['extension']) {
            $account = App::get_current_account();
            $force_pdfjs = $account->is_drive_readonly()
                || ('personal' !== $account->get_type() && App::requires_vulnerability_fix());

            if ('pdfjs' === Settings::get('layout_pdfviewer') || $force_pdfjs) {
                $listtoken = Processor::instance()->get_listtoken();
                $embed_url = SHAREONEDRIVE_ADMIN_URL.'?action=shareonedrive-preview&viewer=1&account_id='.$account_id.'&listtoken='.$listtoken.'&id='.rawurlencode($entry_id);
            }
        }

        // Render Document name
        if ($show_filenames) {
            echo '<h3>'.$item['basename'].'</h3>';
        }

        // Embed Media Files Direct
        if ('1' === $direct_embed && self::is_media_file($item)) {
            echo "<div style='width:100%; max-width:100%;'>";
            $embed_url = SHAREONEDRIVE_ADMIN_URL."?action=shareonedrive-stream&account_id={$account_id}&id={$entry_id}&listtoken=".Processor::instance()->get_listtoken();

            if (false !== strpos($item['mimetype'], 'video/')) {
                ?><video controls preload="metadata" style="width: 100%;">
    <source src="<?php echo \esc_url($embed_url); ?>" type="<?php echo \esc_attr($item['mimetype']); ?>">
</video><?php
            } elseif (false !== strpos($item['mimetype'], 'audio/')) {
                ?><audio controls preload="metadata" style="width: 100%;">
    <source src="<?php echo \esc_url($embed_url); ?>" type="<?php echo \esc_attr($item['mimetype']); ?>">
</audio>
<?php
            } else {
                ?><img src="<?php echo \esc_url($item['embed_url']); ?>" loading="lazy" referrerpolicy="no-referrer" style="max-width: 100%" title="<?php echo \esc_attr($item['basename']).'| '.$item['description']; ?>" ;><?php
            }

            echo '</div>';

            return;
        }

        if (empty($item['embed_url']) || false !== strpos($item['embed_url'], 'disabled')) {
            return;
        }

        // Images are embedded directly
        if (false !== strpos($embed_url, 'shareonedrive-embed-image')) {
            ?><img src="<?php echo \esc_url($embed_url); ?>" loading="lazy" alt="<?php echo \esc_attr($item['basename']); ?>" referrerpolicy="no-referrer" style="max-width: 100%" title="<?php echo \esc_attr($item['basename']).'| '.$item['description']; ?>" ;><?php
        } else {
            if (false === strpos($embed_url, 'embedview') && false === strpos($embed_url, 'embed-redirect')) {
                $embed_url .= (strpos($embed_url, '?')) ? '&action=embedview' : '?action=embedview';
            }

            // Hide toolbar if the file is a Word or Excel document
            $hide_toolbar = false;
            if ('readonly' === $embed_type) {
                $hide_toolbar = (0 === strpos($item['mimetype'], 'application/msword'))
                    || (0 === strpos($item['mimetype'], 'application/vnd.openxmlformats-officedocument.wordprocessingml'))
                    || in_array($item['extension'], ['doc', 'docx', 'dot', 'dotx', 'xls', 'xlsx', 'xlsm', 'xlt', 'xltx'], true)
                    || (0 === strpos($item['mimetype'], 'application/vnd.ms-excel'))
                    || (0 === strpos($item['mimetype'], 'application/vnd.openxmlformats-officedocument.spreadsheetml'));
            }

            $hide_toolbar = apply_filters('shareonedrive_embed_hide_toolbar', $hide_toolbar, $item);

            if ($hide_toolbar && !defined('SHAREONEDRIVE_EMBED_NO_TOOLBAR_CSS_ADDED')) {
                ?>
<style>
.wpcp-embed-wrapper.wpcp-embed-wrapper--no--toolbar:after {
    content: "";
    position: absolute;
    right: 0;
    left: 0;
    bottom: 0;
    height: 30px;
    background: #f5f5f5;
    pointer-events: none;
}
</style>
<?php
define('SHAREONEDRIVE_EMBED_NO_TOOLBAR_CSS_ADDED', true);
            }
            ?>
<div class="wpcp-embed-wrapper <?php echo ($hide_toolbar) ? 'wpcp-embed-wrapper--no--toolbar' : ''; ?>" style="position:relative;">
    <iframe src="<?php echo \esc_url($embed_url); ?>" height="480" style="width:100%;aspect-ratio:<?php echo \esc_attr($embed_ratio); ?>;height:auto;max-height:100vh;border:none;overflow: hidden;" class="sod-embedded" allowfullscreen loading="lazy" referrerpolicy="no-referrer" title="<?php echo $item['basename']; ?>"></iframe>
</div><?php

        }
    }

    /**
     * Check if item is a media file.
     *
     * @param array $item item details to check
     *
     * @return bool true if item is a media file, false otherwise
     */
    public static function is_media_file($item)
    {
        $extension = $item['extension'] ?? '';
        $mimetype = $item['mimetype'] ?? '';

        $allowedextensions = ['jpg', 'jpeg', 'gif', 'png', 'webp', 'heic', 'mp3', 'm4a', 'ogg', 'oga', 'wav', 'opus', 'mp4', 'm4v', 'ogg', 'ogv', 'webmv', 'webm'];
        $allowedimimetypes = ['audio/mpeg', 'audio/mp4', 'audio/ogg', 'audio/x-wav', 'video/mp4', 'video/ogg', 'video/webm'];

        if (!empty($extension) && in_array($extension, $allowedextensions)) {
            return true;
        }

        return in_array($mimetype, $allowedimimetypes);
    }
}
