<?php
namespace NCPC;
use NCPC_Product_Config;
use WP_Query;

/**
 * Frontend Pages Handler
 */
class Frontend
{

    public function __construct()
    {
        add_shortcode('ncpc-configurator', [$this, 'display_configurator']);
        add_shortcode('ncpc-proncducts', [$this, 'get_products_display']);
    }



    /**
     * Render frontend app
     *
     * @param  array $atts
     * @param  string $content
     *
     * @return string
     */
    public function display_configurator($atts, $content = '')
    {
        /**styles */
        wp_enqueue_style('ncpc-frontend', NCPC_ASSETS . '/css/frontend.css', array(), NCPC_VERSION, 'all');
        wp_enqueue_style('ncpc-style', NCPC_ASSETS . '/css/style.css', array(), NCPC_VERSION, 'all');
        wp_enqueue_style('ncpc-vendor', NCPC_ASSETS . '/css/vendors.css', array(), NCPC_VERSION, 'all');
        wp_enqueue_style('ncpc-toast-css', NCPC_ASSETS . '/utilities/toast.min.css', false, NCPC_VERSION);
        /* scripts */
        wp_enqueue_script('ncpc-runtime', NCPC_ASSETS . '/js/runtime.js', [], NCPC_VERSION, true);
        wp_enqueue_script('ncpc-vendor', NCPC_ASSETS . '/js/vendors.js', [], NCPC_VERSION, true);
        wp_enqueue_script('ncpc-toast-js', NCPC_ASSETS . '/utilities/toast.min.js', false, NCPC_VERSION, true);
        wp_enqueue_script('ncpc-fabric', NCPC_ASSETS . '/utilities/fabric.js', [], NCPC_VERSION, true);
        wp_enqueue_script('ncpc-opentype', NCPC_ASSETS . '/utilities/opentype.js', [], NCPC_VERSION, true);
        wp_enqueue_script('ncpc-frontend', NCPC_ASSETS . '/js/frontend.js', ['jquery', "wp-api"], NCPC_VERSION, true);


        extract( // phpcs:ignore
            shortcode_atts(
                array(
                    'productid' => '0'
                ),
                $atts,
                'ncpc-proncducts'
            )
        );
        $product = wc_get_product($productid);
        ob_start();
        ?>
                <div id="ncpc-configurator-container">
                    <div id="ncpc-configurator-loader" class="ncpc-loader-wrapper">
                        <div class="ncpc-loader-container">

                            <!-- Gauche : preview -->
                            <div class="ncpc-loader-preview">
                                <div class="ncpc-loader-buttons">
                                    <div class="ncpc-loader-placeholder ncpc-loader-toggle-btn"></div>
                                    <div class="ncpc-loader-placeholder ncpc-loader-toggle-btn"></div>
                                    <div class="ncpc-loader-placeholder ncpc-loader-toggle-btn"></div>
                                    <div class="ncpc-loader-placeholder ncpc-loader-toggle-btn"></div>
                                </div>

                                <div class="ncpc-loader-preview-box">
                                    <div class="ncpc-loader-placeholder ncpc-loader-text-box"></div>
                                </div>
                            </div>

                            <!-- Droite : sidebar form -->
                            <div class="ncpc-loader-sidebar">
                                <div class="ncpc-loader-placeholder ncpc-loader-style-btn"></div>

                                <div class="ncpc-loader-size-grid">
                                    <div class="ncpc-loader-placeholder ncpc-loader-size-btn"></div>
                                    <div class="ncpc-loader-placeholder ncpc-loader-size-btn"></div>
                                    <div class="ncpc-loader-placeholder ncpc-loader-size-btn"></div>
                                    <div class="ncpc-loader-placeholder ncpc-loader-size-btn"></div>
                                </div>

                                <div class="ncpc-loader-placeholder ncpc-loader-button"></div>
                                <div class="ncpc-loader-placeholder ncpc-loader-input"></div>
                            </div>
                        </div>
                    </div>


                    <?php

                    if ($product) {
                        $meta = get_post_meta($productid, 'product-ncpc-metas', true);

                        if (!empty($meta) && isset($meta[$productid]['config-id'])) {
                            $configId = $meta[$productid]['config-id'];
                            if ($configId != 0) {
                                $config = get_post_meta($configId, "ncpc-configs-meta", true);
                                $othersData = get_option("ncpc_global_settings_others_data", []);
                                if (is_array($config) && !empty($config)) {
                                    $config["data"]["others"] = $othersData;

                                    $configData = array(
                                        'id' => $configId,
                                        'title' => get_the_title(),
                                        'productType' => $config["productType"],
                                        'pricingMode' => $config["pricingMode"],
                                        "data" => $config["data"]
                                    );

                                    $product_price = $product->get_price();
                                    $available_variations = array();

                                    if ($product->get_type() === 'variable') {
                                        $available_variations = $product->get_available_variations();
                                    }

                                    $NCPC = array(
                                        'skin' => $config["data"]['settings']['themes']['skin'],
                                        'productID' => $productid,
                                        'product' => $product,
                                        'currentConfig' => $configData,
                                        'regularPrice' => trim($product_price) != '' ? $product_price : 0,
                                        'thousandSep' => wc_get_price_thousand_separator(),
                                        'decimalSep' => wc_get_price_decimal_separator(),
                                        'decimals' => wc_get_price_decimals(),
                                        'nbDecimals' => wc_get_price_decimals(),
                                        'currencySymbol' => html_entity_decode(get_woocommerce_currency_symbol()),
                                        'currency_pos' => get_option('woocommerce_currency_pos'),
                                        'variations' => $available_variations,
                                        "wpApiSettings" => array(
                                            'root' => esc_url_raw(rest_url()), // URL de base de l'API
                                            'nonce' => wp_create_nonce('wp_rest'), // Crée un nonce pour la sécurité
                                            'user' => get_current_user_id() // Optionnel : ID de l'utilisateur actuel
                                        ),
                                    );

                                    $this->includes_config_fonts($config["data"]['requiredOptions']['fontOptions']['fonts']);
                                    if (isset($config["data"]['settings']['themes']['customCSS']) && !empty($config["data"]['settings']['themes']['customCSS'])) {
                                        wp_add_inline_style('ncpc-frontend', $config["data"]['settings']['themes']['customCSS']);
                                    }

                                    wp_localize_script("ncpc-frontend", "ncpcData", $NCPC);
                                    ?>
                                                    <div id='ncpc-frontend-app'></div>
                                                    <?php
                                                    wp_localize_script("ncpc-frontend", "ncpc_ajax", ["ajax_url" => admin_url('admin-ajax.php'), "nonce" => wp_create_nonce('ncpc_add_to_cart_after_custom')]);

                                }
                            }
                        }
                    }
                    ?>
                </div>
                <?php
                $content .= ob_get_clean();
                return $content;
    }

    private function includes_config_fonts($fonts)
    {
        foreach ($fonts as $font) {
            if (!empty($font['url']) && $font['isGoogleFont']) {
                $font_url = str_replace('http://', '//', $font['url']);
                $this->include_config_ttf_font_style($font['label'], $font_url);
            } elseif (!empty($font['url'])) {
                $this->include_config_ttf_font_style($font['label'], $font['url']);
            }
        }
    }

    private function include_config_ttf_font_style($font_label, $url)
    {
        $font_label = str_replace([" ", "_"], "-", $font_label);
        $inline_style = "@font-face {
            font-family: " . esc_html($font_label) . ";
            src: url('" . esc_url($url) . "') format('truetype');
        }";
        wp_add_inline_style('ncpc-frontend', $inline_style);
    }

}
