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

// =============================================================================
// ENDPOINT AJAX PARA DADOS DO GRÁFICO DO DASHBOARD
// =============================================================================

add_action('wp_ajax_imz_get_dashboard_chart_data', 'imz_get_dashboard_chart_data');
function imz_get_dashboard_chart_data() {
    check_ajax_referer('imz_dashboard_chart_nonce', 'nonce');
    if (!is_user_logged_in()) wp_send_json_error(['message' => 'Não autenticado.']);

    $artist_id = get_current_user_id();
    $period = sanitize_key($_POST['period'] ?? '7days');
    
    global $wpdb;
    $analytics_table = $wpdb->prefix . 'imz_analytics';

    // O catálogo oficial vem do Art Track ligado à conta.
    $track_id = function_exists( 'rmbz_artists_get_art_track_for_user' ) ? absint( rmbz_artists_get_art_track_for_user( $artist_id ) ) : 0;
    $music_ids = $track_id && function_exists( 'rmbz_art_track_music_ids' ) ? array_map( 'absint', rmbz_art_track_music_ids( $track_id ) ) : [];
    if (empty($music_ids)) {
        wp_send_json_success(['labels' => [], 'downloads' => [], 'boosts' => [], 'plays' => []]);
        return;
    }

    $days = $period === '30days' ? 30 : 7;
    $ids_placeholder = implode(',', array_fill(0, count($music_ids), '%d'));

    // Downloads por dia
    $downloads_query = "SELECT DATE(download_date) as day, COUNT(*) as total 
                        FROM $analytics_table 
                        WHERE music_id IN ($ids_placeholder) 
                        AND download_date >= DATE_SUB(CURDATE(), INTERVAL %d DAY)
                        GROUP BY DATE(download_date) 
                        ORDER BY day ASC";
    
    $params = array_merge($music_ids, [$days]);
    $downloads_results = $wpdb->get_results($wpdb->prepare($downloads_query, $params));

    // Reproduções (plays) por dia — tabela wp_imz_plays
    $plays_results = [];
    $plays_table = $wpdb->prefix . 'imz_plays';
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $plays_table)) === $plays_table) {
        $plays_query = "SELECT DATE(play_date) as day, COUNT(*) as total
                        FROM $plays_table
                        WHERE music_id IN ($ids_placeholder)
                        AND play_date >= DATE_SUB(CURDATE(), INTERVAL %d DAY)
                        GROUP BY DATE(play_date)
                        ORDER BY day ASC";
        $plays_results = $wpdb->get_results($wpdb->prepare($plays_query, $params));
    }

    // Impulsionamentos por dia
    $boost_days_data = [];
    $boosts_query = new WP_Query([
        'post_type'      => 'impulsionamento',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'meta_query'     => [
            ['key' => 'post_id_original', 'value' => $music_ids, 'compare' => 'IN'],
            ['key' => 'status', 'value' => 'aprovado'],
        ],
        'date_query'     => [['after' => $days . ' days ago', 'inclusive' => true]],
    ]);

    if ($boosts_query->have_posts()) {
        while ($boosts_query->have_posts()) {
            $boosts_query->the_post();
            $day = get_the_date('Y-m-d');
            $boost_days_data[$day] = ($boost_days_data[$day] ?? 0) + 1;
        }
        wp_reset_postdata();
    }

    // Montar arrays completos (preencher dias sem dados com 0)
    $labels = [];
    $downloads_data = [];
    $boosts_data = [];
    $plays_data = [];

    $downloads_map = [];
    foreach ($downloads_results as $row) {
        $downloads_map[$row->day] = (int) $row->total;
    }

    $plays_map = [];
    foreach ($plays_results as $row) {
        $plays_map[$row->day] = (int) $row->total;
    }

    for ($i = $days - 1; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-{$i} days"));
        $label = date('d/m', strtotime($date));
        $labels[] = $label;
        $downloads_data[] = $downloads_map[$date] ?? 0;
        $boosts_data[] = $boost_days_data[$date] ?? 0;
        $plays_data[] = $plays_map[$date] ?? 0;
    }

    wp_send_json_success([
        'labels'    => $labels,
        'downloads' => $downloads_data,
        'boosts'    => $boosts_data,
        'plays'     => $plays_data,
    ]);
}

// =============================================================================
// ENDPOINT AJAX PARA TOGGLE DARK/LIGHT MODE
// =============================================================================

add_action('wp_ajax_imz_save_theme_preference', 'imz_save_theme_preference');
function imz_save_theme_preference() {
    check_ajax_referer('imz_theme_preference_nonce', 'nonce');
    if (!is_user_logged_in()) wp_send_json_error();
    
    $theme = sanitize_key($_POST['theme'] ?? 'dark');
    if (!in_array($theme, ['dark', 'light'])) $theme = 'dark';
    
    update_user_meta(get_current_user_id(), '_imz_theme_preference', $theme);
    wp_send_json_success(['theme' => $theme]);
}
