<?php
/**
 * Woocommerce filters and actions for UI
 */

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

if (!function_exists('mpvw_is_woocommerce_active')) {
    function mpvw_is_woocommerce_active()
    {
        return in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')));
    }
}

if (mpvw_is_woocommerce_active()) {
    add_action('wp_enqueue_scripts', 'mpvw_front_enqueue_styles');
    function mpvw_front_enqueue_styles()
    {
        wp_enqueue_style(
            MPVW_PLUGIN_SLUG . '-videojs',
            plugin_dir_url(__FILE__) . 'assets/css/video-js.min.css',
            [],
            '8.22.0'
        );

        wp_enqueue_style(
            MPVW_PLUGIN_SLUG,
            plugin_dir_url(__FILE__) . 'assets/css/styles.css',
            [],
            MPVW_PLUGIN_VERSION
        );

        $default_skin_icons_url = plugins_url('/assets/images/default-skin-icons.svg', __FILE__);
        wp_add_inline_style(
            MPVW_PLUGIN_SLUG . '-styles',
            '.mpvw-video-container button { background-image: url("' . esc_url($default_skin_icons_url) . '"); }'
        );

        wp_enqueue_script(
            MPVW_PLUGIN_SLUG,
            plugin_dir_url(__FILE__) . 'assets/js/scripts.js',
            ['jquery'],
            MPVW_PLUGIN_VERSION,
            ['in_footer' => true]
        );

        wp_enqueue_script(
            MPVW_PLUGIN_SLUG . '-videojs',
            plugin_dir_url(__FILE__) . 'assets/js/video.min.js',
            [],
            '8.22.0',
            ['in_footer' => true]
        );

        $player_configs = get_option(MPVW_PLUGIN_OPTIONS['player_configs']);
        if ($player_configs && is_array($player_configs)) {
            wp_localize_script(
                MPVW_PLUGIN_SLUG,
                'playerOptionsMPVW',
                $player_configs
            );
        };

        if (is_array($player_configs)) {
            $background = !empty($player_configs['bgTransparent']) ? 'transparent' : $player_configs['background'];
            $mpvw_inline_css = ".video-js {background: $background;}";
            wp_add_inline_style(MPVW_PLUGIN_SLUG, $mpvw_inline_css);
        }
    }

    add_filter('woocommerce_single_product_image_gallery_classes', function ($classes) {
        $product_video_data = mpvw_get_product_video_data();
        $classes[] = !!$product_video_data ? 'woocommerce-product-gallery--with-video' : '';
        return $classes;
    });

    add_action('woocommerce_product_thumbnails', 'mpvw_show_product_video', 30);
    function mpvw_show_product_video()
    {
        $product_video_data = mpvw_get_product_video_data();
        if (!!$product_video_data) {
            $video_mp4 = $product_video_data['mp4'];
            $video_webm = $product_video_data['webm'];
            $thumbnail_id = $product_video_data['thumbnail_id'] ?? intval(get_option('woocommerce_placeholder_image'));
            $html = mpvw_get_gallery_video_html($video_mp4, $video_webm, $thumbnail_id);
            echo wp_kses(apply_filters('mpvw_single_product_video_thumbnail_html', $html, $video_mp4, $video_webm, $thumbnail_id), MPVW_ALLOWED_HTML);
        }
    }

    function mpvw_get_gallery_video_html($video_mp4 = null, $video_webm = null, $thumbnail_id = null)
    {
        $video_html = '';
        if (!is_null($thumbnail_id)) {
            $flex_slider = (bool)apply_filters('woocommerce_single_product_flexslider_enabled', get_theme_support('wc-product-gallery-slider'));
            $gallery_thumbnail = wc_get_image_size('gallery_thumbnail');
            $thumbnail_size = apply_filters('woocommerce_gallery_thumbnail_size', array($gallery_thumbnail['width'], $gallery_thumbnail['height']));
            $thumbnail_src = wp_get_attachment_image_src($thumbnail_id, $thumbnail_size);
            $thumbnail_sizes = wp_get_attachment_image_sizes($thumbnail_id, $thumbnail_size);
            $alt_text = trim(wp_strip_all_tags(get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true))) ?? _x('Product video cover', 'front', 'magic-product-video-for-woocommerce');

            if (!$flex_slider) {
                add_filter('mpvw_single_product_video_thumbnail_html', 'mpvw_change_single_product_image_thumbnail_html', 10, 4);
                add_filter('woocommerce_gallery_image_html_attachment_image_params', 'mpvw_add_custom_class_to_gallery_image_params', 10, 4);
                $video_html .= wc_get_gallery_image_html($thumbnail_id);
            } else {
                remove_filter('woocommerce_gallery_image_html_attachment_image_params', 'mpvw_add_custom_class_to_gallery_image_params', 10);
                remove_filter('mpvw_single_product_video_thumbnail_html', 'mpvw_change_single_product_image_thumbnail_html', 10);

                $video_html .= '<div class="woocommerce-product-gallery__image" data-thumb="' . esc_url($thumbnail_src[0]) . '" data-thumb-sizes="' . esc_attr($thumbnail_sizes) . '" data-thumb-alt="' . esc_attr($alt_text) . '">';
                $video_html .= '<div class="woocommerce-product-gallery-video">';
                $video_html .= '<div class="woocommerce-product-gallery-video__player">';
                $video_html .= '<video class="mpvw-video video-js" autoplay muted loop>';
                if ($video_webm) $video_html .= '<source src="' . $video_webm . '" type="video/webm">';
                if ($video_mp4) $video_html .= '<source src="' . $video_mp4 . '" type="video/mp4">';
                $video_html .= '</video>';
                $video_html .= '</div>';
                $video_html .= '</div>';
                $video_html .= '</div>';
            }
            return $video_html;
        } else {
            return $video_html;
        }
    }

    function mpvw_change_single_product_image_thumbnail_html($html, $video_mp4, $video_webm, $thumbnail_id)
    {
        $html = str_replace('woocommerce-product-gallery__image', 'woocommerce-product-gallery__video', $html);
        $html = preg_replace_callback(
            '/<a([^>]*)>(.*?)<\/a>/',
            function ($matches) use ($video_mp4, $video_webm) {
                $additional_attributes = ' class="mpvw-thumbnail"';
                $additional_attributes .= ' data-webm="' . esc_attr($video_webm) . '"';
                $additional_attributes .= ' data-mp4="' . esc_attr($video_mp4) . '"';
                return '<div' . $matches[1] . $additional_attributes . '>' . $matches[2] . '</div>';
            },
            $html
        );
        $html = str_replace('href="', 'data-href="', $html);

        return $html;
    }

    function mpvw_add_custom_class_to_gallery_image_params($image_params, $attachment_id, $image_size, $main_image)
    {
        $image_params['class'] = 'mpvw-thumbnail-video';
        return $image_params;
    }

    mpvw_apply_settings();
}

/**
 * Apply default and saved settings of plugins
 * @return void
 */
function mpvw_apply_settings(): void
{
    $settings = get_option(MPVW_PLUGIN_OPTIONS['settings'], []);

    if (!is_array($settings)) {
        $settings = json_decode($settings, true);
    }

    if (key_exists('flexSlider', $settings)) {
        add_filter('woocommerce_single_product_flexslider_enabled', function () use ($settings) {
            return filter_var($settings['flexSlider'], FILTER_VALIDATE_BOOLEAN);
        });
    }
}


