<?php
/*
Module: Artists para 1MZ For Artists
Description: Catálogo, impulsionamento, monetização e ferramentas de artista integradas na conta 1MZ.
Version: 9.9
*/

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

// =============================================================================
// CONSTANTES DO PLUGIN
// =============================================================================
define('IMZ_VERSION',                  '9.9');
define('IMZ_DIR',                      plugin_dir_path(__FILE__));
define('IMZ_URL',                      plugin_dir_url(__FILE__));
define('IMZ_ASSETS_URL',               IMZ_URL . 'assets/');

// Constantes de negócio
define('IMZ_MIN_PAYOUT_AMOUNT',        500); // Mínimo para saque (MT)
define('IMZ_FREE_ARTIST_MUSIC_LIMIT',  3);   // Limite de músicas para artistas gratuitos

global $imz_db_version;
$imz_db_version = '1.1';

// =============================================================================
// 1. INSTALAÇÃO E CRIAÇÃO DAS TABELAS PERSONALIZADAS
// =============================================================================

// Tabela de Analytics (Logs de Download)
function imz_install_analytics_table() {
    global $wpdb;
    global $imz_db_version;

    $table_name = $wpdb->prefix . 'imz_analytics';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        music_id bigint(20) NOT NULL,
        user_ip varchar(45) DEFAULT '' NOT NULL,
        user_agent text DEFAULT '' NOT NULL,
        country varchar(10) DEFAULT '' NOT NULL,
        region varchar(100) DEFAULT '' NOT NULL,
        source varchar(20) DEFAULT 'free' NOT NULL,
        download_date datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        INDEX music_id (music_id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
register_activation_hook(__FILE__, 'imz_install_analytics_table');

// Tabela de Reportes de Problemas
function imz_install_reports_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'imz_reports';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        post_id bigint(20) NOT NULL,
        reason varchar(255) NOT NULL,
        comments text DEFAULT '',
        reporter_ip varchar(45) DEFAULT '' NOT NULL,
        reporter_email varchar(180) DEFAULT '' NOT NULL,
        notify_on_resolve tinyint(1) DEFAULT 0 NOT NULL,
        notified_at datetime DEFAULT NULL,
        admin_notes text DEFAULT '' NOT NULL,
        status varchar(20) DEFAULT 'novo' NOT NULL,
        report_date datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        INDEX post_id (post_id),
        INDEX status (status)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
register_activation_hook(__FILE__, 'imz_install_reports_table');

// Tabela de Pedidos de Compra (Vendas)
function imz_install_purchases_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'imz_purchases';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        music_id bigint(20) NOT NULL,
        artist_id bigint(20) NOT NULL,
        user_name varchar(100) NOT NULL,
        user_phone varchar(20) NOT NULL,
        status varchar(20) DEFAULT 'pendente' NOT NULL,
        download_code varchar(20) DEFAULT '' NOT NULL,
        verification_code varchar(20) DEFAULT '' NOT NULL,
        price decimal(10,2) DEFAULT 0.00 NOT NULL,
        date datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        INDEX music_id (music_id),
        INDEX artist_id (artist_id),
        INDEX status (status),
        INDEX download_code (download_code),
        INDEX verification_code (verification_code)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
register_activation_hook(__FILE__, 'imz_install_purchases_table');

// Tabela de Reproduções (Plays do Player)
function imz_install_plays_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'imz_plays';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        music_id bigint(20) NOT NULL,
        user_ip varchar(45) DEFAULT '' NOT NULL,
        play_date datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        INDEX music_id (music_id),
        INDEX play_date (play_date)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
register_activation_hook(__FILE__, 'imz_install_plays_table');

/**
 * Devolve o número total de reproduções válidas de uma música (com cache de 10 min).
 * Os plays são credíveis: mínimo 30s de escuta e limites por IP (ver imz_ajax_track_play).
 */
function imz_get_play_count($post_id) {
    $post_id = absint($post_id);
    if (!$post_id) return 0;

    $cache_key = 'imz_play_count_' . $post_id;
    $count = get_transient($cache_key);
    if (false !== $count) return (int) $count;

    global $wpdb;
    $table = $wpdb->prefix . 'imz_plays';
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) !== $table) {
        return 0;
    }
    $count = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $table WHERE music_id = %d", $post_id));
    set_transient($cache_key, $count, 10 * MINUTE_IN_SECONDS);
    return $count;
}

// AJAX handler para tracking de plays
add_action('wp_ajax_imz_track_play', 'imz_ajax_track_play');
add_action('wp_ajax_nopriv_imz_track_play', 'imz_ajax_track_play');
function imz_ajax_track_play() {
    $post_id = absint($_POST['post_id'] ?? 0);
    if ($post_id === 0) { wp_send_json_error(); return; }

    // Validar que o post existe e é uma música
    $post = get_post($post_id);
    if (!$post || $post->post_type !== 'post' || $post->post_status !== 'publish') {
        wp_send_json_error(['message' => 'Música inválida.']);
        return;
    }

    // Validar tempo mínimo de escuta (enviado pelo JS)
    $listen_seconds = absint($_POST['listen_seconds'] ?? 0);
    if ($listen_seconds < 30) {
        wp_send_json_error(['message' => 'Tempo de escuta insuficiente.']);
        return;
    }

    global $wpdb;
    $table = $wpdb->prefix . 'imz_plays';
    $ip = function_exists('imz_get_user_ip') ? imz_get_user_ip() : sanitize_text_field($_SERVER['REMOTE_ADDR']);

    // Auto-criar tabela se não existir
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) !== $table) {
        imz_install_plays_table();
    }

    // REGRA 1: Máximo 1 play por IP por música a cada 24 horas
    $recent_same_music = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM $table WHERE music_id = %d AND user_ip = %s AND play_date > DATE_SUB(NOW(), INTERVAL 24 HOUR)",
        $post_id, $ip
    ));
    if ($recent_same_music > 0) {
        wp_send_json_success(['tracked' => false, 'reason' => 'already_counted']);
        return;
    }

    // REGRA 2: Máximo 20 plays totais por IP por dia (anti-spam)
    $daily_plays_by_ip = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM $table WHERE user_ip = %s AND DATE(play_date) = CURDATE()",
        $ip
    ));
    if ($daily_plays_by_ip >= 20) {
        wp_send_json_success(['tracked' => false, 'reason' => 'daily_limit']);
        return;
    }

    // Tudo válido — registar a reprodução
    $wpdb->insert($table, [
        'music_id' => $post_id,
        'user_ip'  => $ip,
    ], ['%d', '%s']);

    wp_send_json_success(['tracked' => true]);
}


// =============================================================================
// SISTEMA DE MEMBROS PERSONALIZADO (PRO vs Gratuito)
// =============================================================================

/**
 * Verifica se um utilizador é um Artista PRO ativo.
 */
function imz_is_artist_pro($user_id = null) {
    if (is_null($user_id)) {
        $user_id = get_current_user_id();
    }
    if (empty($user_id)) {
        return false;
    }

    // Quando embutido, a aprovação no Programa de Parceria é a fonte de
    // verdade para catálogo, controlo e ganhos. A subscrição VIP continua a
    // governar os restantes serviços da plataforma.
    if (defined('RMBZ_ARTISTS_EMBEDDED') && function_exists('imz_rmbz_phone_for_user')) {
        $telemovel = imz_rmbz_phone_for_user($user_id);
        return $telemovel !== ''
            && function_exists('rmbz_partnership_has_access')
            && rmbz_partnership_has_access($telemovel);
    }

    $expiration_timestamp = get_user_meta($user_id, '_imz_pro_expiration_date', true);
    if (empty($expiration_timestamp)) {
        return false;
    }
    return (int)$expiration_timestamp > current_time('timestamp');
}

/**
 * Tarefa agendada (diária) para verificar subscrições PRO expiradas.
 */
function imz_check_expired_pro_memberships() {
    if (defined('RMBZ_ARTISTS_EMBEDDED')) {
        return;
    }
    $args = [
        'meta_key'       => '_imz_pro_expiration_date',
        'meta_value'     => current_time('timestamp'),
        'meta_compare'   => '<=',
        'meta_type'      => 'NUMERIC',
        'fields'         => 'ID'
    ];

    $expired_user_ids = get_users($args);

    foreach ($expired_user_ids as $user_id) {
        delete_user_meta($user_id, '_imz_pro_expiration_date');

        // Reverter músicas pagas para gratuitas
        $args_posts = [
            'post_type' => 'post',
            'author' => $user_id,
            'posts_per_page' => -1,
            'meta_key' => '_imz_enable_paid_download',
            'meta_value' => 'yes',
            'fields' => 'ids'
        ];

        $expired_paid_posts = new WP_Query($args_posts);

        if ($expired_paid_posts->have_posts()) {
            foreach ($expired_paid_posts->posts as $post_id) {
                update_post_meta($post_id, '_imz_enable_paid_download', 'expired_pro');
                update_post_meta($post_id, '_imz_enable_download', 'yes');
            }
        }
    }
}
add_action('imz_daily_expired_check_event', 'imz_check_expired_pro_memberships');

/**
 * Agenda as tarefas recorrentes do plugin e garante as tabelas.
 */
function imz_schedule_tasks() {
    if (!defined('RMBZ_ARTISTS_EMBEDDED') && !wp_next_scheduled('imz_daily_expired_check_event')) {
        wp_schedule_event(time(), 'daily', 'imz_daily_expired_check_event');
    }
    // Garante as tabelas necessárias
    imz_install_analytics_table();
    imz_install_reports_table();
    imz_install_purchases_table();
}
register_activation_hook(__FILE__, 'imz_schedule_tasks');

/**
 * Limpa as tarefas agendadas do plugin.
 */
function imz_clear_scheduled_tasks() {
    wp_clear_scheduled_hook('imz_daily_expired_check_event');
}
register_deactivation_hook(__FILE__, 'imz_clear_scheduled_tasks');


// =============================================================================
// REGISTO DE TIPOS DE POST (CPTs) - ATUALIZADO
// =============================================================================

function imz_admin_parent_slug() {
    return 'edit.php?post_type=impulsionamento';
}

function imz_register_all_cpts() {
    // Menu Principal
    register_post_type('impulsionamento', [
        'labels' => ['name' => '1MZ Admin', 'singular_name' => 'Impulsionamento', 'menu_name' => '1MZ Admin'],
        'public' => false, 'show_ui' => true, 'supports' => ['title', 'custom-fields'],
        'show_in_menu' => true,
        'menu_icon' => 'dashicons-megaphone', 'capabilities' => ['create_posts' => 'do_not_allow'], 'map_meta_cap' => true,
    ]);

    if ( ! function_exists( 'rmbz_dm_legacy_disabled' ) || ! rmbz_dm_legacy_disabled() ) {
    register_post_type('claim', [
        'label' => 'Reivindicações', 'public' => false, 'show_ui' => true,
        'show_in_menu' => imz_admin_parent_slug(),
        'supports' => ['title'], 'menu_icon' => 'dashicons-flag', 'capabilities' => ['create_posts' => 'do_not_allow'], 'map_meta_cap' => true,
    ]);
    }

    register_post_type('imz_takedown', [
        'label' => 'Pedidos de Proteção', 'public' => false, 'show_ui' => true,
        'show_in_menu' => imz_admin_parent_slug(),
        'supports' => ['title'], 'menu_icon' => 'dashicons-shield-alt', 'capabilities' => ['create_posts' => 'do_not_allow'], 'map_meta_cap' => true,
        'labels' => [
            'name' => 'Pedidos de Proteção', 'singular_name' => 'Pedido de Proteção', 'menu_name' => 'Proteção Digital',
            'all_items' => 'Pedidos de Proteção',
            'edit_item' => 'Ver Pedido'
        ]
    ]);

    if (!defined('RMBZ_ARTISTS_EMBEDDED')) {
        register_post_type('imz_subscription', [
            'label' => 'Subscrições PRO', 'public' => false, 'show_ui' => true,
            'show_in_menu' => imz_admin_parent_slug(),
            'supports' => ['title'], 'menu_icon' => 'dashicons-star-filled', 'capabilities' => ['create_posts' => 'do_not_allow'], 'map_meta_cap' => true,
            'labels' => ['name' => 'Subscrições PRO', 'singular_name' => 'Subscrição PRO', 'menu_name' => 'Subscrições PRO', 'all_items' => 'Todas as Subscrições', 'edit_item' => 'Ver Subscrição']
        ]);
    }
    
    register_post_type('imz_payout', [
        'label' => 'Pedidos de Pagamento', 'public' => false, 'show_ui' => true,
        'show_in_menu' => imz_admin_parent_slug(),
        'supports' => ['title'], 'menu_icon' => 'dashicons-money-alt', 'capabilities' => ['create_posts' => 'do_not_allow'], 'map_meta_cap' => true,
        'labels' => [
            'name' => 'Pedidos de Pagamento', 'singular_name' => 'Pedido de Pagamento', 'menu_name' => 'Pagamentos',
            'all_items' => 'Pedidos de Saque',
            'edit_item' => 'Ver Pedido'
        ]
    ]);

    // CPTs Removidos (Agora são tabelas SQL):
    // - imz_download_log
    // - imz_report
    // - imz_purchase
}
add_action('init', 'imz_register_all_cpts');

function imz_register_custom_post_statuses() {
    if ( function_exists( 'rmbz_dm_legacy_disabled' ) && rmbz_dm_legacy_disabled() ) return;
    register_post_status('claim_approved', ['label' => _x('Aprovado', 'claim'), 'public' => false, 'exclude_from_search' => true, 'show_in_admin_all_list' => true, 'show_in_admin_status_list' => true, 'label_count' => _n_noop('Aprovado <span class="count">(%s)</span>', 'Aprovados <span class="count">(%s)</span>')]);
    register_post_status('claim_rejected', ['label' => _x('Rejeitado', 'claim'), 'public' => false, 'exclude_from_search' => true, 'show_in_admin_all_list' => true, 'show_in_admin_status_list' => true, 'label_count' => _n_noop('Rejeitado <span class="count">(%s)</span>', 'Rejeitados <span class="count">(%s)</span>')]);
}
add_action('init', 'imz_register_custom_post_statuses');


// =============================================================================
// GESTÃO DE ASSETS (CSS/JS)
// =============================================================================

/**
 * Helper: retorna a versão de um asset via filemtime() para cache-busting automático.
 *
 * @param  string $relative_path Caminho relativo à pasta do plugin (ex: 'assets/frontend.css')
 * @return string Versão para usar no wp_enqueue_*
 */
function imz_asset_version( string $relative_path ): string {
    $abs = IMZ_DIR . $relative_path;
    return file_exists( $abs ) ? (string) filemtime( $abs ) : IMZ_VERSION;
}

/**
 * Enfileira scripts e estilos para o FRONTEND.
 * Cada asset só é carregado na(s) página(s) onde é realmente necessário.
 */
function imz_enqueue_assets() {
    global $post;

    $is_wp_post          = is_a($post, 'WP_Post');
    $is_embedded_dashboard = defined('RMBZ_ARTISTS_EMBEDDED')
        && is_page('minha-conta')
        && sanitize_key(wp_unslash($_GET['sect'] ?? '')) === 'musicas';
    $is_artist_dashboard = ($is_wp_post && has_shortcode($post->post_content, 'painel_artista')) || $is_embedded_dashboard;
    $is_boost_page       = $is_wp_post && has_shortcode($post->post_content, 'formulario_impulsionar');
    $is_music_post       = is_singular('post');
    $is_leaderboard_page = $is_wp_post && has_shortcode($post->post_content, 'top_impulsionadores_geral');
    $is_become_pro_page  = $is_wp_post && has_shortcode($post->post_content, 'pagina_ser_pro');
    $is_purchase_page    = $is_wp_post && has_shortcode($post->post_content, 'imz_purchase_flow');
    $is_download_page    = is_page('processar-download');
    $is_ad_page          = $is_wp_post && (has_shortcode($post->post_content, 'imz_submeter_anuncio') || has_shortcode($post->post_content, 'imz_anuncios'));
    $is_my_ads_page      = $is_wp_post && has_shortcode($post->post_content, 'imz_meus_anuncios');
    $is_rec_page         = $is_wp_post && (has_shortcode($post->post_content, 'imz_top_recomendadas') || has_shortcode($post->post_content, 'imz_recomendacao'));
    $is_top_musicas_page = $is_wp_post && has_shortcode($post->post_content, 'imz_top_musicas');

    $needs_frontend_css  = $is_music_post || $is_boost_page || $is_artist_dashboard
                        || $is_download_page || $is_leaderboard_page
                        || $is_become_pro_page || $is_purchase_page
                        || $is_ad_page || $is_rec_page || $is_top_musicas_page
                        || $is_my_ads_page;

    // 0. Design tokens — registado sempre, para qualquer estilo do plugin depender dele
    wp_register_style('imz-design-tokens', IMZ_ASSETS_URL . 'design-tokens.css', [], imz_asset_version('assets/design-tokens.css'));

    // 1. CSS principal do frontend — só onde é preciso
    if ($needs_frontend_css) {
        wp_enqueue_style('imz-frontend-styles', IMZ_ASSETS_URL . 'frontend.css', ['imz-design-tokens'], imz_asset_version('assets/frontend.css'));
    }

    // 2. Painel do Artista
    if ($is_artist_dashboard) {
        wp_enqueue_style('imz-artist-dashboard-native', IMZ_ASSETS_URL . 'artist-dashboard-native.css', ['imz-frontend-styles'], imz_asset_version('assets/artist-dashboard-native.css'));
        wp_enqueue_script('imz-artist-dashboard-native', IMZ_ASSETS_URL . 'artist-dashboard-native.js', [], imz_asset_version('assets/artist-dashboard-native.js'), true);
    }
    // 3. Impulsionamento e Upgrade PRO
    if ($is_become_pro_page) {
        wp_enqueue_script('imz-boost-form-script', IMZ_ASSETS_URL . 'boost-form.js', [], imz_asset_version('assets/boost-form.js'), true);
        wp_localize_script('imz-boost-form-script', 'imz_boost_ajax_data', [
            'ajax_url'      => admin_url('admin-ajax.php'),
            'nonce_upload'  => wp_create_nonce('imz_upload_boost_receipt_nonce'),
            'nonce_payment' => wp_create_nonce('imz_initiate_payment_nonce'),
        ]);
    }

    // 3b. Painel do Anunciante
    if ($is_my_ads_page) {
        wp_enqueue_script('imz-ads-advertiser', IMZ_ASSETS_URL . 'ads-advertiser.js', [], imz_asset_version('assets/ads-advertiser.js'), true);
        wp_localize_script('imz-ads-advertiser', 'imz_myads_data', [
            'ajax_url'     => admin_url('admin-ajax.php'),
            'nonce_toggle' => wp_create_nonce('imz_ad_toggle_status'),
        ]);
    }

    // 3c. Pagamento M-Pesa de anúncios (página de submissão e painel do anunciante)
    $has_artist_account = defined('RMBZ_ARTISTS_EMBEDDED')
        ? (function_exists('imz_rmbz_is_artist_logged_in') && imz_rmbz_is_artist_logged_in())
        : is_user_logged_in();
    if (($is_ad_page || $is_my_ads_page) && $has_artist_account && get_option('imz_enable_mpesa_api')) {
        wp_enqueue_script('imz-ads-payment', IMZ_ASSETS_URL . 'ads-payment.js', [], imz_asset_version('assets/ads-payment.js'), true);
        wp_localize_script('imz-ads-payment', 'imz_ad_pay_data', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('imz_ad_payment_nonce'),
        ]);
    }

    // 4. Compra de Música
    if ($is_purchase_page) {
        wp_enqueue_script('imz-purchase-flow-script', IMZ_ASSETS_URL . 'purchase-flow.js', [], imz_asset_version('assets/purchase-flow.js'), true);
        wp_localize_script('imz-purchase-flow-script', 'imz_ajax_data', [
            'ajax_url'            => admin_url('admin-ajax.php'),
            'recaptcha_site_key'  => get_option('imz_recaptcha_site_key', ''),
            'nonce_verify_artist' => wp_create_nonce('imz_verify_artist_code_nonce'),
        ]);
    }

    // 5. Páginas de Música — player de áudio e modal de reporte
    if ($is_music_post || $is_download_page) {
        if ($is_music_post && $is_wp_post && get_post_meta($post->ID, '_imz_enable_audio_player', true) === 'yes') {
            wp_enqueue_script('youtube-iframe-api', 'https://www.youtube.com/iframe_api', [], null, true);
            wp_enqueue_script('imz-audio-player', IMZ_ASSETS_URL . 'audio-player.js', ['youtube-iframe-api'], imz_asset_version('assets/audio-player.js'), true);
            wp_localize_script('imz-audio-player', 'imz_player_data', [
                'ajax_url' => admin_url('admin-ajax.php'),
            ]);
        }
        wp_enqueue_script('imz-report-modal', IMZ_ASSETS_URL . 'report-modal.js', [], imz_asset_version('assets/report-modal.js'), true);
        wp_localize_script('imz-report-modal', 'imz_report_ajax_data', [
            'ajax_url'           => admin_url('admin-ajax.php'),
            'nonce'              => wp_create_nonce('imz_submit_report_nonce'),
            'recaptcha_site_key' => get_option('imz_recaptcha_site_key', ''),
        ]);
    }

    // 6. Processamento de Download
    if ($is_download_page) {
        wp_enqueue_script('imz-download-processor', IMZ_ASSETS_URL . 'download-processor.js', [], imz_asset_version('assets/download-processor.js'), true);
        wp_localize_script('imz-download-processor', 'imz_download_ajax_data', [
            'ajax_url'           => admin_url('admin-ajax.php'),
            'nonce'              => wp_create_nonce('imz_verify_captcha_nonce'),
            'recaptcha_site_key' => get_option('imz_recaptcha_site_key', ''),
        ]);
    }

    // 7. reCAPTCHA — só carregado onde existe chave E é necessário
    $recaptcha_key = get_option('imz_recaptcha_site_key');
    if (!empty($recaptcha_key)) {
        $recaptcha_base = 'https://www.google.com/recaptcha/api.js';
        $recaptcha_args = ['render' => 'explicit'];

        if ($is_purchase_page) {
            $recaptcha_args['onload'] = 'imzPurchaseRecaptchaReady';
            wp_enqueue_script('google-recaptcha-purchase', add_query_arg($recaptcha_args, $recaptcha_base), [], null, true);
        } elseif ($is_download_page && get_option('imz_enable_download_captcha')) {
            $recaptcha_args['onload'] = 'imzDownloadRecaptchaReady';
            wp_enqueue_script('google-recaptcha-download', add_query_arg($recaptcha_args, $recaptcha_base), [], null, true);
        } elseif ($is_music_post) {
            wp_enqueue_script('google-recaptcha-report', add_query_arg($recaptcha_args, $recaptcha_base), [], null, true);
        }
    }
}
add_action('wp_enqueue_scripts', 'imz_enqueue_assets');

/**
 * Enfileira CSS/JS do admin APENAS nas páginas relevantes do plugin.
 * Evita carregar estilos desnecessários em todo o painel WordPress.
 *
 * @param string $hook_suffix Identificador da página atual do admin.
 */
function imz_enqueue_admin_assets(string $hook_suffix) {
    $imz_post_types = ['impulsionamento', 'claim', 'imz_takedown', 'imz_subscription', 'imz_payout'];

    $is_imz_cpt_page = (
        in_array($hook_suffix, ['post.php', 'post-new.php', 'edit.php'], true) &&
        isset($_GET['post_type']) &&
        in_array(sanitize_key($_GET['post_type']), $imz_post_types, true)
    );

    $is_post_edit_page    = ($hook_suffix === 'post.php' || $hook_suffix === 'post-new.php');
    $is_imz_settings_page = (strpos($hook_suffix, 'impulsionamento') !== false);

    if (!$is_imz_cpt_page && !$is_post_edit_page && !$is_imz_settings_page) {
        return;
    }

    wp_enqueue_style('imz-admin-styles', IMZ_ASSETS_URL . 'admin.css', [], imz_asset_version('assets/admin.css'));
}
add_action('admin_enqueue_scripts', 'imz_enqueue_admin_assets');


// =============================================================================
// FUNÇÕES UTILITÁRIAS E GERAIS
// =============================================================================

function imz_calculate_artist_share($artist_id, $amount) {
    $percentage = imz_is_artist_pro($artist_id) ? 70.0 : 20.0;
    return $amount * ($percentage / 100.0);
}

function imz_verify_recaptcha($recaptcha_response) {
    $secret_key = get_option('imz_recaptcha_secret_key');
    if (empty($secret_key) || empty($recaptcha_response)) {
        error_log('IMZ reCAPTCHA Error: Missing key or response.');
        return false;
    }
    $verify_url = 'https://www.google.com/recaptcha/api/siteverify';
    $args = ['body' => ['secret' => $secret_key, 'response' => $recaptcha_response, 'remoteip' => imz_get_user_ip()], 'timeout' => 15];
    $response = wp_remote_post($verify_url, $args);
    if (is_wp_error($response)) return false;
    $result = json_decode(wp_remote_retrieve_body($response), true);
    return isset($result['success']) && $result['success'] === true;
}

function imz_delete_boost_attachment($post_id) {
    if (get_post_type($post_id) === 'impulsionamento' && function_exists('wp_delete_attachment')) {
        $attachment_id = get_post_meta($post_id, 'comprovativo_id', true);
        if ($attachment_id) wp_delete_attachment($attachment_id, true);
    }
}
add_action('before_delete_post', 'imz_delete_boost_attachment');

function imz_unclaim_music_on_claim_deletion($post_id) {
    if (get_post_type($post_id) !== 'claim') return;
    $music_id = get_post_meta($post_id, 'music_id', true);
    if (!$music_id || !get_post($music_id)) return;
    wp_update_post(['ID' => $music_id, 'post_author' => 1]);
    delete_post_meta($music_id, '_is_claimed');
    delete_post_meta($music_id, '_proof_of_ownership_id');
    delete_post_meta($music_id, '_artist_earnings');
}
add_action('before_delete_post', 'imz_unclaim_music_on_claim_deletion', 10, 1);

function imz_get_verified_post_ids() {
    $verified_ids = get_transient('imz_verified_post_ids_list');
    if (false !== $verified_ids && is_array($verified_ids)) return $verified_ids;
    $query = new WP_Query([
        'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1,
        'meta_key' => '_is_verified_by_boosts', 'meta_value' => 'yes', 'fields' => 'ids',
        'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false,
    ]);
    $verified_ids = $query->posts;
    set_transient('imz_verified_post_ids_list', $verified_ids, 12 * HOUR_IN_SECONDS);
    return $verified_ids;
}

function imz_get_valid_artist_strikes($user_id) {
    if (!$user_id) return 0;
    $strikes_timestamps = get_user_meta($user_id, '_fraudulent_claim_strikes', true);
    if (!is_array($strikes_timestamps) || empty($strikes_timestamps)) return 0;
    $expiration_threshold = strtotime('-30 days');
    $valid_strikes = array_filter($strikes_timestamps, function($timestamp) use ($expiration_threshold) {
        return is_numeric($timestamp) && $timestamp > $expiration_threshold;
    });
    return count($valid_strikes);
}

function imz_add_verified_badge_to_title($title, $id = null) {
    if (in_the_loop() && is_main_query() && !is_admin() && get_post_type($id) === 'post') {
        if ($id === null) return $title;
        $badge_style = 'display: inline-block; vertical-align: middle; width: 22px; height: 22px; margin-left: 6px;';
        $post_publish_timestamp = get_the_time('U', $id);
        $is_new = (current_time('U') - $post_publish_timestamp) < (7 * DAY_IN_SECONDS);
        if ($is_new) {
            $new_badge_url = plugin_dir_url(__FILE__) . 'assets/novo.png';
            $title .= "<img src='{$new_badge_url}' style='{$badge_style}' alt='Novo'>";
        }
        $native_enrollment = function_exists( 'rmbz_dm_enrollment' ) ? rmbz_dm_enrollment( $id ) : null;
        $is_claimed = $native_enrollment && $native_enrollment->status === 'active';
        $is_verified = in_array($id, imz_get_verified_post_ids(), true);
        if ($is_claimed) {
            $verified_badge_url = plugin_dir_url(__FILE__) . 'assets/verificado-ouro.png';
            $title .= "<img src='{$verified_badge_url}' style='{$badge_style}' alt='Música Monetizada'>";
        } elseif ($is_verified) {
            $verified_badge_url = plugin_dir_url(__FILE__) . 'assets/verificado.png';
            $title .= "<img src='{$verified_badge_url}' style='{$badge_style}' alt='Verificado'>";
        }
    }
    return $title;
}
add_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);

function imz_prevent_artist_post_editing($allcaps, $caps, $args) {
    if (isset($caps[0]) && $caps[0] === 'edit_post') {
        $post_id = isset($args[2]) ? $args[2] : null;
        if ($post_id && get_post_type($post_id) === 'post') {
            if (!isset($allcaps['manage_options']) || !$allcaps['manage_options']) {
                $owner = function_exists( 'rmbz_dm_catalog_owner' ) ? rmbz_dm_catalog_owner( $post_id ) : null;
                if ( $owner && absint( $owner->linked_user_id ) === absint( $args[1] ?? 0 ) ) {
                    $allcaps[$caps[0]] = false;
                }
            }
        }
    }
    return $allcaps;
}
add_filter('user_has_cap', 'imz_prevent_artist_post_editing', 10, 3);


// =============================================================================
// CARREGAR FICHEIROS DEPENDENTES (INCLUDES)
// =============================================================================

require_once plugin_dir_path(__FILE__) . 'includes/admin-panel.php';
require_once plugin_dir_path(__FILE__) . 'includes/admin-save-handlers.php';
require_once plugin_dir_path(__FILE__) . 'includes/admin-lists-filters.php';
require_once plugin_dir_path(__FILE__) . 'includes/artist/artist-dashboard.php';
require_once plugin_dir_path(__FILE__) . 'includes/payout-system.php';
require_once plugin_dir_path(__FILE__) . 'includes/shortcodes.php';
require_once plugin_dir_path(__FILE__) . 'includes/selo-display.php';
require_once plugin_dir_path(__FILE__) . 'includes/settings.php';
require_once plugin_dir_path(__FILE__) . 'includes/leaderboard.php';
if ( ! function_exists( 'rmbz_dm_native_ready' ) ) require_once plugin_dir_path(__FILE__) . 'includes/monetized-page.php';
require_once plugin_dir_path(__FILE__) . 'includes/cleanup-tool.php';
require_once plugin_dir_path(__FILE__) . 'includes/mpesa-api.php';
require_once plugin_dir_path(__FILE__) . 'includes/youtube-integration.php';
require_once plugin_dir_path(__FILE__) . 'includes/digital-stores.php';
require_once plugin_dir_path(__FILE__) . 'includes/report-system.php';
require_once plugin_dir_path(__FILE__) . 'includes/presave-system.php';
require_once plugin_dir_path(__FILE__) . 'includes/download-manager.php';
require_once plugin_dir_path(__FILE__) . 'includes/document-generator.php';
require_once plugin_dir_path(__FILE__) . 'includes/paid-download-system.php';
require_once plugin_dir_path(__FILE__) . 'includes/analytics-page.php';
require_once plugin_dir_path(__FILE__) . 'includes/ads-geo.php';
require_once plugin_dir_path(__FILE__) . 'includes/ad-formats.php';
require_once plugin_dir_path(__FILE__) . 'includes/boost-analytics.php';
require_once plugin_dir_path(__FILE__) . 'includes/ads-system.php';
require_once plugin_dir_path(__FILE__) . 'includes/ads-reports.php';
require_once plugin_dir_path(__FILE__) . 'includes/ads-advertiser-panel.php';
require_once plugin_dir_path(__FILE__) . 'includes/dashboard-api.php';
require_once plugin_dir_path(__FILE__) . 'includes/recommendation-system.php';
require_once plugin_dir_path(__FILE__) . 'includes/artist-profiles.php';
if ( ! function_exists( 'rmbz_dm_native_ready' ) ) require_once plugin_dir_path(__FILE__) . 'includes/engagement-monetization.php';
require_once plugin_dir_path(__FILE__) . 'includes/top-musicas.php';


// =============================================================================
// SISTEMA DE NOTIFICAÇÕES NO MENU ADMIN (ATUALIZADO)
// =============================================================================

function imz_get_all_pending_counts() {
    $cached_counts = get_transient('imz_pending_counts');
    if (false !== $cached_counts && is_array($cached_counts)) return $cached_counts;

    global $wpdb;

    $counts = [
        'boosts' => 0, 'claims' => 0, 'reports' => 0, 'payouts' => 0,
        'takedowns' => 0, 'subscriptions' => 0, 'purchases' => 0, 'ads' => 0, 'total' => 0
    ];
    
    $query_base = ['post_status' => 'publish', 'fields' => 'ids', 'posts_per_page' => -1, 'no_found_rows' => true];
    
    $counts['boosts'] = (new WP_Query(array_merge($query_base, ['post_type' => 'impulsionamento', 'meta_query' => [['key' => 'status', 'value' => 'pendente']]])))->post_count;
    $counts['claims'] = wp_count_posts('claim')->pending ?? 0;
    
    // SQL Queries para tabelas personalizadas
    $reports_table = $wpdb->prefix . 'imz_reports';
    $purchases_table = $wpdb->prefix . 'imz_purchases';
    
    // Verifica se a tabela existe antes de consultar (para evitar erros na ativação)
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $reports_table)) == $reports_table) {
        $counts['reports'] = (int)$wpdb->get_var("SELECT COUNT(*) FROM $reports_table WHERE status = 'novo'");
    }
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $purchases_table)) == $purchases_table) {
        $counts['purchases'] = (int)$wpdb->get_var("SELECT COUNT(*) FROM $purchases_table WHERE status = 'pendente'");
    }

    $counts['payouts'] = (new WP_Query(array_merge($query_base, ['post_type' => 'imz_payout', 'meta_query' => [['key' => '_payout_status', 'value' => 'pendente']]])))->post_count;
    $counts['takedowns'] = (new WP_Query(array_merge($query_base, ['post_type' => 'imz_takedown', 'meta_query' => [['key' => '_takedown_status', 'value' => 'pendente']]])))->post_count;
    if (!defined('RMBZ_ARTISTS_EMBEDDED')) {
        $counts['subscriptions'] = (new WP_Query(array_merge($query_base, ['post_type' => 'imz_subscription', 'meta_query' => [['key' => 'status', 'value' => 'pendente']]])))->post_count;
    }
    $counts['ads'] = (new WP_Query(array_merge($query_base, ['post_type' => 'imz_anuncio', 'meta_query' => [['key' => '_imz_ad_status', 'value' => 'pendente']]])))->post_count;
    
    $counts['total'] = array_sum(array_diff_key($counts, ['total' => '']));
    set_transient('imz_pending_counts', $counts, 5 * MINUTE_IN_SECONDS);
    return $counts;
}

function imz_add_notification_bubbles_to_menu() {
    global $menu, $submenu;
    $counts = imz_get_all_pending_counts();
    if (!is_array($counts) || !isset($counts['total']) || $counts['total'] == 0) return;

    $main_menu_slug = imz_admin_parent_slug();
    foreach ($menu as $key => $value) {
        if (isset($value[2]) && $main_menu_slug == $value[2]) {
            $menu[$key][0] .= ' <span class="awaiting-mod"><span class="pending-count">' . number_format_i18n($counts['total']) . '</span></span>';
            break;
        }
    }
    if (isset($submenu[$main_menu_slug])) {
        foreach ($submenu[$main_menu_slug] as $key => $value) {
            $count = 0;
            $slug = $value[2];
            if (strpos($slug, 'impulsionamento') !== false) $count = $counts['boosts'];
            elseif (strpos($slug, 'claim') !== false) $count = $counts['claims'];
            elseif (strpos($slug, 'imz_reports_manager') !== false) $count = $counts['reports']; // Nome da página admin
            elseif (strpos($slug, 'imz_payout') !== false) $count = $counts['payouts'];
            elseif (strpos($slug, 'imz_takedown') !== false) $count = $counts['takedowns'];
            elseif (strpos($slug, 'imz_subscription') !== false) $count = $counts['subscriptions'];
            elseif (strpos($slug, 'imz_purchases_manager') !== false) $count = $counts['purchases']; // Nome da página admin
            elseif (strpos($slug, 'imz_ads_manager') !== false) $count = $counts['ads']; // Anúncios pendentes

            if ($count > 0) $submenu[$main_menu_slug][$key][0] .= ' <span class="awaiting-mod"><span class="pending-count">' . number_format_i18n($count) . '</span></span>';
        }
    }
}
add_action('admin_menu', 'imz_add_notification_bubbles_to_menu', 99);

function imz_clear_pending_counts_cache_generic_hook($post_id_or_post) {
    $post_id = is_object($post_id_or_post) ? $post_id_or_post->ID : $post_id_or_post;
    $post = get_post($post_id);
    if (!$post) {
        global $wpdb;
        $post_type = $wpdb->get_var($wpdb->prepare("SELECT post_type FROM $wpdb->posts WHERE ID = %d", $post_id));
        if(!$post_type) return;
    } else {
        $post_type = $post->post_type;
    }
    // CPTs que continuam a ser posts
    $post_types = ['impulsionamento', 'claim', 'imz_payout', 'imz_takedown', 'imz_subscription', 'imz_anuncio'];
    if (in_array($post_type, $post_types)) delete_transient('imz_pending_counts');
}
add_action('save_post', 'imz_clear_pending_counts_cache_generic_hook', 10, 1);
add_action('wp_trash_post', 'imz_clear_pending_counts_cache_generic_hook', 10, 1);
add_action('untrash_post', 'imz_clear_pending_counts_cache_generic_hook', 10, 1);
add_action('before_delete_post', 'imz_clear_pending_counts_cache_generic_hook', 10, 1);

function imz_clear_pending_counts_cache_on_transition($new_status, $old_status, $post) {
    $post_types = ['impulsionamento', 'claim', 'imz_payout', 'imz_takedown', 'imz_subscription', 'imz_anuncio'];
    if ($new_status != $old_status && in_array($post->post_type, $post_types)) delete_transient('imz_pending_counts');
}
add_action('transition_post_status', 'imz_clear_pending_counts_cache_on_transition', 10, 3);
?>
