<?php

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

require_once __DIR__ . "/../Kernel/API/Entity/DigitalSignage4_DemandeEntity.php";
require_once __DIR__ . "/../Kernel/API/Manager/DigitalSignage4_DemandeManager.php";
require_once __DIR__ . "/../Kernel/API/Manager/DigitalSignage4_Exception.php";
require_once __DIR__ . "/../Kernel/API/Manager/DigitalSignage4_PlaylistManager.php";
//require_once __DIR__  ."/../controllers/DigitalSignage4_VideoController.php";

class DigitalSignage4_FrontShortcodeVideoDisplayer
{
    private $current_video_source = null;
    private $asset_rel = '../assets/DS4-tmp.jpg';

    public function __construct()
    {
        //recup token
        $wp = new DigitalSignage4_caller();
        $token = $wp->get_data(DigitalSignage4_caller::FORFAIT);
        if ($token)
        {
            DigitalSignage4_ForfaitManager::instance()->setForfait($token);
        }
        $forfait = DigitalSignage4_ForfaitManager::instance()->getForfait(DigitalSignage4_ForfaitManager::instance()->getToken(),true);
        if (!$forfait) {
            //on ne fait rien
        }
        else
        {
            if ($forfait->isExpired())
            {
                $videocontroller = new DigitalSignage4_VideoController();
                $videocontroller->deleteDirectory(__DIR__ . "/../Videos/");
            }
            else
            {
                add_filter('woocommerce_short_description', array($this, 'ProductPlacement12'));
                add_filter('the_content', array($this, 'ProductPlacement34'));
                add_action( 'woocommerce_after_single_product_summary', array($this,'ProductPlacement_en_dessous_thumbnail'), 6 );
                // emplacement 1
                add_action('parse_request', [$this, 'capture_product_from_slug'], 1);
                add_action('wp_enqueue_scripts', [$this,'enqueue_product_js'], PHP_INT_MAX);
                add_action('wp_footer', [$this,'add_hidden_block'], PHP_INT_MAX);


                add_shortcode('ProductVideoGenerator', array($this, 'shortcode_video'));
                add_shortcode('ProductVideoGenerator_playlist', array($this, 'shortcode_playlist'));
            }

        }
    }

    public function capture_product_from_slug($wp) {
        if (is_admin() || wp_doing_ajax() || wp_doing_cron()) return $wp;
        if (empty($wp->query_vars['product'])) return $wp;

        if (!$this->checkPlacementActive('placement_6')) {
            return $wp;
        }

        $slug = sanitize_title($wp->query_vars['product']);
        $post = get_page_by_path($slug, OBJECT, 'product');
        if (!$post instanceof WP_Post) return $wp;
        $product_id = (int)$post->ID;

        if (!$this->productHaveVideo($product_id)) {
            return $wp;
        }

        // Chemin source
        $src = realpath(plugin_dir_path(__FILE__) . $this->asset_rel);
        if (!$src || !file_exists($src)) return $wp;

        // Snapshot AVANT modifs
        $prev_thumb_id = (int) get_post_thumbnail_id($product_id);
        $prev_gallery  = (string) get_post_meta($product_id, '_product_image_gallery', true);

        // Copier/attacher l'image
        $uploads = wp_upload_dir();
        if (!empty($uploads['error'])) return $wp;
        wp_mkdir_p($uploads['path']);

        $dest_filename = wp_unique_filename($uploads['path'], basename($src));
        $dest_path     = trailingslashit($uploads['path']) . $dest_filename;
        if (!file_exists($dest_path)) {
            if (!@copy($src, $dest_path)) return $wp;
        }
        $filetype = wp_check_filetype($dest_filename, null);
        if (empty($filetype['type'])) return $wp;

        $relative_file = ltrim(str_replace(trailingslashit($uploads['basedir']), '', $dest_path), '/');
        $attached_id   = $this->find_attachment_by_file($relative_file);
        $created_now   = false;

        if (!$attached_id) {
            $attachment = [
                'post_mime_type' => $filetype['type'],
                'post_title'     => 'DS4-tmp-cover',
                'post_content'   => '',
                'post_status'    => 'inherit',
                'guid'           => trailingslashit($uploads['url']) . $dest_filename,
            ];
            $attached_id = wp_insert_attachment($attachment, $dest_path, $product_id);
            if (is_wp_error($attached_id) || !$attached_id) return $wp;

            require_once ABSPATH . 'wp-admin/includes/image.php';
            $meta = wp_generate_attachment_metadata($attached_id, $dest_path);
            if ($meta) wp_update_attachment_metadata($attached_id, $meta);
            update_post_meta($attached_id, '_wp_attached_file', $relative_file);
            $created_now = true;
        }

        // Mettre en cover
        if (function_exists('set_post_thumbnail')) {
            set_post_thumbnail($product_id, $attached_id);
        } else {
            update_post_meta($product_id, '_thumbnail_id', $attached_id);
        }

        // Prepend dans la galerie
        /*
         * Cela met en double la vidéo
        $ids = array_filter(array_map('absint', explode(',', (string) get_post_meta($product_id, '_product_image_gallery', true))));
        if (!in_array($attached_id, $ids, true)) {
            array_unshift($ids, $attached_id);
        } else {
            // Le passer devant s'il n'est pas premier
            $ids = array_values(array_unique(array_merge([$attached_id], array_diff($ids, [$attached_id]))));
        }
        update_post_meta($product_id, '_product_image_gallery', implode(',', $ids));
        */

        // ---------- Nettoyage en TOUTE FIN (sans hook WP) ----------
        register_shutdown_function([__CLASS__, 'late_cleanup'],
            $product_id, $prev_thumb_id, $prev_gallery, $attached_id, $created_now
        );

        return $wp;
    }

    public static function late_cleanup($product_id, $prev_thumb_id, $prev_gallery, $attached_id, $created_now) {
        // Restaurer la cover précédente
        if ($prev_thumb_id > 0) {
            if (function_exists('set_post_thumbnail')) {
                set_post_thumbnail($product_id, $prev_thumb_id);
            } else {
                update_post_meta($product_id, '_thumbnail_id', $prev_thumb_id);
            }
        } else {
            delete_post_meta($product_id, '_thumbnail_id');
        }

        // Restaurer exactement l'ancienne galerie (même ordre)
        if ($prev_gallery !== '') {
            update_post_meta($product_id, '_product_image_gallery', $prev_gallery);
        } else {
            delete_post_meta($product_id, '_product_image_gallery');
        }

        // Optionnel : si on a créé l’attachment spécialement, on le supprime (fichier + DB)
        if ($created_now && $attached_id > 0) {
            // Sécurité : ne pas supprimer si par hasard c'était déjà la cover avant
            if ($prev_thumb_id !== $attached_id) {
                wp_delete_attachment($attached_id, true);
            }
        }
    }

    private function find_attachment_by_file(string $relative_file) {
        $q = new WP_Query([
            'post_type'      => 'attachment',
            'post_status'    => 'inherit',
            'posts_per_page' => 1,
            'fields'         => 'ids',
            'meta_query'     => [[
                'key'   => '_wp_attached_file',
                'value' => $relative_file,
            ]],
            'no_found_rows'  => true,
        ]);
        return !empty($q->posts[0]) ? (int)$q->posts[0] : 0;
    }

    public static function init()
    {
        new DigitalSignage4_FrontShortcodeVideoDisplayer();
    }


    // Ajout du block video caché
    public function add_hidden_block()
    {
        if (function_exists('is_product') && is_product()) {
            global $wp;
            if (empty($wp->query_vars['product'])) return;

            preg_match("/<source[^>]*\s+src=['\"]([^'\"]+)['\"]/", $this->shortcode_video(array(), true), $matches);
            $this->current_video_source = $matches[1] ?? null;

            if ($this->current_video_source != null) {
                echo '<div class="DS4-product-player-block" style="max-height:50px;max-width:50px;position: absolute;top:-5000px;left:-5000px;">
    <video style="position:relative;top:0;left:50%;transform:translateX(-50%);max-width:100%;max-height:100%;width:100%;aspect-ratio:16/9;" controls muted="muted" preload="auto" loop autoplay>
        <source src="' . $this->current_video_source . '" type="video/mp4">
    </video>
</div>';
            }

            global $product;
            if (!$product || !is_a($product, 'WC_Product')) {
                $product = wc_get_product(get_the_ID());
            }
            if ($product) {
                $gallery_image_ids = $product->get_gallery_image_ids();
                if (!empty($gallery_image_ids)) {
                    $first_image_id = $gallery_image_ids[0];
                    $image_path = get_attached_file($first_image_id);
                    if ($image_path) {
                        $image_info = pathinfo($image_path);
                        echo '<script> ds4_first_image = "'.$image_info['filename'].'"; </script>';
                    }
                }
            }
        }
    }

    // Ajout du js
    public function enqueue_product_js()
    {
        if (is_product()) {
                wp_enqueue_script(
                    'ds4-product-script',
                    plugin_dir_url(__FILE__) . '../assets/digitalsignage4.js',
                    array(),
                    '1.0.0',
                    true
                );

            // Ajout du filtre pour ajouter "defer"
            add_filter('script_loader_tag', function ($tag, $handle, $src) {
                if ('ds4-product-script' === $handle) {
                    return '<script src="' . esc_url($src) . '" defer></script>';
                }
                return $tag;
            }, 10, 3);

        }
    }

    public function ProductPlacement_en_dessous_thumbnail($src) {

        $finalHtml = "";

        if ($this->checkPlacementActive('placement_5')) {
            $finalHtml .= $this->shortcode_video(array('no_decalage' => true));
        }

        $allowed_html = array(
            'object' => array(
                'type' => array(),
                'style' => array(),
                'data' => array(),
            ),
            'video' => array(
                'controls' => array(),
                'width' => array(),
                'height' => array(),
                'preload' => array(),
                'loop' => array(),
                'muted' => array(),
                'style' => array(),
                'class' => array(),
                'autoplay' => array(),
            ),
            'source' => array(
                'src' => array(),
                'type' => array(),
            ),

        );
        echo wp_kses($finalHtml, $allowed_html);
    }

    public function ProductPlacement12($shortDescriptionContent)
    {
        $finalHtml = "";

        /*if ($this->checkPlacementActive('placement_1')) {
            $finalHtml .= $this->shortcode_video(array('no_decalage' => true));
        }

        $finalHtml .= '<p>' . $shortDescriptionContent . '<p>';*/

        if ($this->checkPlacementActive('placement_2')) {
            $finalHtml .= $this->shortcode_video(array('no_decalage' => true));
        }

        return ($finalHtml);
    }

    public function ProductPlacement34($descriptionContent)
    {
        $finalHtml = "";

        if ($this->checkPlacementActive('placement_3')) {
            $finalHtml .= $this->shortcode_video(array('no_decalage' => true));
        }

        $finalHtml .= '<p>' . $descriptionContent . '<p>';

        if ($this->checkPlacementActive('placement_4')) {
            $finalHtml .= $this->shortcode_video(array('no_decalage' => true));
        }
        return ($finalHtml);
    }


    private function checkPlacementActive($placement)
    {
        $wp = new DigitalSignage4_caller();
        if ($datas = $wp->get_data(DigitalSignage4_caller::PLACEMENT)) {
            if (array_key_exists($placement, $datas) && $datas[$placement] == 'on') {
                return true;
            }
        }

        return false;
    }


    public function shortcode_video($params, $onlySource = false)
    {
        global $product;

        $retour='';

        $video = $this->getVideoForShortcode(($product) ? $product->get_id() : null, (isset($params['id'])) ? $params['id'] : null);
        if ($video && $video->getVideoUrl()) {
            $extra = (in_array('noLoop', $params)) ? '0' : '1';

            $no_decalage = (in_array('no_decalage', $params)) ? true : false;

            if ($onlySource) {
                $retour= ($video->getVideoPlayer($params['width'], $params['height'], $extra, '1',$no_decalage));
            } else {
                $retour= ($video->getVideoPlayer('max-width: 600px;width: 600px', 'max-height:500px;height: 500px', $extra, '1',$no_decalage));
            }
        }
        return $retour;
    }

    private function getVideoForShortcode($id_product, $id_video = null)
    {
        if ($id_video) {
            return $this->getVideoFromIdDemande($id_video);
        } else {
            if ($id_product) {
                try {
                    $idVideo = DigitalSignage4_DisplayedVideoProduct::getDisplayedVideoProduct($id_product);
                    return $this->getVideoFromIdDemande($idVideo);
                } catch (Exception $e) {
                    return $this->getVideoLastFromProduct($id_product);
                }
            }
        }
        return false;
    }

    private function getVideoLastFromProduct($id_product)
    {
        $demandeManager = new DigitalSignage4_DemandeManager(DigitalSignage4_caller::getInstance());
        $sql="SELECT * FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `product_id` = %d";
        global $wpdb;
        $sql=$wpdb->prepare($sql,$id_product);
        $videoL = $demandeManager->getLocalDemandes($sql);
        if (isset($videoL[0]) && $videoL[0] instanceof DigitalSignage4_DemandeEntity) {
            return $videoL[0];
        }
        return false;
    }

    private function getVideoFromIdDemande($id_video)
    {
        $demandeManager = new DigitalSignage4_DemandeManager(DigitalSignage4_caller::getInstance());
        global $wpdb;
        $sql="SELECT * FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `id_demande` = %d";
        $sql=$wpdb->prepare($sql,$id_video);
        $videoL = $demandeManager->getLocalDemandes($sql);
        if (isset($videoL[0]) && $videoL[0] instanceof DigitalSignage4_DemandeEntity) {
            return $videoL[0];
        }
        return false;
    }

    public function shortcode_playlist($params)
    {
        if (isset($params['id'])) {
            $playlist = DigitalSignage4_PlaylistManager::set(DigitalSignage4_caller::getInstance())->get_playlist($params['id']);
            if ($playlist && $playlist->get_active() && $videos = $playlist->get_videos()) {

                $videos = array_slice($videos, 0, $playlist->get_limit());

                $videosMp4 = array_map(function ($id) {
                    $sql="SELECT * FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `id_demande` = %d";
                    global $wpdb;
                    $sql=$wpdb->prepare($sql,$id);

                    $localDemandes = DigitalSignage4_DemandeManager::set(DigitalSignage4_caller::getInstance())->getLocalDemandes($sql);
                    $localDemande = $localDemandes[0];

                    return $localDemande->getVideoUrl();
                }, $videos);

                $random = rand(0, 100000);

                if ($videos) {
                    $baliseHtmlVideo = ('<video  playlist="' . $params['id'] . '" style="max-width: 600px;max-height:600px;" class="" preload="auto" autoplay="autoplay"  muted="muted" width="600" onended="DigitalSignage4_onVideoEnded(' . $params['id'] . ');">
				                        <source id="' . $random . '_mp4" src="" type="video/mp4">
				                        <!--source id="' . $random . '_ogv" src="" type="video/ogg"-->
				                    </video>');

                    $allowed_html = array(
                        'video' => array(
                            'controls' => array(),
                            'onend' => array(),
                            'playlist' => array(),
                            'width' => array(),
                            'height' => array(),
                            'preload' => array(),
                            'loop' => array(),
                            'muted' => array(),
                            'style' => array(),
                            'class' => array(),
                            'autoplay' => array(),
                        ),
                        'source' => array(
                            'id' => array(),
                            'src' => array(),
                            'type' => array(),
                        ),
                    );

                    return wp_kses($baliseHtmlVideo, $allowed_html);
                }
            }
        }
        return "";
    }

    private function productHaveVideo($in_id_product=null)
    {
        try {
            if(is_null($in_id_product)) {
                global $product;
                $id_product = $product->get_id();
            } else {
                $id_product = $in_id_product;
            }
            $sql="SELECT * FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `product_id` = %d";
            global $wpdb;
            $sql=$wpdb->prepare($sql,$id_product);

            $videoL = DigitalSignage4_DemandeManager::set(DigitalSignage4_caller::getInstance())->getLocalDemandes($sql);

            return !empty($videoL);
        } catch (DigitalSignage4_Exception $e) {
            return false;
        }
    }
}
