<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Get historical price for '1g' category from $days_ago
 * 
 * @param int $days_ago Number of days in the past
 * @return string|null Price or null if not found
 */
function kaz_get_historical_price($days_ago)
{
    global $wpdb;

    // Ensure $days_ago is a positive integer
    $days_ago = absint($days_ago);

    // Calculate target date
    $target_date = date('Y-m-d', strtotime("-$days_ago days"));
    $table_name = $wpdb->prefix . 'kaz_price_history';

    $query = $wpdb->prepare("
        SELECT price 
        FROM $table_name 
        WHERE weight_category = '1g' 
        AND date <= %s 
        ORDER BY date DESC 
        LIMIT 1
    ", $target_date);

    $price = $wpdb->get_var($query);

    return $price;
}

// ==============================================================================
// 1. Cron Job: Automatski upis dnevne cene
// ==============================================================================

// Povezivanje WP Cron hook-a sa funkcijom
add_action('kaz_daily_price_record_hook', 'kaz_record_daily_price');

// Funkcija za upis u bazu
function kaz_record_daily_price() {
    global $wpdb;
    
    // Dohvati najnižu cenu za proizvode sa tagom 'chart-ref-1g'
    $args = array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'product_tag' => 'chart-ref-1g',
        'meta_query' => array(
            array(
                'key' => '_stock_status',
                'value' => 'instock',
                'compare' => '='
            )
        )
    );

    $query = new WP_Query($args);
    $lowest_price = null;

    if ($query->have_posts()) {
        foreach ($query->posts as $post) {
            $product = wc_get_product($post->ID);
            if ($product) {
                $price = (float) $product->get_price();
                if ($lowest_price === null || $price < $lowest_price) {
                    $lowest_price = $price;
                }
            }
        }
    }

    if ($lowest_price !== null) {
        // Dinamički prefiks (automatski rešava 'wpx4_' ili bilo koji drugi prefix)
        $table_name = $wpdb->prefix . 'kaz_price_history'; 
        $date = date('Y-m-d');
        
        // Upisujemo cenu za tekući dan. IGNORE sprečava duplikate ako se cron okine više puta dnevno.
        $wpdb->query($wpdb->prepare("
            INSERT IGNORE INTO $table_name (date, weight_category, price)
            VALUES (%s, %s, %f)
        ", $date, '1g', $lowest_price));
    }
}

// Zakazivanje događaja ukoliko već nije zakazan
add_action('wp', 'kaz_setup_daily_price_cron');
function kaz_setup_daily_price_cron() {
    if (!wp_next_scheduled('kaz_daily_price_record_hook')) {
        // Zakaži dnevno izvršavanje
        wp_schedule_event(time(), 'daily', 'kaz_daily_price_record_hook');
    }
}

