<?php
/**
 * Enqueues all JavaScript files for the Boxyfy plugin.
 *
 * @package Boxyfy
 */

// Sicherheitscheck: Direkten Zugriff auf die Datei verhindern.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Backend/Admin scripts – only for heatmap management in the admin area
 */
if ( function_exists( 'boxyfy_enqueue_heatmap_admin_scripts' ) ) {
	add_action( 'admin_enqueue_scripts', 'boxyfy_enqueue_heatmap_admin_scripts' );
}

function boxyfy_enqueue_heatmap_admin_scripts( $hook ) {
	if ( 'boxyfy_tsprodukte_page_boxyfy_heatmap' !== $hook ) {
		return;
	}

	wp_enqueue_script(
		'boxyfy-heatmap-lib-admin',
		plugin_dir_url( BOXYFY_PLUGIN_FILE ) . 'assets/js/hm.min.js',
		[],
		'2.0.5',
		true
	);

	wp_enqueue_script(
		'boxyfy-heatmap-admin',
		plugin_dir_url( BOXYFY_PLUGIN_FILE ) . 'assets/js/heatmap-admin.js',
		[ 'jquery', 'boxyfy-heatmap-lib-admin' ],
		'1.1',
		true
	);

	$current_radius = (int) get_option( 'boxyfy_heatmap_radius', 50 );
	$current_gradient = get_option(
		'boxyfy_heatmap_gradient',
		wp_json_encode([
			"0.45" => "blue",
			"0.55" => "lime",
			"0.65" => "yellow",
			"0.95" => "red"
		])
	);
	$grad_array = json_decode( $current_gradient, true );

	wp_localize_script(
		'boxyfy-heatmap-admin',
		'boxyfyHeatmapData',
		[
			'ajax_url'       => admin_url( 'admin-ajax.php' ),
			'nonce_view'     => wp_create_nonce( 'boxyfy_heatmap_nonce' ),
			'nonce_delete'   => wp_create_nonce( 'boxyfy_heatmap_admin_nonce' ),
			'current_radius' => $current_radius,
			'grad_array'     => $grad_array,
		]
	);
}

/**
 * Frontend scripts – for click tracking on boxyfy_tsprodukte pages
 */
add_action( 'wp_enqueue_scripts', 'boxyfy_enqueue_frontend_heatmap_scripts' );
function boxyfy_enqueue_frontend_heatmap_scripts() {
	if ( is_singular( 'boxyfy_tsprodukte' ) ) {
		wp_enqueue_script(
			'boxyfy-heatmap-lib',
			plugin_dir_url( BOXYFY_PLUGIN_FILE ) . 'assets/js/hm.min.js',
			[],
			'2.0.5',
			true
		);

		wp_enqueue_script(
			'boxyfy-heatmap-frontend',
			plugin_dir_url( BOXYFY_PLUGIN_FILE ) . 'assets/js/heatmap-frontend.js',
			[ 'jquery', 'boxyfy-heatmap-lib' ],
			'1.0',
			true
		);

		wp_localize_script(
			'boxyfy-heatmap-frontend',
			'boxyfy_heatmap_obj',
			[
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'boxyfy_heatmap_nonce' ),
				'post_id'  => get_the_ID(),
			]
		);
	}
}

/**
 * Enqueues the locally hosted Google Charts library for single product pages.
 */
function boxyfy_enqueue_preistracker_and_google_charts() {
    if ( is_singular( 'boxyfy_tsprodukte' ) ) {
        // Google Charts laden
        wp_enqueue_script(
            'google-charts',
            plugins_url( 'assets/vendor/google/google-charts-loader.js', BOXYFY_PLUGIN_FILE ),
            array(),
            '1.0.0',
            true
        );
        // Nur das "load", nicht der Callback!
        wp_add_inline_script(
            'google-charts',
            "google.charts.load('current', {packages:['corechart']});"
        );

        // Preistracker Script nach google-charts
        wp_enqueue_script(
            'preistracker-single',
            plugins_url( 'assets/js/preistracker-single.js', BOXYFY_PLUGIN_FILE ),
            array( 'jquery', 'google-charts' ),
            '1.0.0',
            true
        );
    }
}
add_action( 'wp_enqueue_scripts', 'boxyfy_enqueue_preistracker_and_google_charts' );

/**
 * Enqueue metabox JS for additional images.
 *
 * @param string $hook The current admin hook.
 */
function boxyfy_add_images_metabox_enqueue_scripts( $hook ) {
	global $post;
	// Only load on edit/new pages for the "boxyfy_tsprodukte" post type.
	if ( ( 'post.php' === $hook || 'post-new.php' === $hook ) && isset( $post ) && 'boxyfy_tsprodukte' === $post->post_type ) {
		// Enqueue Media Library scripts.
		wp_enqueue_media();
		wp_enqueue_script(
			'ts-metabox-weitere-bilder-js',
			plugins_url( 'assets/js/metabox_weitere_bilder.js', BOXYFY_PLUGIN_FILE ),
			array( 'jquery' ),
			'1.0.0',
			true
		);
	}
}
add_action( 'admin_enqueue_scripts', 'boxyfy_add_images_metabox_enqueue_scripts' );

/**
 * Enqueue JS for the "Vor- und Nachteile anlegen" metabox.
 *
 * @param string $hook The current admin page hook.
 */
function boxyfy_vor_nachteile_admin_assets_js( $hook ) {
    global $post;

    // Only load on edit/new pages for the "boxyfy_tsprodukte" post type.
    if ( ( 'post.php' === $hook || 'post-new.php' === $hook ) && isset( $post ) && 'boxyfy_tsprodukte' === $post->post_type ) {
        wp_enqueue_script(
            'boxyfy-vorteile-nachteile-js',
            plugins_url( 'assets/js/metabox-vorteile-nachteile.js', BOXYFY_PLUGIN_FILE ),
            array( 'jquery' ),
            '1.0.0',
            true
        );
    }
}
add_action( 'admin_enqueue_scripts', 'boxyfy_vor_nachteile_admin_assets_js' );

/**
 * Enqueue JS for the Amazon product box.
 */
function boxyfy_amazon_product_box_enqueue_scripts() {
	wp_enqueue_script(
		'amazon-product-box-js',
		plugins_url( 'assets/js/amazon-produktbox-simple.js', BOXYFY_PLUGIN_FILE ),
		array(),
		'1.0.0',
		true
	);
}
add_action( 'wp_enqueue_scripts', 'boxyfy_amazon_product_box_enqueue_scripts' );

/**
 * Register Swiper.js and slider script – load only when shortcode is used.
 */
function boxyfy_register_slider_assets() {
    // Swiper.js
    wp_register_script(
        'swiper-js',
        plugins_url( 'assets/vendor/swiper/swiper-bundle.min.js', BOXYFY_PLUGIN_FILE ),
        array(),
        '9.0.0',
        true
    );

    // Boxyfy Slider Init
    wp_register_script(
        'amazon-product-slider-js',
        plugins_url( 'assets/js/amazon-produktbox-slider.js', BOXYFY_PLUGIN_FILE ),
        array( 'swiper-js', 'jquery' ),
        '1.0.0',
        true
    );
}
add_action( 'wp_enqueue_scripts', 'boxyfy_register_slider_assets' );

/**
 * Ensure slider assets are enqueued if the shortcode is used on any page/post.
 */
function boxyfy_maybe_enqueue_slider_assets( $posts ) {
    if ( empty( $posts ) ) {
        return $posts;
    }

    $shortcode_found = false;

    foreach ( $posts as $post ) {
        if ( has_shortcode( $post->post_content, 'boxyfy_amazon_products_slider' ) ) {
            $shortcode_found = true;
            break;
        }
    }

    if ( $shortcode_found ) {
        wp_enqueue_script( 'swiper-js' );
        wp_enqueue_script( 'amazon-product-slider-js' );
    }

    return $posts;
}
add_filter( 'the_posts', 'boxyfy_maybe_enqueue_slider_assets' );

/**
 * Enqueue scripts for the Amazon Bestseller Shortcode
 */
function boxyfy_amazon_bestseller_table2_enqueue_scripts() {

    // Script registrieren
    wp_register_script(
        'amazon-bestseller-table2-js',
        plugins_url( 'assets/js/amazon-bestseller-table2.js', BOXYFY_PLUGIN_FILE ), // Pfad anpassen
        array(),
        '1.0.0',
        true // im Footer laden
    );

    // Pfeil-URLs per Localize übergeben
    wp_localize_script(
        'amazon-bestseller-table2-js',
        'boxyfy_arrowUrls',
        array(
            'down' => plugins_url( 'assets/images/arrow-down2.webp', BOXYFY_PLUGIN_FILE ),
            'up'   => plugins_url( 'assets/images/arrow-top.webp', BOXYFY_PLUGIN_FILE ),
        )
    );

    // Script enqueue
    wp_enqueue_script( 'amazon-bestseller-table2-js' );
}
add_action( 'wp_enqueue_scripts', 'boxyfy_amazon_bestseller_table2_enqueue_scripts' );

/**
 * Enqueue JS for the "Weitere Preise" metabox.
 *
 * @param string $hook The current admin page hook.
 */
function boxyfy_weitere_preise_enqueue_scripts( $hook ) {
	global $post;

	// Only load on edit/new pages for the "boxyfy_tsprodukte" post type.
	if ( ( 'post.php' === $hook || 'post-new.php' === $hook ) && isset( $post ) && 'boxyfy_tsprodukte' === $post->post_type ) {
		// Für den Logo-Uploader brauchen wir die Medien-Skripte
		wp_enqueue_media();

		wp_enqueue_script(
			'boxyfy-metabox-weitere-preise-js',
			plugins_url( 'assets/js/metabox_weitere_preise.js', BOXYFY_PLUGIN_FILE ), // Pfad anpassen
			array( 'jquery' ),
			'1.0.0',
			true
		);
	}
}
add_action( 'admin_enqueue_scripts', 'boxyfy_weitere_preise_enqueue_scripts' );

/**
 * Enqueue admin JS for Autoren-Subpage.
 *
 * @param string $hook Current admin page hook.
 */
function boxyfy_autoren_admin_enqueue_scripts( $hook ) {
	// Sicherer Zugriff auf $_GET['page']
	$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';

	// Nur auf Autoren-Unterseite oder den boxyfy_tsprodukte Edit-Seiten laden
	if (
		'boxyfy_autoren' === $page ||
		'post.php' === $hook ||
		'post-new.php' === $hook
	) {
		wp_enqueue_media(); // Needed for the media uploader
		wp_enqueue_script(
			'boxyfy-autoren-admin-js',
			plugins_url( 'assets/js/autoren-admin.js', BOXYFY_PLUGIN_FILE ),
			array( 'jquery' ),
			'1.0.0',
			true
		);
	}
}
add_action( 'admin_enqueue_scripts', 'boxyfy_autoren_admin_enqueue_scripts' );

/**
 * Enqueue JS for the small Amazon product box.
 */
function boxyfy_amazon_product_box_small_enqueue_scripts() {
    wp_enqueue_script(
        'amazon-produktbox-small-js',
        plugins_url( 'assets/js/amazon-produktbox-small.js', BOXYFY_PLUGIN_FILE ),
        array( 'jquery' ),
        '1.0.0',
        true
    );
}
add_action( 'wp_enqueue_scripts', 'boxyfy_amazon_product_box_small_enqueue_scripts' );

/**
 * Enqueue JS for the Amazon bestseller table (sorting, etc.).
 */
function boxyfy_amazon_bestseller_table_enqueue_scripts() {
    wp_enqueue_script(
        'amazon-bestseller-table-js',
        plugins_url( 'assets/js/amazon-bestseller-table.js', BOXYFY_PLUGIN_FILE ),
        array(),   // z.B. array('jquery') falls Du jQuery brauchst
        '1.0.0',
        true       // Im Footer laden
    );
}
add_action( 'wp_enqueue_scripts', 'boxyfy_amazon_bestseller_table_enqueue_scripts' );

/**
 * Enqueue admin JS for the "Product Labels" metabox.
 *
 * @param string $hook The current admin page hook (e.g., post.php, post-new.php).
 */
function boxyfy_enqueue_produktlabels_metabox_js( $hook ) {
	global $post;
	// Nur auf den Edit-/New-Seiten und nur für den Post-Typ "boxyfy_tsprodukte"
	if ( ( 'post.php' === $hook || 'post-new.php' === $hook ) && isset( $post ) && 'boxyfy_tsprodukte' === $post->post_type ) {
		wp_enqueue_script(
			'boxyfy-metabox-produktlabels-js',
			plugins_url( 'assets/js/metabox-produktlabels.js', BOXYFY_PLUGIN_FILE ),
			array(),
			'1.0.0',
			true
		);
	}
}
add_action( 'admin_enqueue_scripts', 'boxyfy_enqueue_produktlabels_metabox_js' );

/**
 * Enqueue the single-tsprodukt JavaScript.
 */
function boxyfy_enqueue_single_tsprodukt_scripts() {
    if ( is_singular( 'boxyfy_tsprodukte' ) ) {
        wp_enqueue_script(
            'boxyfy-single-tsprodukt-js',
            plugins_url( 'assets/js/single-tsprodukt.js', BOXYFY_PLUGIN_FILE ),
            array( 'jquery' ),
            '1.0.0',
            true
        );
    }
}
add_action( 'wp_enqueue_scripts', 'boxyfy_enqueue_single_tsprodukt_scripts' );

/**
 * Enqueue the single-tsprodukt-price.
 */
function boxyfy_enqueue_singleproduktpreis_js( $hook_suffix ) {
    global $post;

    // Prüfen, ob wir in einem boxyfy_tsprodukte-Post sind
    if ( isset( $post->post_type ) && 'boxyfy_tsprodukte' === $post->post_type ) {
        wp_enqueue_script(
            'boxyfy-singleproduktpreis-js',
            plugins_url( 'assets/js/singleproduktpreis.js', BOXYFY_PLUGIN_FILE ),
            array(), // z.B. array('jquery') falls du jQuery brauchst
            '1.0.0',
            true
        );

        // Hier kommt das Localize anstelle des Inline-Skripts
        // 'ts_amazon_image_nonce' war dein alter Nonce-Wert
        wp_localize_script(
            'boxyfy-singleproduktpreis-js',
            'BoxyfyPreisSettings', // Beliebiger Name
            array(
                'nonce'    => wp_create_nonce( 'boxyfy_amazon_image_nonce' ), // Wichtig: gleiche Nonce wie check_ajax_referer()
                'ajax_url' => admin_url( 'admin-ajax.php' ),
                'post_id'  => $post->ID,
            )
        );
    }
}
add_action( 'admin_enqueue_scripts', 'boxyfy_enqueue_singleproduktpreis_js' );

/**
 * Enqueue JS for the Amazon Image Metabox.
 *
 * Loads the external JavaScript file for the Amazon Image Metabox in the admin area
 * for posts of type boxyfy_TSProdukte.
 *
 * @param string $hook_suffix The current admin page hook suffix.
 */
function boxyfy_enqueue_singleproduktimages_js( $hook_suffix ) {
    $screen = get_current_screen();

    if (
        isset( $screen->post_type )
        && 'boxyfy_tsprodukte' === $screen->post_type
        && 'post' === $screen->base // nur auf der Bearbeitungsseite
    ) {
        wp_enqueue_script(
            'boxyfy-singleproduktimages-js',
            plugins_url( 'assets/js/singleproduktimages.js', BOXYFY_PLUGIN_FILE ),
            array(), // z. B. array('jquery') falls nötig
            '1.0.0',
            true
        );

        global $post;
        if ( is_object( $post ) ) {
            wp_localize_script(
                'boxyfy-singleproduktimages-js',
                'boxyfyAmazonImage',
                array(
                    'nonce'    => wp_create_nonce( 'boxyfy_fetch_amazon_image_nonce' ),
                    'ajax_url' => admin_url( 'admin-ajax.php' ),
                    'post_id'  => $post->ID,
                )
            );
        }
    }
}
add_action( 'admin_enqueue_scripts', 'boxyfy_enqueue_singleproduktimages_js' );

/* =======================================================================
 *  Boxyfy – JS für die Vergleichstabelle (Filter + Pagination …)
 *  Lädt auf Single-TSProdukte **und** überall dort,
 *  wo der Shortcode [boxyfy_produkte_vergleich] verwendet wird
 * =====================================================================*/

/**
 * 1)  Script laden und PHP-Werte an JS übergeben
 */
function boxyfy_enqueue_vergleichstabelle_js() {

	wp_enqueue_script(
		'boxyfy-vergleichstabelle-js',
		plugins_url( 'assets/js/singleproduktvergleichtabellefilter.js', BOXYFY_PLUGIN_FILE ),
		[ 'jquery' ],
		'1.0.0',
		true
	);

	wp_localize_script(
		'boxyfy-vergleichstabelle-js',
		'boxyfy_filter_settings',
		[
			'boxesPerPage' => (int) get_option( 'boxyfy_vergleich_boxes_seitenanzahl', 12 ),
		]
	);
}

/* -----------------------------------------------------------------------
 * 2)  Automatisch auf Single-TSProdukt-Seiten
 * ----------------------------------------------------------------------*/
add_action( 'wp_enqueue_scripts', function () {
	if ( is_singular( 'boxyfy_tsprodukte' ) ) {
		boxyfy_enqueue_vergleichstabelle_js();
	}
}, 20 );

/* -----------------------------------------------------------------------
 * 3)  Zusätzlich bei Shortcode-Verwendung auf beliebigen Seiten/Posts
 * ----------------------------------------------------------------------*/
function boxyfy_maybe_enqueue_vergleichstabelle_js( $posts ) {

	if ( empty( $posts ) ) { return $posts; }

	foreach ( $posts as $post ) {
		if ( has_shortcode( $post->post_content, 'boxyfy_produkte_vergleich' ) ) {
			add_action( 'wp_enqueue_scripts', 'boxyfy_enqueue_vergleichstabelle_js', 20 );
			break;
		}
	}
	return $posts;
}
add_filter( 'the_posts', 'boxyfy_maybe_enqueue_vergleichstabelle_js' );


/**
 * Enqueues the JS für die Backend‑Settings und fügt das JSON‑Objekt inline ein.
 */
function boxyfy_enqueue_backend_setting_pages_js() {
    $handle = 'boxyfy-backend-setting-pages-js';

    // 1) Script enqueuen
    wp_enqueue_script(
        $handle,
        plugins_url( 'assets/js/backend_setting_pages.js', BOXYFY_PLUGIN_FILE ),
        array( 'jquery' ),
        '1.0.0',
        true
    );

    // 2) PHP‑Array mit allen Daten anlegen
    $boxyfy_backend_settings = array(
        // translators: %s ist die Anzahl der Monate
        'deleteConfirmMessage'   => sprintf( __( 'Wirklich alle Einträge, die älter als %s Monat(e) sind, löschen?', 'boxyfy' ), '%s' ),
        'manualUpdateInProgress' => __( 'Neuer Preisabruf läuft …', 'boxyfy' ),
        'manualUpdateComplete'   => __( 'Alle Amazon‑Preise nochmal abrufen und aktualisieren', 'boxyfy' ),
        'ajaxError'              => __( 'Ein Fehler ist aufgetreten.', 'boxyfy' ),
        'updateError'            => __( 'Ein Datenabruf‑Fehler ist aufgetreten.', 'boxyfy' ),
        'deleteDataNonce'        => wp_create_nonce( 'delete_old_data_action' ),
        'manualUpdateNonce'      => wp_create_nonce( 'boxyfy_manual_update_nonce' ),
    );

    // 3) Das Array in JSON verwandeln
    $json = wp_json_encode( $boxyfy_backend_settings );

    // 4) Inline‑Script definieren
    $inline_script = "var backendSettings = {$json};";

    // 5) Vor dem eigentlichen Script einfügen
    wp_add_inline_script( $handle, $inline_script, 'before' );
}
add_action( 'admin_enqueue_scripts', 'boxyfy_enqueue_backend_setting_pages_js' );

/**
 * Enqueue JavaScript for the Product Details Metabox.
 *
 */
function boxyfy_enqueue_metabox_productdetails_script( $hook ) {
	global $post;
	if ( isset( $post ) && 'boxyfy_tsprodukte' === get_post_type( $post ) ) {
		wp_enqueue_script(
			'boxyfy-metabox-productdetails-script',
			plugins_url( 'assets/js/productdetails-metabox.js', BOXYFY_PLUGIN_FILE ),
			array( 'jquery' ),
			'1.0.0',
			true
		);
	}
}
add_action( 'admin_enqueue_scripts', 'boxyfy_enqueue_metabox_productdetails_script' );

/**
 * Enqueue JavaScript for the Single-Produkt-Shortcode (inkl. KI-Chat)
 */
function boxyfy_maybe_enqueue_single_produkt_shortcode_script( $posts ) {
	if ( empty( $posts ) ) { return $posts; }

	foreach ( $posts as $post ) {
		if ( has_shortcode( $post->post_content, 'boxyfy_produktbox' ) ) {
			wp_enqueue_script(
				'boxyfy-single-produkt-shortcode-js',
				plugins_url( 'assets/js/single-produkt-shortcode.js', BOXYFY_PLUGIN_FILE ),
				[ 'jquery' ],
				'1.0.0',
				true
			);
			wp_localize_script( 'boxyfy-single-produkt-shortcode-js', 'boxyfyData', [
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'boxyfy_ai_nonce' ),
			] );
			break;
		}
	}
	return $posts;
}
add_filter( 'the_posts', 'boxyfy_maybe_enqueue_single_produkt_shortcode_script' );