<?php
/**
 * Plugin Name:       Magic Product Video for WooCommerce
 * Plugin URI:        https://gorkovenko.net/magic-product-video-for-woocommerce
 * Description:       Easy, fast, and cross-browser solution for uploading videos to WooCommerce product gallery without using of external services.
 * Version:           1.3.8
 * Requires at least: 6.6
 * Requires           PHP: 7.4
 * Author:            Andrii Gorkovenko
 * Author URI:        https://gorkovenko.net
 * Text Domain:       magic-product-video-for-woocommerce
 * License:           GPLv3
 * License URI:       https://www.gnu.org/licenses/gpl-3.0.html
 * Domain Path:       /languages
 * Requires Plugins:  woocommerce
 */

if (!defined('ABSPATH')) {
    exit;
}

define('MPVW_PLUGIN_URL', plugin_dir_url(__FILE__));
define('MPVW_PLUGIN_DIR', plugin_dir_path(__FILE__));

const MPVW_PLUGIN_SLUG = 'magic-product-video-for-woocommerce';
const MPVW_ADMIN_NONCE = 'mpvw_plugin_nonce';
const MPVW_PLUGIN_VERSION = '1.3.8';
const MPVW_ALLOWED_FORMATS = ['mp4', 'mov', 'avi', 'mkv', 'hevc', 'webm'];
const MPVW_REQUIRED_FORMATS = ['mp4', 'webm']; // TODO: ogm, ogg, ogv
const MPVW_VIDEO_CODEC = ['mp4' => 'libx264', 'webm' => 'libvpx']; // TODO: libvpx-vp9
const MPVW_AUDIO_CODEC = ['mp4' => 'aac', 'webm' => 'libvorbis'];
const MPVW_META_BOX_KEY_CVF = 'mpvw_converted_video_files';
const MPVW_META_BOX_KEY_PVD = 'mpvw_product_video_data';
const MPVW_LOCALES = ['en', 'uk'];
const MPVW_TRANSLATIONS = MPVW_LOCALES;
const MPVW_PLUGIN_OPTIONS = [
    'plugin_settings'     => 'mpvw_plugin_settings',
    'settings'            => 'mpvw_settings',
    'player_configs'      => 'mpvw_player_configs',
    'ffmpeg_availability' => 'mpvw_ffmpeg_available',
    'ffmpeg_version'      => 'mpvw_ffmpeg_version',
    'ffmpeg_settings'     => 'mpvw_ffmpeg_settings'
];
const MPVW_ALLOWED_HTML = array(
    'video'  => array(
        'class'    => true,
        'autoplay' => true,
        'muted'    => true,
        'loop'     => true,
        'controls' => true,
    ),
    'source' => array(
        'src'  => true,
        'type' => true,
    ),
    'div'    => array(
        'class'            => true,
        'data-thumb'       => true,
        'data-thumb-alt'   => true,
        'data-thumb-sizes' => true,
        'data-webm'        => true,
        'data-mp4'         => true
    ),
    'img'    => array(
        'src'      => true,
        'alt'      => true,
        'class'    => true,
        'data-src' => true,
        'width'    => true,
        'height'   => true,
    ),
    'a'      => array(
        'href'      => true,
        'class'     => true,
        'data-webm' => true,
        'data-mp4'  => true,
    ),
);

register_activation_hook(__FILE__, 'mpvw_on_plugin_activation');

function mpvw_on_plugin_activation()
{
    mpvw_reorder_metabox();
    mpvw_check_requirements();
}

function mpvw_reorder_metabox()
{
    // Reorder metabox on sidebar for woocommerce product page
    $current_value = get_user_meta(get_current_user_id(), 'meta-box-order_product', true);
    $side = $current_value['side'];

    $side_array = explode(',', $side);

    $image_index = array_search('woocommerce-product-images', $side_array);
    $video_index = array_search(MPVW_PLUGIN_SLUG, $side_array);

    if ($video_index !== false) {
        unset($side_array[$video_index]);
        $side_array = array_values($side_array);
    }

    if ($image_index !== false) {
        array_splice($side_array, $image_index + 1, 0, MPVW_PLUGIN_SLUG);
    }

    $updated_side = implode(',', $side_array);

    update_user_meta(
        get_current_user_id(),
        'meta-box-order_product',
        array(
            'side'     => $updated_side,
            'normal'   => 'woocommerce-product-data,postcustom,slugdiv,postexcerpt',
            'advanced' => '',
        )
    );
}

function mpvw_check_requirements()
{
    $ffmpeg = exec('which ffmpeg');
    $ffmpeg = trim($ffmpeg);
    if ($ffmpeg === '') {
        add_option('mpvw_requirement_notice_ffmpeg', true);
    } else {
        delete_option('mpvw_requirement_notice_ffmpeg');
    }

    if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
        add_option('mpvw_requirements_notice_woocommerce', true);
    } else {
        delete_option('mpvw_requirements_notice_woocommerce');
    }
}

add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'mpvw_add_settings_link');

function mpvw_add_settings_link($links)
{
    $settings_url = admin_url('admin.php?page=mpvw_settings');
    $settings_link = '<a href="' . esc_url($settings_url) . '">' . esc_html_x('Settings', 'admin', 'magic-product-video-for-woocommerce') . '</a>';
    array_unshift($links, $settings_link);
    return $links;
}

add_action('admin_enqueue_scripts', 'mpvw_enqueue_admin_scripts_and_styles');

function mpvw_enqueue_admin_scripts_and_styles()
{
    wp_enqueue_script(
        MPVW_PLUGIN_SLUG,
        plugin_dir_url(__FILE__) . MPVW_PLUGIN_SLUG . '.js',
        ['jquery'],
        MPVW_PLUGIN_VERSION,
        true
    );

    wp_enqueue_style(
        MPVW_PLUGIN_SLUG,
        plugin_dir_url(__FILE__) . MPVW_PLUGIN_SLUG . '.css',
        [],
        MPVW_PLUGIN_VERSION,
        'all'
    );

    wp_localize_script(MPVW_PLUGIN_SLUG, 'ajaxDataMPVW', [
        'ajaxUrl'      => admin_url('admin-ajax.php'),
        'nonce'        => wp_create_nonce(MPVW_ADMIN_NONCE),
        'translations' => [
            'button'        => [
                'upload' => __('Upload Video', 'magic-product-video-for-woocommerce'),
                'change' => __('Change Video', 'magic-product-video-for-woocommerce'),
            ],
            'fileFrame'     => [
                'title'  => __('Select a Video', 'magic-product-video-for-woocommerce'),
                'button' => [
                    'text' => __('Use this video', 'magic-product-video-for-woocommerce')
                ]
            ],
            'notifications' => [
                'missingFormats' => __('Missing formats of video:', 'magic-product-video-for-woocommerce')
            ]
        ]
    ]);
}

add_action('wp_ajax_mpvw_dismiss_notice', 'mpvw_dismiss_notice_after_activation');

function mpvw_dismiss_notice_after_activation()
{
    check_ajax_referer(MPVW_ADMIN_NONCE, 'nonce');

    $noticeType = isset($_POST['type']) ? sanitize_text_field(wp_unslash($_POST['type'])) : '';

    if ($noticeType) {
        delete_option($noticeType);
        wp_send_json_success(['message' => 'Notice dismissed', 'notice' => $noticeType]);
    } else {
        wp_send_json_error(['message' => 'Invalid notice type']);
    }
}

add_action('admin_notices', 'mpvw_show_notice_after_activation');

function mpvw_show_notice_after_activation()
{
    if (get_option('mpvw_requirements_notice_woocommerce')) {
        ?>
        <div class="notice notice-warning mpvw-notice is-dismissible" data-type="mpvw_requirements_notice_woocommerce">
            <p>
                <?php echo wp_kses(__('To use the <b>Magic Product Video for WooCommerce</b> plugin, the <b>Woocommerce</b> plugin must be installed.', 'magic-product-video-for-woocommerce'), array('b' => array()));
                ?>
            </p>
        </div>
        <?php
    }

    if (get_option('mpvw_requirement_notice_ffmpeg')) {
        ?>
        <div class="notice notice-warning mpvw-notice is-dismissible" data-type="mpvw_requirement_notice_ffmpeg">
            <p>
                <?php echo wp_kses(__('To ensure the full functionality of the plugin <b>Magic Product Video for WooCommerce</b>, the <b>FFmpeg library</b> installation is required.', 'magic-product-video-for-woocommerce'), array('b' => array())); ?>
            </p>

        </div>
        <?php
    }
}

// Add a meta box to the product edit page
add_action('add_meta_boxes', 'mpvw_add_video_upload_metabox');

function mpvw_add_video_upload_metabox()
{
    $plugin_settings_default = mpvw_get_default_plugin_settings();
    $plugin_settings_values = get_option(MPVW_PLUGIN_OPTIONS['plugin_settings'], $plugin_settings_default);
    if (!is_array($plugin_settings_values)) $plugin_settings_values = json_decode($plugin_settings_values, true);

    if (!is_array($plugin_settings_values['postTypes'])) {
        $plugin_settings_values['postTypes'] = [];
    }
    $plugin_settings_values['postTypes'][] = ['name' => 'product', 'label' => __('Product', 'magic-product-video-for-woocommerce')];

    foreach ($plugin_settings_values['postTypes'] as $post_type) {
        add_meta_box(
            MPVW_PLUGIN_SLUG,
            __('Product Video', 'magic-product-video-for-woocommerce'),
            'mpvw_render_video_upload_metabox',
            $post_type['name'],
            'side',
            'core'
        );
    }
}

function mpvw_render_video_upload_metabox($post)
{
    $product_video_meta = get_post_meta($post->ID, MPVW_META_BOX_KEY_PVD, true);
    $product_video_data = $product_video_meta === '' ? false : json_decode($product_video_meta, true);
    ?>
    <div class="product-video-woocommerce-block">
        <div class="product-video-woocommerce-block__notification"></div>
        <div class="product-video-woocommerce__player">
            <video id="product_video_player"
                   width="auto"
                   height="auto"
                   controls
                   autoplay
                   loop
                   muted
                   class="<?php echo(!!$product_video_data ? 'product-video-woocommerce-show' : 'product-video-woocommerce-hide'); ?>">
                <source src="<?php if (!!$product_video_data && $product_video_data['webm']) echo esc_attr($product_video_data['webm']); ?>"
                        type="video/webm">
                <source src="<?php if (!!$product_video_data && $product_video_data['mp4']) echo esc_attr($product_video_data['mp4']) ?>"
                        type="video/mp4">
            </video>
        </div>

        <?php wp_nonce_field('mpvw_save_product_video', 'mpvw_nonce'); ?>

        <input type="hidden"
               id="product_video_url"
               name="product_video_url"
               value="<?php echo esc_attr($product_video_meta); ?>">

        <div class="product-video-woocommerce-block__control">
            <button type="button"
                    id="upload_video_button_clear"
                    class="button <?php echo !!$product_video_data ? esc_attr('product-video-woocommerce-show') : esc_attr('product-video-woocommerce-hide'); ?>">
                <?php esc_html_e('Remove Video', 'magic-product-video-for-woocommerce'); ?>
            </button>
            <button type="button"
                    id="upload_video_button"
                    class="button button button-primary">
                <?php !!$product_video_data ? esc_html_e('Change Video', 'magic-product-video-for-woocommerce') : esc_html_e('Upload Video', 'magic-product-video-for-woocommerce'); ?>
            </button>
        </div>
    </div>

    <div id="product-video-woocommerce-preloader" style="display:none;">
        <div class="video-spinner"></div>
        <p><?php esc_html_e('File conversion into the required formats for proper display across different browsers, please wait...', 'magic-product-video-for-woocommerce'); ?></p>
        <div class="progress-container">
            <div id="progress-bar-mp4" class="progress-bar"></div>
            <div id="progress-bar-webm" class="progress-bar"></div>
        </div>
    </div>
    <?php
}

add_action('save_post', 'mpvw_save_product_video_data');

function mpvw_save_product_video_data($post_id)
{
    if (!isset($_POST['mpvw_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['mpvw_nonce'])), 'mpvw_save_product_video')) {
        return $post_id;
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;

    if (isset($_POST['product_video_url'])) {
        $product_video_url = sanitize_text_field(wp_unslash($_POST['product_video_url']));
        if ($product_video_url === '') {
            delete_post_meta($post_id, MPVW_META_BOX_KEY_PVD);
        } else {
            update_post_meta($post_id, MPVW_META_BOX_KEY_PVD, sanitize_text_field($product_video_url));
        }
    }

    return $post_id;
}

add_action('wp_ajax_mpvw_convert_video_format', 'mpvw_convert_video_format');

function mpvw_convert_video_format()
{
    if (!function_exists('wp_mkdir_p')) require_once ABSPATH . 'wp-admin/includes/file.php';
    global $wp_filesystem;
    if (!WP_Filesystem()) {
        // Handle error: WP_Filesystem initialization failed
        wp_die(esc_html__('Unable to initialize the WP_Filesystem API.', 'magic-product-video-for-woocommerce'));
    }

    if (!isset($_POST['_ajax_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_ajax_nonce'])), MPVW_ADMIN_NONCE)) {
        die('Permission denied');
    }

    $upload_dir = wp_upload_dir();
    $output_dir = $upload_dir['basedir'] . '/product-video-woocommerce/';


    if (!$wp_filesystem->exists($output_dir)) {
        $wp_filesystem->mkdir($output_dir, FS_CHMOD_DIR);
    }

    $with_audio = false; // Make variable
    $attachment_id = !empty($_POST['attachment_id']) ? intval(sanitize_text_field(wp_unslash($_POST['attachment_id']))) : '';
    $file_path = get_attached_file($attachment_id);
    $file_url = wp_get_attachment_url($attachment_id);
    $file_info = pathinfo($file_path);
    $file_extension = $file_info['extension'];
    $file_duration = mpvw_get_video_duration($file_path);

    $converted_video_files = get_post_meta($attachment_id, MPVW_META_BOX_KEY_CVF, true);

    if (!$converted_video_files) {

        if (in_array($file_extension, MPVW_ALLOWED_FORMATS)) {
            $ffmpeg = exec('which ffmpeg');
            $ffmpeg = trim($ffmpeg);
            if ($ffmpeg) {
                $attachment_ids = [$attachment_id];

                $output_thumbnail = $output_dir . $file_info['filename'] . '.jpg';
                exec("ffmpeg -i $file_path -ss 1 -vframes 1 $output_thumbnail");
                $thumbnail_attachment_id = wp_insert_attachment([
                                                                    'post_mime_type' => 'image/jpg',
                                                                    /* translators: the cover file name matches the name of the uploaded video file  */
                                                                    'post_title'     => sprintf(__('Cover of product video: %s.jpg', 'magic-product-video-for-woocommerce'), $file_info['filename']),
                                                                    'post_content'   => '',
                                                                    'post_status'    => 'inherit',
                                                                    'guid'           => $output_thumbnail
                                                                ], $output_thumbnail);
                if (!is_wp_error($thumbnail_attachment_id)) {
                    $attachment_metadata = wp_generate_attachment_metadata($thumbnail_attachment_id, $output_thumbnail);
                    wp_update_attachment_metadata($thumbnail_attachment_id, $attachment_metadata);
                }

                $response = [
                    'original'     => $file_url,
                    'thumbnail_id' => $thumbnail_attachment_id
                ];

                $progress_files = [];

                foreach (MPVW_REQUIRED_FORMATS as $format) {
                    $progress_file = $output_dir . uniqid('progress_') . '.txt';
                    $output_file = $output_dir . $file_info['filename'] . '.' . $format;

                    /**
                     * Get and prepare all ffmpeg settings
                     */
                    $ffmpeg_settings = get_option(MPVW_PLUGIN_OPTIONS['ffmpeg_settings']);
                    $ffmpeg_settings = $ffmpeg_settings ?? get_default_ffmpeg_settings();
                    $property_format_name = ucfirst($format);
                    $audio = $ffmpeg_settings['withoutAudio'] ? ['-an'] : ['-c:a', $ffmpeg_settings['audioCodec' . $property_format_name]];
                    $video_codec = $ffmpeg_settings['videoCodec' . $property_format_name];
                    $width = $ffmpeg_settings['resolutionWidth'];
                    $height = $ffmpeg_settings['resolutionHeight'];
                    $filters = [];
                    if ($width == -1 && $height == -1) {
                        $filters[] = 'scale=iw:ih';
                    } elseif ($width != -1 && $height == -1) {
                        $filters[] = "scale=$width:-1";
                    } elseif ($width == -1 && $height != -1) {
                        $filters[] = "scale=-1:$height";
                    } else {
                        if ($ffmpeg_settings['scalingMode'] === 'contain') {
                            $filters[] = "scale=$width:$height:force_original_aspect_ratio=decrease";
                            $filters[] = "pad=$width:$height:(ow-iw)/2:(oh-ih)/2";
                        } elseif ($ffmpeg_settings['scalingMode'] === 'cover') {
                            $filters[] = "scale=$width:$height:force_original_aspect_ratio=increase";
                            $filters[] = "crop=$width:$height";
                        } else {
                            $filters[] = "scale=$width:$height";
                        }
                    }
                    $video_filter = implode(',', $filters);

                    $cmd_parts = [
                        escapeshellcmd($ffmpeg),
                        '-i', escapeshellarg($file_path),
                        '-c:v', escapeshellarg($video_codec),
                        '-crf', escapeshellarg($ffmpeg_settings['crf']),
                        '-preset', escapeshellarg($ffmpeg_settings['preset']),
                        '-vf', escapeshellarg($video_filter),
                        ...$audio,
                        '-y',
                        escapeshellarg($output_file),
                        '-report',
                        '-progress', escapeshellarg($progress_file),
                    ];
                    $cmd = implode(' ', $cmd_parts) . ' > /dev/null 2>&1 &';
                    exec($cmd);

                    // TODO: Add only when process of conversion will done
                    $converted_attachment_id = wp_insert_attachment([
                                                                        'post_mime_type' => 'video/' . $format,
                                                                        'post_title'     => $file_info['filename'] . '.' . $format,
                                                                        'post_content'   => '',
                                                                        'post_status'    => 'inherit',
                                                                        'guid'           => $output_file
                                                                    ], $output_file);

                    if (!is_wp_error($converted_attachment_id)) {
                        $attachment_ids[] = $converted_attachment_id;
                        $progress_files[$format] = $progress_file;
                        $file_url = wp_get_attachment_url($converted_attachment_id);
                        $response[$format] = $file_url;
                    }
                }

                $response = mpvw_validate_product_video_data($response);

                $value = wp_json_encode($response);
                foreach ($attachment_ids as $id) {
                    update_post_meta($id, MPVW_META_BOX_KEY_CVF, $value);
                }

                wp_send_json_success([
                                         'progress_files' => $progress_files,
                                         'files'          => $response,
                                         'duration'       => $file_duration
                                     ]);
            } else {
                if (in_array($file_extension, MPVW_REQUIRED_FORMATS)) {
                    $data = mpvw_validate_product_video_data([$file_extension => $file_url]);
                    $filtered_required_formats = array_filter(MPVW_REQUIRED_FORMATS, function ($format) use ($file_extension) {
                        return strtolower($format) !== strtolower($file_extension);
                    });
                    wp_send_json_success([
                                             'progress_files' => null,
                                             'files'          => $data,
                                             'duration'       => $file_duration,
                                             'missing_format' => array_values($filtered_required_formats)
                                         ]);
                } else {
                    wp_send_json_error(__('FFmpeg not found or not installed. Needed for conversion to the required formats.', 'magic-product-video-for-woocommerce'));
                }
            }
        } else {
            /* translators: file extension that does not support  */
            wp_send_json_error(sprintf(__('Format of file (%s) is not supported', 'magic-product-video-for-woocommerce'), $file_extension));
        }
    } else {
        wp_send_json_success([
                                 'progress_files' => null,
                                 'files'          => json_decode($converted_video_files),
                                 'duration'       => $file_duration
                             ]);
    }
}

add_action('wp_ajax_mpvw_get_conversion_progress', 'mpvw_get_conversion_progress');

function mpvw_get_conversion_progress()
{
    if (!function_exists('wp_mkdir_p')) require_once ABSPATH . 'wp-admin/includes/file.php';
    global $wp_filesystem;
    if (!WP_Filesystem()) {
        // Handle error: WP_Filesystem initialization failed
        wp_die(esc_html__('Unable to initialize the WP_Filesystem API.', 'magic-product-video-for-woocommerce'));
    }

    if (!isset($_POST['_ajax_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_ajax_nonce'])), MPVW_ADMIN_NONCE)) {
        die('Permission denied');
    }

    $progress_file = isset($_POST['progress_file']) ? str_replace('\\', '', sanitize_text_field(wp_unslash($_POST['progress_file']))) : '';

    if (!file_exists($progress_file)) {
        /* translators: path to conversion progress file  */
        wp_send_json_error(sprintf(__('Progress file (%s) not found.', 'magic-product-video-for-woocommerce'), $progress_file));
    }

    if ($wp_filesystem->exists($progress_file)) {
        $progress_content = $wp_filesystem->get_contents($progress_file);
        wp_send_json_success(['progressContent' => $progress_content]);
    } else {
        wp_send_json_error(['message' => esc_html__('Progress file not found.', 'magic-product-video-for-woocommerce')]);
    }
}


function mpvw_get_video_duration($file_path)
{
    $duration_seconds = shell_exec("ffprobe -v quiet -show_entries format=duration -of csv=p=0 $file_path");
    $duration_microseconds = (float)$duration_seconds * 1000000;
    return (int)$duration_microseconds;
}


function mpvw_validate_product_video_data(array $data)
{
    $required_keys = ['mp4', 'webm', 'thumbnail_id'];
    foreach ($required_keys as $key) {
        if (!array_key_exists($key, $data)) {
            $data[$key] = null;
        }
    }
    return $data;
}

function mpvw_get_default_plugin_settings(): array
{
    return [
        'postTypes' => []
    ];
}

function mpvw_get_default_settings(): array
{
    $flexSlider = (bool)apply_filters('woocommerce_single_product_flexslider_enabled', get_theme_support('wc-product-gallery-slider'));
    return [
        'flexSlider'        => $flexSlider,
        'syncWpmlLanguages' => false,
        'isWpmlActivated'   => defined('ICL_SITEPRESS_VERSION')
    ];
}

function mpvw_get_product_video_data($product_id = null)
{
    if (is_null($product_id)) {
        global $product;
        $product_id = $product ? $product->get_id() : null;
    }


    $product_video_data = mpvw_get_product_video_meta($product_id);
    if (is_array($product_video_data)) {
        return $product_video_data;
    } else {

        $settings_default = mpvw_get_default_settings();
        $settings_values = get_option(MPVW_PLUGIN_OPTIONS['settings'], $settings_default);
        if (!is_array($settings_values)) $settings_values = json_decode($settings_values, true);
        // Migration to new fields set
        $settings_values = array_merge($settings_default, $settings_values);

        if ($settings_values['syncWpmlLanguages']) {
            return mpvw_get_product_video_by_translations($product_id);
        }
    }
    return false;
}

function mpvw_get_product_video_meta($product_id = null)
{
    $product_video_meta = $product_id ? get_post_meta($product_id, MPVW_META_BOX_KEY_PVD, true) : '';
    $product_video_data = $product_video_meta === '' ? false : json_decode($product_video_meta, true);
    if ($product_video_data && is_array($product_video_data)) {
        return mpvw_validate_product_video_data($product_video_data);
    }
    return false;
}

function mpvw_get_product_video_by_translations($product_id)
{
    $default_lang_code = apply_filters('wpml_default_language', null);
    $product_lang_code = apply_filters('wpml_element_language_code', null, [
        'element_id'   => $product_id,
        'element_type' => 'post_product'
    ]);

    if ($product_lang_code !== $default_lang_code) {
        $default_translated_product_id = apply_filters('wpml_object_id', $product_id, 'product', false, $default_lang_code);
        $default_translated_product_video_data = mpvw_get_product_video_meta($default_translated_product_id);
        if (is_array($default_translated_product_video_data)) {
            return $default_translated_product_video_data;
        }
    }

    if ($product_lang_code == $default_lang_code) {
        $trid = apply_filters('wpml_element_trid', null, $product_id, 'post_product');
        $translations = apply_filters('wpml_get_element_translations', null, $trid, 'post_product');
        if (!empty($translations)) {
            foreach ($translations as $lang => $translation) {
                if (!empty($translation->element_id) && $lang != $product_lang_code) {
                    $translated_product_video_data = mpvw_get_product_video_meta($translation->element_id);
                    if (is_array($translated_product_video_data)) {
                        return $translated_product_video_data;
                    }
                }
            }
        }
    }

    return false;
}

require_once MPVW_PLUGIN_DIR . 'magic-product-video-for-woocommerce-ui.php';

if (is_admin()) {
    require_once MPVW_PLUGIN_DIR . 'admin/app.php';
    require_once MPVW_PLUGIN_DIR . 'admin/ajax.php';
}
