<?php

/********************************************************************
 * Copyright (C) 2025 Upvimeo.com (https://upvimeo.com)
 *
 * This file is part of Upvimeo
 *
 * Upvimeo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * Upvimeo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Upvimeo. If not, see <https://www.gnu.org/licenses/>.
 **********************************************************************/

/**
 * Class UpVimeo_Shared
 *
 * The shared functionality of the plugin (admin/frontend)
 *
 * @license GPLv2
 * @copyright Upvimeo.com (https://upvimeo.com)
 * @since 1.0.0
 */
class UpVimeo_Shared
{

    /**
     * The settings
     * @var UpVimeo_Settings_Helper
     */
    protected $settings_helper;

    /**
     * The API Helper
     * @var UpVimeo_Api_Helper
     */
    protected $api_helper;

    /**
     * UpVimeo_Shared constructor.
     */
    public function __construct()
    {
        $this->settings_helper = new UpVimeo_Settings_Helper();
        $this->api_helper = new UpVimeo_Api_Helper();
    }

    /**
     * Create nonce
     */
    public function get_nonce()
    {
        static $UPVIMEO_nonce;
        if (empty($UPVIMEO_nonce)) {
            $UPVIMEO_nonce = wp_create_nonce('upvimeo_ajax_nonce');
        }

        return $UPVIMEO_nonce;
    }

    /**
     * Check if it is possible to enqueue the Vimeo plugin for tinymce.
     * @return bool
     */
    public function can_enqueue_vimeo_tinymce()
    {
        // Removed Gutenberg check to allow Classic blocks/metaboxes to work.
        /*
        $is_gutenberg = is_admin() && upvimeo_is_gutenberg_active();

        if ($is_gutenberg) {
            return false;
        }
        */

        // ---------------------------------------------------------
        // Elementor Safety Guard
        // ---------------------------------------------------------
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $is_elementor_preview = isset($_GET['elementor-preview']);
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $is_elementor_action = isset($_GET['action']) && $_GET['action'] === 'elementor';
        $is_elementor_editor_mode = false;

        if (defined('ELEMENTOR_VERSION') && class_exists('\Elementor\Plugin')) {
            if (\Elementor\Plugin::$instance->editor->is_edit_mode()) {
                $is_elementor_editor_mode = true;
            }
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ($is_elementor_preview || $is_elementor_action || $is_elementor_editor_mode || isset($_REQUEST['action']) && 'elementor_ajax' === $_REQUEST['action']) {
            return false;
        }

        if (!apply_filters('UPVIMEO_enable_tinymce_upload_plugin', true)) {
            return false;
        }

        return true;
    }

    /**
     * Register Vimeo Button
     *
     * @param $buttons
     *
     * @return mixed
     */
    public function tinymce_vimeo_button($buttons)
    {

        if ($this->can_enqueue_vimeo_tinymce()) {
            array_push($buttons, 'UPVIMEO_vimeo_button');
        }

        return $buttons;
    }

    /**
     * Register Vimeo Plugin
     *
     * @param $plugin_array
     *
     * @return mixed
     */
    public function tinymce_vimeo_plugin($plugin_array)
    {

        if ($this->can_enqueue_vimeo_tinymce()) {
            $plugin_array['UPVIMEO_vimeo_button'] = UPVIMEO_URL . 'shared/js/tinymce-upload.js';
        }

        return $plugin_array;
    }

    /**
     * Add media button
     *
     * @param $editor_id
     */
    public function add_media_button($editor_id)
    {
        if (!$this->can_enqueue_vimeo_tinymce()) {
            return;
        }

        $title = __('Add Vimeo', 'upvimeo-direct-uploads');
        $icon_url = upvimeo_get_vimeo_icon_url();

        echo '<a href="#" class="button upvimeo-media-button" data-editor="' . esc_attr($editor_id) . '" title="' . esc_attr($title) . '">
            <span class="wp-media-buttons-icon" style="background-image: url(' . esc_url($icon_url) . '); background-repeat: no-repeat; background-position: center; background-size: contain;"></span> ' . esc_html($title) . '
        </a>';
    }

    /**
     * Add editor styles
     */
    public function tinymce_styles()
    {
        /*if ( ! wp_script_is( 'upvimeo-upload-modal', 'enqueued' ) ) {
            add_editor_style( UPVIMEO_URL . 'shared/css/upload-modal.css' );
        }*/
        // Disabled, throws wp_script_is() warning.
    }

    /**
     * Tinymce globals
     *
     * @param $settings
     */
    public function tinymce_globals($settings)
    {

        $is_loaded = false;

        if (is_array($settings)) {
            foreach ($settings as $editor_id => $editor) {
                if (isset($editor['external_plugins'])) {
                    if (strpos($editor['external_plugins'], 'UPVIMEO_vimeo_button') !== false) {
                        $is_loaded = true;
                    }
                }
            }
        }

        if (!$is_loaded) {
            return;
        }

        $this->enqueue_tinymce_assets();
    }


    /**
     * Register all the resources
     */
    public function register_scripts()
    {
        wp_register_script(
            'upvimeo-http',
            UPVIMEO_URL . 'shared/js/http.js',
            array(),
            UPVIMEO_VERSION,
            true
        );

        wp_register_script(
            'upvimeo-dropzone',
            UPVIMEO_URL . 'shared/resources/dropzone/dropzone.min.js',
            array(),
            UPVIMEO_VERSION,
            true
        );

        wp_register_style(
            'upvimeo-dropzone',
            UPVIMEO_URL . 'shared/resources/dropzone/dropzone.min.css',
            array(),
            UPVIMEO_VERSION,
            'all'
        );

        wp_register_script(
            'upvimeo-chunked-upload',
            UPVIMEO_URL . 'shared/js/chunked-upload.js',
            array('wp-util', 'upvimeo-dropzone', 'jquery'),
            UPVIMEO_VERSION,
            true
        );

        wp_localize_script('upvimeo-chunked-upload', 'UPVIMEO_CHUNKED_UPLOAD', array(
            'url' => admin_url('admin-ajax.php'),
            'errors' => array(
                'file_not_uploaded' => esc_html__('This file was not uploaded.', 'upvimeo-direct-uploads'),
                'file_limit' => esc_html__('File limit has been reached ({fileLimit}).', 'upvimeo-direct-uploads'),
                'file_extension' => esc_html__('File type is not allowed.', 'upvimeo-direct-uploads'),
                'file_size' => esc_html__('File exceeds the max size allowed.', 'upvimeo-direct-uploads'),
                'post_max_size' => sprintf( /* translators: %s - max allowed file size by a server. */
                    esc_html__('File exceeds the upload limit allowed (%s).', 'upvimeo-direct-uploads'),
                    upvimeo_max_upload_size()
                ),
            ),
            'loading_message' => esc_html__('File upload is in progress. Please submit the form once uploading is completed.', 'upvimeo-direct-uploads'),
            'nonce' => $this->get_nonce(),
        ));

        wp_register_script(
            'upvimeo-select2',
            UPVIMEO_URL . 'shared/resources/select2/select2.min.js',
            array(),
            UPVIMEO_VERSION,
            true
        );

        wp_register_style(
            'upvimeo-select2',
            UPVIMEO_URL . 'shared/resources/select2/select2.min.css',
            array(),
            UPVIMEO_VERSION,
            'all'
        );

        wp_register_script(
            'upvimeo-swal',
            UPVIMEO_URL . 'shared/js/sweetalert2.js',
            array(),
            UPVIMEO_VERSION,
            true
        );

        wp_register_script(
            'upvimeo-tus',
            UPVIMEO_URL . 'shared/resources/tus-js-client/tus.min.js',
            array(),
            UPVIMEO_VERSION,
            true
        );

        wp_register_script(
            'upvimeo-uploader',
            UPVIMEO_URL . 'shared/js/uploader.js',
            array('jquery', 'upvimeo-tus'),
            UPVIMEO_VERSION,
            true
        );

        wp_register_script(
            'upvimeo-upload-modal',
            UPVIMEO_URL . 'shared/js/upload-modal.js',
            array('jquery', 'upvimeo-uploader', 'upvimeo-swal'),
            UPVIMEO_VERSION,
            true
        );

        $modal_config = $this->get_modal_config_params();
        wp_localize_script('upvimeo-upload-modal', 'UPVIMEO_Modal_Config', $modal_config);

        wp_register_script(
            'upvimeo-admin',
            UPVIMEO_URL . 'admin/js/admin.js',
            array(
                'jquery',
                'upvimeo-uploader',
                'upvimeo-http',
            ),
            UPVIMEO_VERSION,
            true
        );

        wp_localize_script('upvimeo-admin', 'UPVIMEOAdmin', array(
            'phrases' => array(
                'select2' => array(
                    'errorLoading' => __('The results could not be loaded.', 'upvimeo-direct-uploads'),
                    'inputTooLong' => __('Please delete {number} character', 'upvimeo-direct-uploads'),
                    'inputTooShort' => __('Please enter {number} or more characters', 'upvimeo-direct-uploads'),
                    'loadingMore' => __('Loading more results...', 'upvimeo-direct-uploads'),
                    'maximumSelected' => __('You can only select {number} item', 'upvimeo-direct-uploads'),
                    'noResults' => __('No results found', 'upvimeo-direct-uploads'),
                    'searching' => __('Searching...', 'upvimeo-direct-uploads'),
                    'removeAllItems' => __('Remove all items', 'upvimeo-direct-uploads'),
                    'removeItem' => __('Remove item', 'upvimeo-direct-uploads'),
                    'search' => __('Search', 'upvimeo-direct-uploads'),
                )
            )
        ));

        wp_register_script(
            'wvv-vimeo-upload-block',
            UPVIMEO_URL . 'admin/blocks/upload/script.js',
            array(
                'wp-blocks',
                'wp-editor',
                'wp-element',
                'jquery',
                'upvimeo-uploader'
            ),
            UPVIMEO_VERSION,
            true
        );

        wp_register_style(
            'wvv-vimeo-upload-block',
            UPVIMEO_URL . 'admin/blocks/upload/style.css',
            array('dashicons'),
            UPVIMEO_VERSION,
            'all'
        );

        if (function_exists('register_block_type')) {
            register_block_type('upvimeo/wp-vimeo-video', array(
                'editor_style' => 'wvv-vimeo-upload-block',
            ));
        }

        wp_register_style(
            'upvimeo-admin',
            UPVIMEO_URL . 'admin/css/admin.css',
            array(),
            UPVIMEO_VERSION,
            'all'
        );

        wp_register_style(
            'upvimeo-upload-modal',
            UPVIMEO_URL . 'shared/css/upload-modal.css',
            array(),
            UPVIMEO_VERSION,
            'all'
        );
    }

    /**
     * Enqueues scripts
     * @return void
     */
    public function enqueue_scripts_tinymce($config)
    {
        if (isset($config['tinymce']) && $config['tinymce'] && $this->can_enqueue_vimeo_tinymce()) {
            $this->enqueue_tinymce_assets();
        }
    }

    /**
     * Enqueues TinyMCE assets
     */
    public function enqueue_tinymce_assets()
    {
        foreach (array('upvimeo-swal', 'upvimeo-tus', 'upvimeo-uploader', 'upvimeo-upload-modal') as $script) {
            wp_enqueue_script($script);
        }
        foreach (array('upvimeo-upload-modal') as $style) {
            wp_enqueue_style($style);
        }
        // Config
        $mce_icon = apply_filters('UPVIMEO_mce_toolbar_icon_enable', true);
        $mce_icon_url = $mce_icon ? apply_filters('UPVIMEO_mce_toolbar_icon_url', esc_url(upvimeo_get_vimeo_icon_url())) : null;
        $mce_text = apply_filters('UPVIMEO_mce_toolbar_title', __('Vimeo', 'upvimeo-direct-uploads'));
        $mce_text = $mce_icon && $mce_text ? sprintf(' %s', $mce_text) : $mce_text;
        $mce_tooltip = apply_filters('UPVIMEO_mce_toolbar_tooltip', __('Insert Vimeo Video', 'upvimeo-direct-uploads'));
        wp_localize_script('wp-tinymce', 'UPVIMEO_MCE_Config', array(
            'phrases' => array(
                'tmce_title' => $mce_text,
                'tmce_tooltip' => $mce_tooltip,
                'cancel_upload_confirm' => esc_html__('Are you sure you want to cancel the upload?', 'upvimeo-direct-uploads'),
            ),
            'icon' => $mce_icon,
            'icon_url' => $mce_icon_url,
            'markup' => apply_filters('UPVIMEO_mce_output_markup', '[upvimeo_video id="{id}"]')
        ));
        wp_localize_script('upvimeo-upload-modal', 'UPVIMEO_Modal_Config', $this->get_modal_config_params());
    }


    /**
     * The modal config params
     * @return array
     */
    private function get_modal_config_params()
    {
        return array(
            'nonce' => $this->get_nonce(),
            'ajax_url' => admin_url('admin-ajax.php'),
            'assets_url' => UPVIMEO_URL . 'assets/',
            'default_privacy' => is_admin()
                ? $this->settings_helper->get_default_admin_view_privacy()
                : $this->settings_helper->get_default_frontend_view_privacy(),
            'enable_vimeo_search' => $this->settings_helper->get('upvimeo_mce_enable_account_search'),
            'enable_local_search' => $this->settings_helper->get('upvimeo_mce_enable_local_search'),
            'words' => array(
                'sorry' => __('Sorry', 'upvimeo-direct-uploads'),
                'success' => __('Success', 'upvimeo-direct-uploads'),
                'title' => __('Title', 'upvimeo-direct-uploads'),
                'desc' => __('Description', 'upvimeo-direct-uploads'),
                'insert' => __('Insert', 'upvimeo-direct-uploads'),
                'search' => __('Search', 'upvimeo-direct-uploads'),
                'searching3d' => __('Searching...', 'upvimeo-direct-uploads'),
                'upload' => __('Upload', 'upvimeo-direct-uploads'),
                'uploading3d' => __('Uploading', 'upvimeo-direct-uploads'),
                'file' => __('File', 'upvimeo-direct-uploads'),
                'privacy_view' => __('Who can view this video?', 'upvimeo-direct-uploads'),
            ),
            'phrases' => array(
                'title' => apply_filters('UPVIMEO_upload_modal_title', __('Insert Vimeo Video', 'upvimeo-direct-uploads')),
                'http_error' => __('Sorry there was a HTTP error. Please check the server logs or contact support.', 'upvimeo-direct-uploads'),
                'upload_invalid_file' => __('Please select valid video file.', 'upvimeo-direct-uploads'),
                'invalid_search_phrase' => __('Invalid search phrase. Please enter valid search phrase.', 'upvimeo-direct-uploads'),
                'videos_not_found' => __('No uploaded videos found.', 'upvimeo-direct-uploads'),
                'search_not_found' => __('No matching videos found for your search', 'upvimeo-direct-uploads'),
                'cancel_upload_confirm' => esc_html__('Are you sure you want to cancel the upload?', 'upvimeo-direct-uploads')
            ),
            'methods' => upvimeo_get_editor_insert_methods(),
            'upload_form_options' => array(
                'enable_privacy_option' => (int) $this->settings_helper->get('upvimeo_enable_privacy_option_mce', 0),
                'privacy_view' => is_admin() ? $this->api_helper->get_view_privacy_options_for_forms('admin') : null,
            )
        );
    }
}
