<?php

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

class AIEO_DMM_Product_Video extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_dmm_product_video_settings';
    private $embedded = false;

    public function get_id()       { return 'product_video'; }
    public function get_label()    { return __('Product Video', 'ai-eshop-optimizer'); }
    public function get_priority() { return 60; }
    public function get_group()    { return 'product_display'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_product_video_save', array($this, 'ajax_save'));

        $s = $this->get_settings();
        if (empty($s['enabled'])) { return; }

        
        add_action('add_meta_boxes',     array($this, 'add_meta_box'));
        add_action('save_post_product',  array($this, 'save_meta_box'));
        add_action('admin_enqueue_scripts', array($this, 'admin_enqueue'));

        
        add_action('wp_enqueue_scripts', array($this, 'register_scripts'));
        add_filter('woocommerce_post_class', array($this, 'add_video_class'), 10, 2);
        add_filter('woocommerce_single_product_image_thumbnail_html', array($this, 'add_featured_video'), 5, 2);
        add_filter('woocommerce_single_product_image_thumbnail_html', array($this, 'add_gallery_videos'), 10, 2);
    }

    public function get_settings() {
        $stored = get_option(self::OPTION_KEY, array());
        if (!is_array($stored)) { $stored = array(); }
        $legacy = get_option('om_ppe_product-video', array());
        if (!is_array($legacy)) { $legacy = array(); }
        return array_merge(array(
            'enabled'              => false,
            'default_autoplay'     => false,
            'default_aspect_ratio' => '16-9',
        ), $legacy, $stored);
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        $valid_ratios = array('16-9','9-16','4-3','3-2','1-1','auto');
        $ar = isset($_POST['default_aspect_ratio']) ? sanitize_key(wp_unslash($_POST['default_aspect_ratio'])) : '16-9';
        update_option(self::OPTION_KEY, array(
            'enabled'              => !empty($_POST['enabled']),
            'default_autoplay'     => !empty($_POST['default_autoplay']),
            'default_aspect_ratio' => in_array($ar, $valid_ratios, true) ? $ar : '16-9',
        ), false);
        wp_send_json_success(array('message' => __('Product Video settings saved.', 'ai-eshop-optimizer')));
    }

    public function register_scripts() {
        $version = defined('AIEO_VERSION') ? AIEO_VERSION : '1.0';
        wp_register_style(
            'aieo-product-video',
            plugins_url('assets/css/product-display/product-video.css', AIEO_FILE),
            array(), $version
        );
        wp_register_script(
            'aieo-product-video',
            plugins_url('assets/js/product-display/product-video.js', AIEO_FILE),
            array('jquery'), $version, true
        );
        if (function_exists('is_product') && is_product()) {
            wp_enqueue_style('aieo-product-video');
        }
    }

    public function admin_enqueue($hook) {
        if (!in_array($hook, array('post.php','post-new.php'), true)) { return; }
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if (!$screen || $screen->post_type !== 'product') { return; }
        
    }

    public function add_meta_box() {
        add_meta_box('aieo_product_video', __('Product Video', 'ai-eshop-optimizer'), array($this, 'render_meta_box'), 'product', 'side', 'default');
    }

    public function render_meta_box($post) {
        wp_nonce_field('aieo_product_video', 'aieo_product_video_nonce');
        $enable_featured = get_post_meta($post->ID, '_merchant_enable_featured_video', true);
        $video_url       = get_post_meta($post->ID, '_merchant_product_video_url', true);
        $autoplay        = get_post_meta($post->ID, '_merchant_product_video_autoplay', true);
        $aspect_ratio    = get_post_meta($post->ID, '_merchant_product_video_aspect_ratio', true);
        if ($aspect_ratio === '') { $aspect_ratio = (string) $this->get_settings()['default_aspect_ratio']; }
        $enable_gallery  = get_post_meta($post->ID, '_merchant_enable_gallery', true);
        $gallery_videos  = get_post_meta($post->ID, '_merchant_videos_in_gallery', true);
        $video_position  = get_post_meta($post->ID, '_merchant_video_position', true);
        ?>
        <div class="aieo-product-video-metabox">
            <p><label><input type="checkbox" name="_merchant_enable_featured_video" value="1" <?php checked($enable_featured, '1'); ?>> <?php esc_html_e('Enable Featured Video', 'ai-eshop-optimizer'); ?></label></p>
            <p class="aieo-pv-url" style="<?php echo empty($enable_featured) ? 'display:none;' : ''; ?>">
                <label for="_merchant_product_video_url"><?php esc_html_e('Video URL', 'ai-eshop-optimizer'); ?></label>
                <input type="text" id="_merchant_product_video_url" name="_merchant_product_video_url" value="<?php echo esc_attr((string) $video_url); ?>" class="widefat" placeholder="https://youtube.com/watch?v=...">
                <span class="description"><?php esc_html_e('YouTube, Vimeo, or self-hosted video URL', 'ai-eshop-optimizer'); ?></span>
            </p>
            <p class="aieo-pv-autoplay" style="<?php echo empty($enable_featured) ? 'display:none;' : ''; ?>">
                <label><input type="checkbox" name="_merchant_product_video_autoplay" value="1" <?php checked($autoplay, '1'); ?>> <?php esc_html_e('Autoplay (muted)', 'ai-eshop-optimizer'); ?></label>
            </p>
            <p>
                <label for="_merchant_product_video_aspect_ratio"><?php esc_html_e('Aspect Ratio', 'ai-eshop-optimizer'); ?></label>
                <select id="_merchant_product_video_aspect_ratio" name="_merchant_product_video_aspect_ratio" class="widefat">
                    <?php foreach (array('16-9','9-16','4-3','3-2','1-1','auto') as $r): ?>
                        <option value="<?php echo esc_attr($r); ?>" <?php selected($aspect_ratio, $r); ?>><?php echo esc_html($r === 'auto' ? __('Auto', 'ai-eshop-optimizer') : str_replace('-', ':', $r)); ?></option>
                    <?php endforeach; ?>
                </select>
            </p>
            <hr>
            <p><label><input type="checkbox" name="_merchant_enable_gallery" value="1" <?php checked($enable_gallery, '1'); ?>> <?php esc_html_e('Enable Video Gallery', 'ai-eshop-optimizer'); ?></label></p>
            <div class="aieo-pv-gallery" style="<?php echo empty($enable_gallery) ? 'display:none;' : ''; ?>">
                <p>
                    <label><?php esc_html_e('Gallery Video URLs (one per line)', 'ai-eshop-optimizer'); ?></label>
                    <textarea name="_merchant_videos_in_gallery" rows="4" class="widefat"><?php echo esc_textarea(is_array($gallery_videos) ? implode("\n", $gallery_videos) : ''); ?></textarea>
                </p>
                <p>
                    <label for="_merchant_video_position"><?php esc_html_e('Video Position', 'ai-eshop-optimizer'); ?></label>
                    <select id="_merchant_video_position" name="_merchant_video_position" class="widefat">
                        <option value="before" <?php selected($video_position, 'before'); ?>><?php esc_html_e('Before Image Gallery', 'ai-eshop-optimizer'); ?></option>
                        <option value="after"  <?php selected($video_position, 'after'); ?>><?php esc_html_e('After Image Gallery', 'ai-eshop-optimizer'); ?></option>
                    </select>
                </p>
            </div>
        </div>
        <script>
            jQuery(function($){
                $('input[name="_merchant_enable_featured_video"]').on('change', function(){ $('.aieo-pv-url, .aieo-pv-autoplay').toggle(this.checked); });
                $('input[name="_merchant_enable_gallery"]').on('change', function(){ $('.aieo-pv-gallery').toggle(this.checked); });
            });
        </script>
        <?php
    }

    public function save_meta_box($post_id) {
        if (!isset($_POST['aieo_product_video_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['aieo_product_video_nonce'])), 'aieo_product_video')) { return; }
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; }
        if (!current_user_can('edit_post', $post_id)) { return; }

        update_post_meta($post_id, '_merchant_enable_featured_video', isset($_POST['_merchant_enable_featured_video']) ? '1' : '');
        update_post_meta($post_id, '_merchant_product_video_url', isset($_POST['_merchant_product_video_url']) ? esc_url_raw(wp_unslash($_POST['_merchant_product_video_url'])) : '');
        update_post_meta($post_id, '_merchant_product_video_autoplay', isset($_POST['_merchant_product_video_autoplay']) ? '1' : '');
        $ar = isset($_POST['_merchant_product_video_aspect_ratio']) ? sanitize_text_field(wp_unslash($_POST['_merchant_product_video_aspect_ratio'])) : '16-9';
        update_post_meta($post_id, '_merchant_product_video_aspect_ratio', $ar);
        update_post_meta($post_id, '_merchant_enable_gallery', isset($_POST['_merchant_enable_gallery']) ? '1' : '');
        $gallery = array();
        if (!empty($_POST['_merchant_videos_in_gallery'])) {
            $lines = explode("\n", sanitize_textarea_field(wp_unslash($_POST['_merchant_videos_in_gallery'])));
            foreach ($lines as $line) {
                $url = trim($line);
                if ($url !== '') { $gallery[] = esc_url_raw($url); }
            }
        }
        update_post_meta($post_id, '_merchant_videos_in_gallery', $gallery);
        update_post_meta($post_id, '_merchant_video_position', isset($_POST['_merchant_video_position']) ? sanitize_text_field(wp_unslash($_POST['_merchant_video_position'])) : 'before');
    }

    public function add_video_class($classes, $product) {
        $is_main = is_singular('product') && $product->get_id() === get_queried_object_id();
        if ($is_main) { return $classes; }
        $url = (string) get_post_meta($product->get_id(), '_merchant_product_video_url', true);
        if ($url !== '') { $classes[] = 'om-ppe-product-has-video'; }
        return $classes;
    }

    public function add_featured_video($html, $post_thumbnail_id) {
        global $product;
        if (!$product) { return $html; }
        $enable = (string) get_post_meta($product->get_id(), '_merchant_enable_featured_video', true);
        $url    = (string) get_post_meta($product->get_id(), '_merchant_product_video_url', true);
        if ($enable === '' || $url === '') { return $html; }
        if (!has_post_thumbnail() || get_post_thumbnail_id() !== $post_thumbnail_id) { return $html; }
        ob_start(); $this->render_video($product->get_id()); $video_html = (string) ob_get_clean();
        $poster = $this->oembed_thumb($url) ?: plugins_url('assets/images/product-display/video-placeholder.svg', AIEO_FILE);
        return '<div data-thumb="' . esc_attr($poster) . '" class="woocommerce-product-gallery__image">' . $video_html . '</div>';
    }

    public function add_gallery_videos($html, $post_thumbnail_id) {
        global $product;
        if (!$product) { return $html; }
        $enable = (string) get_post_meta($product->get_id(), '_merchant_enable_gallery', true);
        $videos = (array) get_post_meta($product->get_id(), '_merchant_videos_in_gallery', true);
        $videos = array_filter($videos);
        if ($enable === '' || empty($videos)) { return $html; }
        if ($this->embedded) { return $html; }

        $position = (string) get_post_meta($product->get_id(), '_merchant_video_position', true);
        $ar = (string) get_post_meta($product->get_id(), '_merchant_product_video_aspect_ratio', true);
        if ($ar === '') { $ar = '16-9'; }
        $ar_class = $ar !== 'auto' ? 'om-ppe-video-ratio om-ppe-video-ratio-' . $ar : 'om-ppe-video-ratio-auto';
        $video_html = '';
        foreach ($videos as $url) {
            if ($url === '') { continue; }
            $ft = wp_check_filetype($url, wp_get_mime_types());
            $type = wp_ext2type($ft['ext']);
            if ($type === 'video') {
                $poster = plugins_url('assets/images/product-display/video-placeholder.svg', AIEO_FILE);
                $video_html .= '<div data-thumb="' . esc_url($poster) . '" data-video="html5" class="woocommerce-product-gallery__image">';
                $video_html .= '<div class="om-ppe-product-video ' . esc_attr($ar_class) . '">';
                $video_html .= '<video controls><source src="' . esc_url($url) . '" type="' . esc_attr($ft['type']) . '" /></video>';
                $video_html .= '</div></div>';
            } else {
                $oembed = _wp_oembed_get_object()->get_data($url);
                if (!empty($oembed)) {
                    $video_html .= '<div data-thumb="' . esc_attr($oembed->thumbnail_url ?? '') . '" data-video="oembed" class="woocommerce-product-gallery__image">';
                    $video_html .= '<div class="om-ppe-product-video ' . esc_attr($ar_class) . '">';
                    $video_html .= _wp_oembed_get_object()->data2html($oembed, $url);
                    $video_html .= '</div></div>';
                }
            }
        }
        if ($video_html !== '') {
            $html = ($position === 'after') ? $html . $video_html : $video_html . $html;
            $this->embedded = true;
            wp_enqueue_script('aieo-product-video');
        }
        return $html;
    }

    private function render_video($product_id) {
        $url      = (string) get_post_meta($product_id, '_merchant_product_video_url', true);
        $autoplay = (string) get_post_meta($product_id, '_merchant_product_video_autoplay', true);
        $ar       = (string) get_post_meta($product_id, '_merchant_product_video_aspect_ratio', true);
        if ($url === '') { return; }
        if ($ar === '') { $ar = (string) $this->get_settings()['default_aspect_ratio']; }
        $ar_class = $ar !== 'auto' ? 'om-ppe-video-ratio om-ppe-video-ratio-' . $ar : 'om-ppe-video-ratio-auto';
        $autoplay_attr = $autoplay !== '' ? ' autoplay muted loop playsinline' : ' controls';
        $ft = wp_check_filetype($url, wp_get_mime_types());
        $type = wp_ext2type($ft['ext']);
        if ($type === 'video') {
            echo '<div class="om-ppe-product-video ' . esc_attr($ar_class) . '">';
            echo '<video' . esc_attr($autoplay_attr) . '><source src="' . esc_url($url) . '" type="' . esc_attr($ft['type']) . '" /></video>';
            echo '</div>';
        } else {
            $oembed = _wp_oembed_get_object()->get_data($url);
            if (!empty($oembed)) {
                $oembed_html = (string) $oembed->html;
                if ($autoplay !== '' && in_array(strtolower((string) ($oembed->provider_name ?? '')), array('youtube','vimeo','dailymotion'), true)) {
                    if (preg_match('/<iframe.*src=\"(.*)\".*><\/iframe>/isU', $oembed_html, $m) && !empty($m[1])) {
                        $oembed_html = str_replace($m[1], add_query_arg(array(
                            'autoplay' => '1', 'mute' => '1', 'muted' => '1', 'controls' => '0',
                        ), $m[1]), $oembed_html);
                    }
                }
                echo '<div class="om-ppe-product-video ' . esc_attr($ar_class) . '">';
                echo wp_kses($oembed_html, array('iframe' => array('src' => true,'width' => true,'height' => true,'frameborder' => true,'allow' => true,'allowfullscreen' => true,'title' => true)));
                echo '</div>';
            }
        }
    }

    private function oembed_thumb($url) {
        $oembed = _wp_oembed_get_object()->get_data($url);
        return !empty($oembed->thumbnail_url) ? (string) $oembed->thumbnail_url : '';
    }

    public function render_subtab() {
        $s = $this->get_settings();
        $nonce = wp_create_nonce(AIEO_DMM::NONCE_ACTION);
        $ajax  = admin_url('admin-ajax.php');
        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Product Video', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Embed a video into the product gallery (YouTube / Vimeo / self-hosted). Per-product config lives on the product edit screen → "Product Video" meta box. Same `_merchant_*` post meta keys as the legacy module.', 'ai-eshop-optimizer') . '</p>';
        echo '<form id="aieo-dmm-pv-form" class="aieo-dmm-form aieo-dmm-card"><table class="form-table">';
        echo '<tr><th>' . esc_html__('Enable', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="enabled" value="1" ' . checked(!empty($s['enabled']), true, false) . '></label></td></tr>';
        echo '<tr><th>' . esc_html__('Default autoplay (per-product overridable)', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" name="default_autoplay" value="1" ' . checked(!empty($s['default_autoplay']), true, false) . '></label></td></tr>';
        echo '<tr><th>' . esc_html__('Default aspect ratio', 'ai-eshop-optimizer') . '</th><td><select name="default_aspect_ratio">';
        foreach (array('16-9','9-16','4-3','3-2','1-1','auto') as $r) {
            $label = $r === 'auto' ? __('Auto', 'ai-eshop-optimizer') : str_replace('-', ':', $r);
            echo '<option value="' . esc_attr($r) . '" ' . selected($s['default_aspect_ratio'], $r, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td></tr>';
        echo '</table>';
        echo '<p><button type="button" class="button button-primary" id="aieo-dmm-pv-save">' . esc_html__('Save', 'ai-eshop-optimizer') . '</button>';
        echo ' <span id="aieo-dmm-pv-status" style="margin-left:10px;color:#646970;font-size:13px;"></span></p>';
        echo '</form>';
        echo '<script>(function(){var f=document.getElementById("aieo-dmm-pv-form");var b=document.getElementById("aieo-dmm-pv-save");var s=document.getElementById("aieo-dmm-pv-status");if(!b)return;b.addEventListener("click",function(){var fd=new FormData(f);fd.set("action","aieo_dmm_product_video_save");fd.set("nonce","' . esc_js($nonce) . '");s.style.color="#646970";s.textContent="' . esc_js(__('Saving…', 'ai-eshop-optimizer')) . '";fetch("' . esc_js($ajax) . '",{method:"POST",credentials:"same-origin",body:fd}).then(function(r){return r.json();}).then(function(j){if(j&&j.success){s.style.color="#15803d";s.textContent=j.data.message;}else{s.style.color="#b91c1c";s.textContent=(j&&j.data&&j.data.message)||"' . esc_js(__('Save failed.', 'ai-eshop-optimizer')) . '";}});});})();</script>';
        echo '</div>';
    }
}
