<?php

// Include custom functionalities
require_once get_template_directory() . '/inc/image-optimization.php';
require_once get_template_directory() . '/inc/price-history.php';
require_once get_template_directory() . '/inc/live-prices.php';
require_once get_template_directory() . '/inc/svg-helper.php';

function kaz_enqueue_styles()
{
    wp_enqueue_style('kaz-fonts', get_template_directory_uri() . '/assets/fonts/fonts.css', array(), '1.0');
    wp_enqueue_style('kaz-style', get_stylesheet_uri(), array('kaz-fonts'), wp_get_theme()->get('Version'));

    // Enqueue Lenis.js
    wp_enqueue_script('lenis', get_template_directory_uri() . '/assets/js/vendor/lenis.min.js', array(), '1.0.0', true);

    // Enqueue custom scroll.js
    wp_enqueue_script('kaz-scroll', get_template_directory_uri() . '/assets/js/scroll.js', array('lenis'), '1.0.0', true);

    // Enqueue live prices JS
    wp_enqueue_script('kaz-live-prices', get_template_directory_uri() . '/assets/js/live-prices.js', array(), '1.0.0', true);
    wp_localize_script('kaz-live-prices', 'kaz_live_prices_data', array(
        'rest_url' => esc_url_raw(rest_url('kaz/v1/live-prices'))
    ));

    // Enqueue global main.js for responsive navigation
    wp_enqueue_script('kaz-main', get_template_directory_uri() . '/assets/js/main.js', array(), '1.0.0', true);


    // Enqueue Chart.js and custom Price Chart JS (only on the front page)
    if (is_front_page()) {
        wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js', array(), '4.4.0', true);
        wp_enqueue_script('kaz-price-chart', get_template_directory_uri() . '/assets/js/price-chart.js', array('chart-js'), '1.0.0', true);
        wp_localize_script('kaz-price-chart', 'kaz_live_prices_data', array(
            'rest_url' => esc_url_raw(rest_url('kaz/v1/live-prices'))
        ));
    }
}
add_action('wp_enqueue_scripts', 'kaz_enqueue_styles');

// 1. Sakrij tehničke tagove sa same stranice proizvoda (ispod Add to Cart)
add_filter('term_links-product_tag', 'kaz_hide_chart_tags_from_meta');
function kaz_hide_chart_tags_from_meta($links)
{
    $filtered_links = array();
    foreach ($links as $link) {
        // Ako link taga ne sadrži našu tehničku ključnu reč, prikaži ga
        if (strpos($link, 'chart-ref-') === false) {
            $filtered_links[] = $link;
        }
    }
    return $filtered_links;
}

// 2. Sakrij tehničke tagove iz WooCommerce Tag Cloud-a i filtera
add_filter('woocommerce_product_tag_cloud_widget_args', 'kaz_hide_chart_tags_from_widget');
function kaz_hide_chart_tags_from_widget($args)
{
    $hidden_terms = get_terms(array(
        'taxonomy' => 'product_tag',
        'name__like' => 'chart-ref-',
        'fields' => 'ids'
    ));

    if (!empty($hidden_terms) && !is_wp_error($hidden_terms)) {
        $args['exclude'] = $hidden_terms;
    }
    return $args;
}

// 3. REST API Endpoint for Chart Data
add_action('rest_api_init', function () {
    register_rest_route('kaz/v1', '/chart-data', array(
        'methods' => 'GET',
        'callback' => 'kaz_chart_data_endpoint',
        'permission_callback' => '__return_true',
        'args' => array(
            'days' => array(
                'required' => false,
                'default' => 7,
                'sanitize_callback' => 'absint',
            ),
        ),
    ));
});

function kaz_chart_data_endpoint($request) {
    global $wpdb;
    $days = $request->get_param('days');
    
    // Ensure days is a valid number, default to 7 if invalid
    if (!in_array($days, [7, 30, 180])) {
        $days = 7;
    }

    $table_name = $wpdb->prefix . 'kaz_price_history';
    
    // Calculate the start date
    $start_date = date('Y-m-d', strtotime("-$days days"));

    // Fetch data from wp_kaz_price_history
    $query = $wpdb->prepare(
        "SELECT date, price FROM {$table_name} WHERE weight_category = %s AND date >= %s ORDER BY date ASC",
        '1g',
        $start_date
    );

    $results = $wpdb->get_results($query);

    $labels = [];
    $values = [];

    if ($results) {
        foreach ($results as $row) {
            $labels[] = date('d.m.', strtotime($row->date));
            $values[] = (float) $row->price;
        }
    }

    return rest_ensure_response([
        'labels' => $labels,
        'values' => $values,
    ]);
}
