<?php
/*
Arquivo: wp-content/themes/cancao-verdadeira/inc/ranking.php

Resumo:
Este arquivo gerencia o sistema de ranking das músicas.
Calcula o score baseado em views, favoritos e avaliação média.
Também implementa o fator trending (crescimento recente).
Os valores são armazenados no banco para evitar cálculos pesados em tempo real.
Inclui funções para atualizar score automaticamente e buscar rankings.
Preparado para cache e alta performance.
*/

if (!defined('ABSPATH')) {
    exit;
}


/* =========================
   📊 CALCULAR SCORE
========================= */
function cancao_calcular_score($post_id) {

    $views      = intval(get_post_meta($post_id, '_cancao_views', true));
    $favoritos  = intval(get_post_meta($post_id, '_cancao_favoritos', true));
    $rating     = floatval(get_post_meta($post_id, '_cancao_rating', true));

    // Trending (últimos 7 dias - simplificado)
    $views_7dias = intval(get_post_meta($post_id, '_cancao_views_7dias', true));

    $trending = $views_7dias * 0.05;

    // Fórmula final
    $score = ($rating * 2) + ($views * 0.03) + ($favoritos * 1.2) + $trending;

    update_post_meta($post_id, '_cancao_score', $score);

    return $score;
}


/* =========================
   🔄 ATUALIZAR SCORE AUTOMÁTICO
========================= */
function cancao_update_score_on_save($post_id) {

    if (get_post_type($post_id) !== 'musica') {
        return;
    }

    cancao_calcular_score($post_id);
}
add_action('save_post', 'cancao_update_score_on_save');


/* =========================
   🔥 ATUALIZAÇÃO PERIÓDICA (CRON)
========================= */
function cancao_atualizar_todos_scores() {

    $args = [
        'post_type'      => 'musica',
        'posts_per_page' => -1,
        'post_status'    => 'publish'
    ];

    $query = new WP_Query($args);

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            cancao_calcular_score(get_the_ID());
        }
        wp_reset_postdata();
    }
}

// Agenda cron (1x por hora)
if (!wp_next_scheduled('cancao_cron_ranking')) {
    wp_schedule_event(time(), 'hourly', 'cancao_cron_ranking');
}
add_action('cancao_cron_ranking', 'cancao_atualizar_todos_scores');


/* =========================
   🏆 BUSCAR TOP MÚSICAS
========================= */
function cancao_get_top_musicas($limit = 10, $genero = null) {

    $args = [
        'post_type'      => 'musica',
        'posts_per_page' => $limit,
        'meta_key'       => '_cancao_score',
        'orderby'        => 'meta_value_num',
        'order'          => 'DESC'
    ];

    if ($genero) {
        $args['tax_query'] = [
            [
                'taxonomy' => 'genero',
                'field'    => 'slug',
                'terms'    => $genero
            ]
        ];
    }

    return new WP_Query($args);
}


/* =========================
   📈 TRENDING (7 DIAS)
========================= */
function cancao_get_trending($limit = 10) {

    return new WP_Query([
        'post_type'      => 'musica',
        'posts_per_page' => $limit,
        'meta_key'       => '_cancao_views_7dias',
        'orderby'        => 'meta_value_num',
        'order'          => 'DESC'
    ]);
}