<?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');
    }
}


// ==============================================================================
// 2. Privremeni REST Endpoint za popunjavanje istorije (May 12 - Danas)
// ==============================================================================

add_action('rest_api_init', function () {
    register_rest_route('kaz/v1', '/fill-history', array(
        'methods' => 'GET',
        'callback' => 'kaz_fill_history_endpoint',
        'permission_callback' => '__return_true',
    ));
});

function kaz_fill_history_endpoint() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'kaz_price_history';

    $messages = [];

    // --- DEO 1: Generisanje 6 meseci istorije (Novembar - Maj) ---
    $start_date_6m = new DateTime('2025-11-20');
    $end_date_6m = new DateTime('2026-05-12'); // Do 11. maja
    $period_6m = new DatePeriod($start_date_6m, new DateInterval('P1D'), $end_date_6m);

    $inserted_6m = 0;
    $current_price_6m = 18500.00; // Početna cena za novembar

    foreach ($period_6m as $dt) {
        $date_str = $dt->format('Y-m-d');
        
        $result = $wpdb->query($wpdb->prepare("
            INSERT IGNORE INTO $table_name (date, weight_category, price)
            VALUES (%s, %s, %f)
        ", $date_str, '1g', $current_price_6m));

        if ($result) {
            $inserted_6m++;
        }

        // Fluktuacija od -1.0% do +1.3% za taj period
        $random_percent = mt_rand(-100, 130) / 100.0; 
        $current_price_6m = $current_price_6m * (1 + ($random_percent / 100.0));
    }
    $messages[] = "Uneseno $inserted_6m dana za 6-mesečni period.";

    // --- DEO 2: Ispravka loših podataka (10,000 RSD) od 12. maja do danas ---
    $start_date_fix = new DateTime('2026-05-12');
    $end_date_fix = new DateTime(); // Danas
    $period_fix = new DatePeriod($start_date_fix, new DateInterval('P1D'), $end_date_fix);

    $updated_fix = 0;
    // Oslanjamo se na današnju realnu cenu, pa stavljamo vrednosti blizu 18450
    $current_price_fix = 18450.00; 

    foreach ($period_fix as $dt) {
        $date_str = $dt->format('Y-m-d');
        
        $result = $wpdb->query($wpdb->prepare("
            UPDATE $table_name 
            SET price = %f 
            WHERE date = %s AND weight_category = '1g'
        ", $current_price_fix, $date_str));

        if ($result !== false) {
            $updated_fix++;
        }

        // Veoma blaga fluktuacija oko nule da se ravno uklopi u danas
        $random_percent = mt_rand(-50, 80) / 1000.0; 
        $current_price_fix = $current_price_fix * (1 + ($random_percent / 100.0));
    }
    $messages[] = "Ispravljeno $updated_fix dana od 12. maja gde je cena bila pala na 10000.";

    return rest_ensure_response([
        'status' => 'success',
        'message' => implode(' | ', $messages),
    ]);
}
