<?php

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

require_once __DIR__ ."/../../Classes/DigitalSignage4_Tools.php";
require_once __DIR__ ."/../../Classes/DigitalSignage4_caller.php";
require_once __DIR__ ."/../../controllers/DigitalSignage4_Controller.php";
require_once __DIR__ ."/../../controllers/override/DigitalSignage4_UpdateVideoHandlerManager.php";
require_once __DIR__ ."/../../Kernel/API/Manager/DigitalSignage4_DemandeManager.php";
require_once __DIR__ ."/../../Kernel/API/Manager/DigitalSignage4_ForfaitManager.php";
require_once __DIR__ ."/../../Kernel/API/Manager/DigitalSignage4_GabaritManager.php";
require_once __DIR__ ."/../../controllers/DigitalSignage4_VideoController.php";

class DigitalSignage4_wooCommerceProductOverride extends DigitalSignage4_Controller
{
    private $params = array();
    private $idVideo = -1;
    private $article = null;

    private $productDatas = array();
    private $productId = "";
    private $productImgs = array();

    /**
     * @param WC_Product $article
     */
    public function setArticle($article)
    {
        $productTemp = new WC_Product($article->get_id());
        $this->article = $article;
        $this->productDatas = $productTemp->get_data();
        $this->productDatas['permalink'] = $productTemp->get_permalink();


        $terms =  get_the_terms($article->get_id(), 'product_cat');
        if ($terms && ! is_wp_error($terms)) {
            $this->productDatas['first_category'] = $terms[0]->name;
        } else {
            $this->productDatas['first_category'] = "";
        }

        $this->productDatas['pourcent_reduc'] ="";
        if ($this->productDatas['regular_price'] ==$this->productDatas['price']) {
            $this->productDatas['pourcent_reduc'] ="0%";
        } else {
            if ($this->productDatas['regular_price'] >0) {
                //$this->productDatas['pourcent_reduc'] = "-".round(($this->productDatas['price'] * 100) / $this->productDatas['regular_price'])."%";
                //leNombre =   ABS (( (prix_initial MOINS prix_remisé) / Prix_de_départ ) x 100)
                $reduc_ =  ((($this->productDatas['regular_price'] - $this->productDatas['price']) / $this->productDatas['regular_price']) * 100);
                if ($this->productDatas['regular_price'] > $this->productDatas['price']) {
                    $this->productDatas['pourcent_reduc'] = "-".abs(round($reduc_))."%";
                } else {
                    $this->productDatas['pourcent_reduc'] = "+".abs(round($reduc_))."%";
                }
            }
        }

        $this->productId = $productTemp->get_id();
        $this->productImgs = $this->getImages($this->productId);
    }

    public function generatePage()
    {
        if (!$this->article) {
            return false;
        }
	
		
		

        $gabarits = DigitalSignage4_GabaritManager::instance()->getGabarits();

        foreach ($gabarits as $gabarit_) {
            $gabarit_->initCustomChamp();
        }



        $this->assign(array(
            'product' => $this->productDatas,
            'product_img' => $this->productImgs,
            //'urlSpecialData' => DigitalSignage4_Tools::getModuleUrl()."Classes/DigitalSignage4_CreationVideoSpecialDataProviderAjaxHandler.php?digitalSignageSpecialData=",
            'urlSpecialData' => admin_url( 'admin-ajax.php' ),
            'urlAjax' => admin_url( 'admin-ajax.php' ),
            'urlChangeDisplayedVideo' =>  DigitalSignage4_Tools::getModuleUrl()."Classes/DigitalSignage4_DisplayedVideoProduct.php",
            'urlLoadingImg' => DigitalSignage4_Tools::getModuleUrl()."Kernel/Views/img/loadingChamp.gif",
            'gabarits' => $gabarits,
            'urlTraitement' => plugin_dir_url(__FILE__).'DigitalSignage4_AddVideoHandler.php',
            'urlVideos' => 'admin.php?page=DigitalSignageVideos',
            'videoPath' => DigitalSignage4_Tools::getModuleVideoUrl(),
            'updateController' => plugin_dir_url(__FILE__).'DigitalSignage4_UpdateVideoHandler.php',
            'user_connected' => DigitalSignage4_ForfaitManager::instance()->getToken() !== null,
            'currentHistoriqueHtml' => $this->getHistoriqueHtml(),
            //'NbrActiveVideo'		  => DigitalSignage4_ForfaitManager::instance()->getForfait()->getActiveVideos() - (new DigitalSignage4_VideoController())->getNbrVideosActives(),
            'NbrActiveVideo'		  => 0,
            //'form_nonce' => wp_nonce_field( 'ds4_form_nonce' ),
            'ajax_nonce' => wp_create_nonce( 'ds4_ajax_nonce' ),
        ));

        $this->setWPTemplate("../hook/front/adminProductCreateVideoForm");

        return true;
    }

    public function getHistoriqueHtml()
    {
        $contentHtml = "";
		$sql="SELECT * FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `product_id` = %d";
		global $wpdb;
		$sql=$wpdb->prepare($sql,$this->productId);
			
        try {
            $videoForThisProduct = DigitalSignage4_DemandeManager::set(DigitalSignage4_caller::getInstance())->getLocalDemandes($sql);
        } catch (\Exception $e) {
            $videoForThisProduct = array();
        }

        foreach ($videoForThisProduct as $video) {
            $videoHistoriqueManager = new DigitalSignage4_UpdateVideoHandlerManager(true, $video->getIdDemande(), $video->getProductId());
            $contentHtml = $contentHtml . $videoHistoriqueManager->getHtmlDatas();
        }

        return $contentHtml;
    }

    public function getImages($id_product)
    {
        $images = array();
        $miniature = wp_get_attachment_image_src(get_post_thumbnail_id($id_product), 'single-post-thumbnail');
        if ($miniature === false) {
            return $images;
        }
        array_push($images, $miniature[0]);
        $attachment_ids = $this->article->get_gallery_image_ids();
        array_map(
            function ($di_image) use (&$images) {
                array_push($images, wp_get_attachment_url($di_image));
            },
            $attachment_ids
        );

        return array_map(
            function ($image) {
                $uploads = wp_upload_dir();
                $file_path = str_replace($uploads['baseurl'], $uploads['basedir'], $image);
                
                return array(
                    "url" => $image,
                    "path" => $file_path
                );
            },
            $images
        );
    }
}
