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

// =============================================================================
// FUNÇÕES AUXILIARES
// =============================================================================

/**
 * Obtém o IP do utilizador de forma segura.
 *
 * Usa apenas REMOTE_ADDR: os headers HTTP_CLIENT_IP / HTTP_X_FORWARDED_FOR são
 * controlados pelo cliente e permitiam falsificar IPs para contornar os rate
 * limits (plays, reações, downloads). NOTA: se o site passar a estar atrás de
 * um proxy/CDN (ex: Cloudflare), REMOTE_ADDR será o IP do proxy — nesse caso é
 * preciso reintroduzir aqui a leitura do header do proxy (ex: CF-Connecting-IP),
 * validando que REMOTE_ADDR pertence ao próprio proxy.
 */
function imz_get_user_ip() {
    $ip = !empty($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '';
    return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '0.0.0.0';
}

/**
 * Obtém o User Agent.
 */
function imz_get_user_agent() {
    return isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '';
}

/**
 * Gera a impressão digital (fingerprint) do utilizador.
 */
function imz_get_user_fingerprint() {
    $ip = imz_get_user_ip();
    $user_agent = imz_get_user_agent();
    return md5($ip . $user_agent);
}


// =============================================================================
// DISPLAY DA CAIXA DE DOWNLOAD (FRONTEND)
// =============================================================================

add_filter('the_content', 'imz_display_download_box', 5);
function imz_display_download_box($content) {
    if (is_singular('post') && in_the_loop() && is_main_query()) {
        $post_id = get_the_ID();

        // --- VERIFICAR DOWNLOAD PAGO (PRO) ---
        $is_paid_download_enabled = get_post_meta($post_id, '_imz_enable_paid_download', true);
        $artist_id = get_post_field('post_author', $post_id);
        $is_pro = function_exists('imz_is_artist_pro') ? imz_is_artist_pro($artist_id) : false;

        if ($is_paid_download_enabled === 'yes' && $is_pro) {
            $price = get_post_meta($post_id, '_imz_paid_download_price', true);
            $price_text = !empty($price) ? ' (' . esc_html($price) . ' MT)' : '';
            $purchase_page_url = home_url('/comprar-musica/');
            $purchase_link = add_query_arg(['music_id' => $post_id], $purchase_page_url);

            ob_start();
            ?>
            <div class="imz-download-box" style="background-color: #fffbeb; border-color: #fde68a;">
                <h3 class="imz-download-title"><?php the_title(); ?></h3>
                <p style="font-size: 16px; color: #b45309; margin-top: 0;">Esta é uma música exclusiva para venda.</p>
                <a href="<?php echo esc_url($purchase_link); ?>" class="imz-download-button" style="background-color: #f59e0b;">
                    <svg viewBox="0 0 24 24"><path d="M18 6h-2c0-2.21-1.79-4-4-4S8 3.79 8 6H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-6-2c1.1 0 2 .9 2 2h-4c0-1.1.9-2 2-2zm6 16H6V8h2v2c0 .55.45 1 1 1s1-.45 1-1V8h4v2c0 .55.45 1 1 1s1-.45 1-1V8h2v12z"></path></svg>
                    Comprar Música<?php echo $price_text; ?>
                </a>
            </div>
            <?php
            return $content . ob_get_clean();
        }

        // --- DOWNLOAD GRATUITO ---
        $enable_download = get_post_meta($post_id, '_imz_enable_download', true);
        if ($enable_download !== 'yes') {
            return $content;
        }

        $file_source_type = get_post_meta($post_id, '_imz_file_source_type', true);
        $file_url = get_post_meta($post_id, '_imz_download_file_url', true);
        $file_id = get_post_meta($post_id, '_imz_download_file_id', true);

        if (($file_source_type === 'url' && empty($file_url)) || ($file_source_type !== 'url' && empty($file_id))) {
            return $content;
        }

        $processing_token = wp_generate_password(20, false);
        set_transient('imz_processing_token_' . $processing_token, $post_id, 10 * MINUTE_IN_SECONDS);

        $release_date_raw = get_post_meta($post_id, '_imz_release_date', true);
        $release_date_formatted = '';
        if ($release_date_raw) {
            $date_obj = date_create($release_date_raw);
            if ($date_obj) {
                $meses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
                $mes_index = (int)$date_obj->format('n') - 1;
                $release_date_formatted = $date_obj->format('j') . ' de ' . ($meses[$mes_index] ?? '') . ' de ' . $date_obj->format('Y');
            }
        }

        $quality = get_post_meta($post_id, '_imz_quality', true);
        $download_count = (int) get_post_meta($post_id, '_imz_download_count', true);
        $genres = get_the_category($post_id);
        $genre_names = wp_list_pluck($genres, 'name');

        $processing_page_url = home_url('/processar-download/');
        $download_link = add_query_arg(['key' => $processing_token], $processing_page_url);

        $copyright_notice = get_option('imz_download_copyright_notice', 'Os direitos autorais desta obra pertencem ao artista e/ou ao seu representante. A 1MusicMoz não se responsabiliza pelo conteúdo disponibilizado.');

        // --- Verificar disponibilidade do download ---
        $is_available = true;
        $unavailable_reason = '';

        // Limite total
        $total_limit = (int) get_post_meta($post_id, '_imz_download_limit_per_post', true);
        if ($total_limit > 0 && $download_count >= $total_limit) {
            $is_available = false;
            $unavailable_reason = 'Esta música atingiu o limite total de downloads.';
        }

        // Limite diário
        if ($is_available) {
            $daily_limit_per_post = get_post_meta($post_id, '_imz_daily_download_limit', true);
            $daily_limit = (is_numeric($daily_limit_per_post) && $daily_limit_per_post !== '') ? (int)$daily_limit_per_post : (int)get_option('imz_download_limit', 0);
            if ($daily_limit > 0) {
                $today = date('Y-m-d');
                $daily_count = (int) get_transient('imz_daily_downloads_' . $post_id . '_' . $today);
                if ($daily_count >= $daily_limit) {
                    $is_available = false;
                    $unavailable_reason = 'O limite diário de downloads foi atingido. Tente novamente amanhã.';
                }
            }
        }

        // Cookie de restrição (já baixou)
        if ($is_available) {
            $restriction_level = get_option('imz_download_restriction_level', 'ip_only');
            if ($restriction_level !== 'none' && isset($_COOKIE['imz_downloaded_' . $post_id])) {
                $is_available = false;
                $unavailable_reason = 'Já descarregou esta música anteriormente.';
            }
        }

        $status_color = $is_available ? '#059669' : '#ef4444';
        $status_text = $is_available ? 'Disponível' : 'Indisponível';

        remove_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);
        $clean_title = get_the_title($post_id);
        add_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);

        ob_start();
        ?>
        <div class="imz-dl-card <?php echo !$is_available ? 'imz-dl-unavailable' : ''; ?>">
            <!-- Barra de status no topo -->
            <div class="imz-dl-status-bar" style="background: <?php echo $status_color; ?>;">
                <span class="imz-dl-status-glow" style="background: <?php echo $status_color; ?>;"></span>
            </div>

            <!-- Header só com título e status -->
            <div class="imz-dl-header">
                <h3 class="imz-dl-title"><?php echo esc_html($clean_title); ?></h3>
                <div class="imz-dl-status">
                    <span class="imz-dl-status-dot" style="background: <?php echo $status_color; ?>; box-shadow: 0 0 8px <?php echo $status_color; ?>;"></span>
                    <span class="imz-dl-status-text" style="color: <?php echo $status_color; ?>;"><?php echo $status_text; ?></span>
                </div>
            </div>

            <!-- Metadados em chips -->
            <div class="imz-dl-meta">
                <?php if ($release_date_formatted) : ?>
                    <span class="imz-dl-chip">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                        <?php echo esc_html($release_date_formatted); ?>
                    </span>
                <?php endif; ?>
                <?php if ($quality) : ?>
                    <span class="imz-dl-chip">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>
                        <?php echo esc_html($quality); ?>
                    </span>
                <?php endif; ?>
                <?php if (!empty($genre_names)) : ?>
                    <span class="imz-dl-chip">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
                        <?php echo esc_html(implode(', ', $genre_names)); ?>
                    </span>
                <?php endif; ?>
            </div>

            <!-- Stats -->
            <div class="imz-dl-stats">
                <div class="imz-dl-stat-item">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                    <span class="imz-dl-stat-value"><?php echo number_format($download_count); ?></span>
                    <span class="imz-dl-stat-label">downloads</span>
                </div>
            </div>

            <?php if ($is_available) : ?>
            <!-- Botão de download -->
            <a href="<?php echo esc_url($download_link); ?>" class="imz-dl-button">
                <span class="imz-dl-button-icon">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                </span>
                <span>Baixar Agora</span>
            </a>
            <?php else : ?>
            <!-- Download indisponível -->
            <div class="imz-dl-unavailable-msg">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>
                <span><?php echo esc_html($unavailable_reason); ?></span>
            </div>
            <?php endif; ?>

            <!-- Aviso de copyright -->
            <div class="imz-dl-footer">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
                <span><?php echo esc_html($copyright_notice); ?></span>
            </div>
        </div>
        <?php
        return $content . ob_get_clean();
    }
    return $content;
}


// =============================================================================
// SHORTCODE DA PÁGINA DE PROCESSAMENTO
// =============================================================================

add_shortcode('imz_process_download', 'imz_process_download_shortcode');
function imz_process_download_shortcode() {
    $token = isset($_GET['key']) ? sanitize_key($_GET['key']) : '';
    if (empty($token)) { return '<div class="imz-processing-message error">Link de download inválido.</div>'; }

    // Valida o token inicial
    $post_id = get_transient('imz_processing_token_' . $token);
    if (false === $post_id) { return '<div class="imz-processing-message error">O seu link de download expirou. Por favor, volte à página da música e tente novamente.</div>'; }

    delete_transient('imz_processing_token_' . $token); // Token uso único

    // --- LÓGICA DE LIMITES ---
    $total_limit = (int)get_post_meta($post_id, '_imz_download_limit_per_post', true);
    if ($total_limit > 0) {
        $total_count = (int) get_post_meta($post_id, '_imz_download_count', true);
        if ($total_count >= $total_limit) {
            $message = get_option('imz_limit_reached_message', 'Esta música atingiu o limite total de downloads.');
            return '<div class="imz-processing-message warning">' . wp_kses_post(str_replace('por hoje', '', $message)) . '</div>';
        }
    }

    $daily_limit_per_post = get_post_meta($post_id, '_imz_daily_download_limit', true);
    $daily_limit = (is_numeric($daily_limit_per_post) && $daily_limit_per_post !== '') ? (int)$daily_limit_per_post : (int)get_option('imz_download_limit', 0);
    if ($daily_limit > 0) {
        $today = date('Y-m-d');
        $daily_count = (int) get_transient('imz_daily_downloads_' . $post_id . '_' . $today);
        if ($daily_count >= $daily_limit) {
            $message = get_option('imz_limit_reached_message', 'Esta música atingiu o limite de downloads por hoje.');
            return '<div class="imz-processing-message warning">' . wp_kses_post($message) . '</div>';
        }
    }

    // --- VERIFICAÇÕES DE RESTRIÇÃO ---
    $restriction_level = get_option('imz_download_restriction_level', 'ip_only');
    if ($restriction_level !== 'none') {
        if (isset($_COOKIE['imz_downloaded_' . $post_id])) {
            return '<div class="imz-processing-message warning">Já descarregou esta música. O download está limitado a uma vez por pessoa.</div>';
        }
        // Nota: A verificação na tabela SQL personalizada é feita no momento do download para evitar queries pesadas aqui
    }

    // --- BLOQUEIO GEOGRÁFICO ---
    $user_ip = imz_get_user_ip();
    $blocked_countries_str = get_post_meta($post_id, '_imz_blocked_countries_per_post', true) ?: get_option('imz_blocked_countries', '');
    if (!empty($blocked_countries_str)) {
        $blocked_countries = array_map('strtoupper', array_map('trim', explode(',', $blocked_countries_str)));
        $response = wp_remote_get("http://ip-api.com/json/{$user_ip}?fields=countryCode");
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            $data = json_decode(wp_remote_retrieve_body($response), true);
            $country_code = $data['countryCode'] ?? '';
            if (!empty($country_code) && in_array(strtoupper($country_code), $blocked_countries)) {
                return '<div class="imz-processing-message error">Lamentamos, mas este conteúdo não está disponível para download na sua região.</div>';
            }
        }
    }

    // --- PREPARA O PASSO SEGUINTE ---
    $final_token = wp_generate_password(20, false);
    set_transient('imz_final_token_' . $final_token, $post_id, 5 * MINUTE_IN_SECONDS);
    $secure_link = add_query_arg(['download_key' => $final_token], home_url());

    $terms = get_option('imz_download_terms');
    $enable_captcha_setting = get_option('imz_enable_download_captcha');
    $site_key = get_option('imz_recaptcha_site_key');
    $wait_seconds = (int) get_option('imz_download_wait_seconds', 10);
    if ($wait_seconds < 5) $wait_seconds = 10;

    // Dados da música para exibir
    remove_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);
    $music_title = get_the_title($post_id);
    add_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);

    ob_start();
    ?>
    <style>
    .imz-proc { max-width: 600px; margin: 40px auto; font-family: var(--imz-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif); }

    .imz-proc-card {
        background: var(--imz-color-background-soft, #1a1a1a);
        border: 1px solid var(--imz-border-color, #2a2a2a);
        border-radius: 20px;
        overflow: hidden;
        box-shadow: 0 12px 40px rgba(0,0,0,0.4);
    }

    /* Step indicator */
    .imz-proc-steps-bar {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 18px 24px 0;
    }
    .imz-proc-step-dot {
        width: 32px;
        height: 4px;
        border-radius: 2px;
        background: var(--imz-border-color, #2a2a2a);
        transition: background 0.4s ease;
    }
    .imz-proc-step-dot.done { background: #059669; }
    .imz-proc-step-dot.active { background: #ffffff; animation: imzProcPulse 1.5s ease-in-out infinite; }
    @keyframes imzProcPulse { 0%,100%{ opacity:1; } 50%{ opacity:0.4; } }

    /* Content area */
    .imz-proc-content {
        padding: 28px 28px 24px;
        text-align: center;
        min-height: 200px;
    }

    .imz-proc-icon {
        width: 56px;
        height: 56px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 18px;
    }
    .imz-proc-icon svg { width: 28px; height: 28px; stroke-width: 2; stroke: currentColor; fill: none; stroke-linecap: round; stroke-linejoin: round; }

    .imz-proc-icon.loading { background: rgba(255,255,255,0.06); color: var(--imz-color-text-light, #888); }

    /* Anel de carregamento do passo "A verificar..." (Opção B) */
    .imz-proc-icon.loading { color: var(--imz-color-text, #fff); }
    .imz-proc-spinner-ring {
        width: 26px; height: 26px; border-radius: 50%;
        border: 3px solid rgba(255,255,255,0.18);
        border-top-color: #fff;
        animation: imzRingSpin .8s linear infinite;
    }
    .imz-proc-icon.shield { background: rgba(59,130,246,0.1); color: #60a5fa; }
    .imz-proc-icon.terms { background: rgba(245,158,11,0.1); color: #fbbf24; }
    .imz-proc-icon.success { background: rgba(16,185,129,0.1); color: #34d399; }
    .imz-proc-icon.wait { background: rgba(139,92,246,0.1); color: #a78bfa; }

    .imz-proc h3 { font-size: 20px; font-weight: 700; color: var(--imz-color-text, #fff); margin: 0 0 8px; }
    .imz-proc .imz-proc-desc { font-size: 14px; color: var(--imz-color-text-light, #888); margin: 0 0 24px; line-height: 1.6; }
    .imz-proc .imz-proc-music-name { font-size: 13px; color: var(--imz-color-text-light, #666); margin-bottom: 20px; }
    .imz-proc .imz-proc-music-name strong { color: var(--imz-color-text, #fff); }

    /* Progress bar */
    .imz-proc-progress { height: 5px; border-radius: 3px; background: var(--imz-border-color, #2a2a2a); margin-bottom: 12px; overflow: hidden; }
    .imz-proc-progress-fill { height: 100%; border-radius: 3px; background: #fff; width: 0%; transition: width 0.3s linear; position: relative; }
    .imz-proc-progress-fill::after { content:''; position:absolute; top:0; left:-60%; width:60%; height:100%; background:linear-gradient(90deg,transparent,rgba(255,255,255,0.4),transparent); animation:imz-shimmer 1.5s infinite; }
    .imz-proc-progress-text { font-size: 12px; color: var(--imz-color-text-light, #555); text-transform: uppercase; letter-spacing: 0.5px; }

    /* Countdown circle */
    .imz-proc-countdown {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        border: 3px solid var(--imz-border-color, #2a2a2a);
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 18px;
        font-size: 28px;
        font-weight: 800;
        color: #a78bfa;
        position: relative;
    }
    .imz-proc-countdown-ring {
        position: absolute;
        inset: -3px;
        border-radius: 50%;
        border: 3px solid transparent;
        border-top-color: #a78bfa;
        animation: imzRingSpin 1s linear infinite;
    }
    @keyframes imzRingSpin { to { transform: rotate(360deg); } }

    /* Terms */
    .imz-proc-terms-box { background: var(--imz-color-background, #141414); border: 1px solid var(--imz-border-color, #2a2a2a); border-radius: 10px; padding: 16px; max-height: 140px; overflow-y: auto; text-align: left; color: var(--imz-color-text-light, #888); font-size: 13px; line-height: 1.6; margin-bottom: 16px; }
    .imz-proc-terms-box::-webkit-scrollbar { width: 4px; }
    .imz-proc-terms-box::-webkit-scrollbar-thumb { background: #444; border-radius: 2px; }
    .imz-proc-terms-label { display: flex; align-items: center; justify-content: center; gap: 8px; font-size: 14px; color: var(--imz-color-text, #fff); cursor: pointer; margin-bottom: 18px; }
    .imz-proc-terms-label input { accent-color: #059669; width: 16px; height: 16px; }

    /* Button */
    .imz-proc-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 14px 32px;
        border: none;
        border-radius: 12px;
        font-size: 15px;
        font-weight: 700;
        cursor: pointer;
        text-transform: uppercase;
        letter-spacing: 0.6px;
        transition: all 0.25s ease;
        text-decoration: none !important;
        color: #000 !important;
        background: linear-gradient(135deg, #ffffff, #e5e7eb);
    }
    .imz-proc-btn:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(255,255,255,0.15); }
    .imz-proc-btn:disabled { opacity: 0.4; cursor: not-allowed; transform: none !important; box-shadow: none !important; }
    .imz-proc-btn svg { width: 18px; height: 18px; stroke: currentColor; fill: none; stroke-width: 2.5; }
    .imz-proc-btn.green { background: linear-gradient(135deg, #10b981, #059669); color: #fff !important; }
    .imz-proc-btn.green:hover { box-shadow: 0 6px 20px rgba(16,185,129,0.3); }

    /* Ad zone */
    .imz-proc-ad-zone {
        padding: 20px 28px;
        border-top: 1px solid var(--imz-border-color, #2a2a2a);
        text-align: center;
    }
    .imz-proc-ad-label { font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: var(--imz-color-text-light, #555); margin-bottom: 12px; }

    /* Footer */
    .imz-proc-footer {
        padding: 14px 28px;
        border-top: 1px solid var(--imz-border-color, #2a2a2a);
        text-align: center;
    }
    .imz-proc-footer a { font-size: 13px; color: var(--imz-color-text-light, #666); text-decoration: none; }
    .imz-proc-footer a:hover { color: var(--imz-color-text, #fff); }

    /* Step visibility */
    .imz-proc-step { display: none; animation: imzProcFade 0.4s ease; }
    .imz-proc-step.active { display: block; }
    @keyframes imzProcFade { from { opacity:0; transform:translateY(10px); } to { opacity:1; transform:translateY(0); } }

    @media (max-width: 480px) {
        .imz-proc { margin: 20px auto; }
        .imz-proc-content { padding: 24px 20px 20px; }
        .imz-proc-ad-zone { padding: 16px 20px; }
    }
    </style>

    <div class="imz-proc">
        <div class="imz-proc-card">
            <!-- Step indicator dots -->
            <div class="imz-proc-steps-bar">
                <div class="imz-proc-step-dot active" data-step="1"></div>
                <div class="imz-proc-step-dot" data-step="2"></div>
                <?php if ($terms) : ?><div class="imz-proc-step-dot" data-step="3"></div><?php endif; ?>
                <?php if ($enable_captcha_setting) : ?><div class="imz-proc-step-dot" data-step="4"></div><?php endif; ?>
                <div class="imz-proc-step-dot" data-step="5"></div>
                <div class="imz-proc-step-dot" data-step="6"></div>
            </div>

            <div class="imz-proc-content">
                <!-- STEP 1: Verificação -->
                <div class="imz-proc-step active" id="imz-step-verifying">
                    <div class="imz-proc-icon loading">
                        <span class="imz-proc-spinner-ring"></span>
                    </div>
                    <h3>A verificar...</h3>
                    <p class="imz-proc-music-name">Música: <strong><?php echo esc_html($music_title); ?></strong></p>
                    <div class="imz-proc-progress"><div class="imz-proc-progress-fill" id="imz-progress-bar"></div></div>
                    <p class="imz-proc-progress-text" id="imz-progress-text">A iniciar...</p>
                </div>

                <!-- STEP 2: Countdown / espera com anúncio -->
                <div class="imz-proc-step" id="imz-step-wait">
                    <div class="imz-proc-icon wait">
                        <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                    </div>
                    <h3>Aguarde um momento</h3>
                    <p class="imz-proc-desc">O seu download estará pronto em breve. Enquanto espera, conheça os nossos parceiros.</p>
                    <div class="imz-proc-countdown" id="imz-countdown">
                        <div class="imz-proc-countdown-ring"></div>
                        <span id="imz-countdown-number"><?php echo $wait_seconds; ?></span>
                    </div>
                </div>

                <!-- STEP 3: Termos -->
                <?php if ($terms) : ?>
                <div class="imz-proc-step" id="imz-step-terms">
                    <div class="imz-proc-icon terms">
                        <svg viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
                    </div>
                    <h3>Termos de Uso</h3>
                    <p class="imz-proc-desc">Leia e aceite os termos para prosseguir.</p>
                    <div class="imz-proc-terms-box"><?php echo wp_kses_post($terms); ?></div>
                    <label class="imz-proc-terms-label"><input type="checkbox" id="imz-terms-checkbox"> Eu li e concordo com os termos</label>
                    <button id="imz-terms-continue-btn" class="imz-proc-btn" disabled>Continuar</button>
                </div>
                <?php endif; ?>

                <!-- STEP 4: reCAPTCHA -->
                <?php if ($enable_captcha_setting) : ?>
                <div class="imz-proc-step" id="imz-step-captcha">
                    <div class="imz-proc-icon shield">
                        <svg viewBox="0 0 24 24"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                    </div>
                    <h3>Verificação de Segurança</h3>
                    <p class="imz-proc-desc">Complete a verificação para confirmar que não é um robô.</p>
                    <form id="imz-captcha-form" onsubmit="return false;">
                        <?php if (!empty($site_key)): ?>
                            <div id="imz-download-recaptcha" class="g-recaptcha" data-sitekey="<?php echo esc_attr($site_key); ?>" style="display: inline-block; margin-bottom: 20px;"></div>
                        <?php else: ?>
                            <p style="color: #ef4444;">reCAPTCHA não configurado.</p>
                        <?php endif; ?>
                        <br>
                        <button type="submit" class="imz-proc-btn" <?php disabled(empty($site_key)); ?>>Verificar</button>
                    </form>
                </div>
                <?php endif; ?>

                <!-- STEP 5: Sucesso -->
                <div class="imz-proc-step" id="imz-step-download">
                    <div class="imz-proc-icon success">
                        <svg viewBox="0 0 24 24"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                    </div>
                    <h3>Download Pronto!</h3>
                    <p class="imz-proc-desc">O ficheiro foi preparado com sucesso. Clique abaixo para iniciar o download.</p>
                    <a href="<?php echo esc_url($secure_link); ?>" class="imz-proc-btn green">
                        <svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                        Baixar Agora
                    </a>
                </div>

                <div id="imz-download-messages" style="margin-top: 16px;"></div>
            </div>

            <!-- Recomendação -->
            <div style="padding: 0 28px 8px; border-top: 1px solid var(--imz-border-color, #2a2a2a);">
                <?php echo imz_render_recommendation_buttons($post_id, 'download'); ?>
            </div>

            <!-- Ad zone -->
            <div class="imz-proc-ad-zone">
                <p class="imz-proc-ad-label">Parceiros</p>
                <?php echo do_shortcode('[imz_anuncios tipo="banner" max="1" layout="horizontal" excluir_musica="' . $post_id . '"]'); ?>
            </div>

            <!-- Footer -->
            <div class="imz-proc-footer">
                <a href="#" id="imz-open-report-modal">⚠️ Encontrou um problema? Relatar</a>
            </div>
        </div>
    </div>

    <?php
    // Modal de reporte
    if (function_exists('imz_get_report_modal_html')) {
        echo imz_get_report_modal_html($post_id);
    }

    // Pass wait seconds to JS
    echo '<script>var imzWaitSeconds = ' . $wait_seconds . ';</script>';

    return ob_get_clean();
}


// =============================================================================
// VERIFICAÇÃO AJAX (USANDO TRANSIENT)
// =============================================================================

add_action('wp_ajax_imz_verify_download_recaptcha', 'imz_ajax_verify_download_recaptcha');
add_action('wp_ajax_nopriv_imz_verify_download_recaptcha', 'imz_ajax_verify_download_recaptcha');

function imz_ajax_verify_download_recaptcha() {
    check_ajax_referer('imz_verify_captcha_nonce', 'nonce');
    $recaptcha_response = isset($_POST['g-recaptcha-response']) ? sanitize_text_field($_POST['g-recaptcha-response']) : '';

    if (!function_exists('imz_verify_recaptcha') || !imz_verify_recaptcha($recaptcha_response)) {
        wp_send_json_error(['message' => 'Falha na verificação reCAPTCHA. Por favor, tente novamente.']);
        return;
    } else {
        // Define transient de verificação (válido por 60s)
        $user_fingerprint = imz_get_user_fingerprint();
        $transient_key = 'imz_captcha_verified_' . md5($user_fingerprint);
        set_transient($transient_key, true, 60);
        wp_send_json_success();
    }
    wp_die();
}


// =============================================================================
// PROCESSAMENTO FINAL DO DOWNLOAD (DB OTIMIZADA)
// =============================================================================

add_action('init', 'imz_handle_final_secure_download');
function imz_handle_final_secure_download() {
    if (isset($_GET['download_key'])) {
        $token = sanitize_key($_GET['download_key']);
        $transient_data = get_transient('imz_final_token_' . $token);
        $post_id = false;
        $download_source = 'unknown';

        if (is_array($transient_data) && isset($transient_data['music_id'])) {
            $post_id = $transient_data['music_id'];
            $download_source = $transient_data['source'] ?? 'free';
        } elseif (is_numeric($transient_data)) {
            $post_id = $transient_data;
            $download_source = 'free';
        }

        if (false === $post_id) { wp_die('Link de download inválido ou expirado.'); }
        delete_transient('imz_final_token_' . $token);

        // Verifica Transient do Captcha (Se aplicável)
        if ($download_source !== 'paid' && get_option('imz_enable_download_captcha')) {
            $user_fingerprint = imz_get_user_fingerprint();
            $transient_key = 'imz_captcha_verified_' . md5($user_fingerprint);
            if (false === get_transient($transient_key)) {
                wp_die('Verificação de segurança falhou ou expirou. Por favor, complete todos os passos novamente.');
            }
            delete_transient($transient_key);
        }

        // --- GRAVAÇÃO NA TABELA PERSONALIZADA (Otimizado) ---
        global $wpdb;
        $restriction_level = get_option('imz_download_restriction_level', 'ip_only');

        if ($download_source === 'paid' || $restriction_level !== 'none') {
            $user_ip = imz_get_user_ip();
            $user_agent = imz_get_user_agent();

            // Geolocalização
            $location_data = ['country' => '', 'region' => ''];
            $response = wp_remote_get("http://ip-api.com/json/{$user_ip}?fields=status,countryCode,regionName");
            if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
                $data = json_decode(wp_remote_retrieve_body($response), true);
                if ($data && $data['status'] === 'success') {
                    $location_data['country'] = $data['countryCode'] ?? '';
                    $location_data['region'] = $data['regionName'] ?? '';
                }
            }

            // Inserção na tabela wp_imz_analytics
            $wpdb->insert(
                $wpdb->prefix . 'imz_analytics',
                [
                    'music_id' => $post_id,
                    'user_ip' => $user_ip,
                    'user_agent' => substr($user_agent, 0, 255),
                    'country' => $location_data['country'],
                    'region' => $location_data['region'],
                    'source' => $download_source,
                    'download_date' => current_time('mysql')
                ],
                ['%d', '%s', '%s', '%s', '%s', '%s', '%s']
            );

            // Cookie de restrição
            if ($download_source !== 'paid' && $restriction_level !== 'none') {
                 setcookie('imz_downloaded_' . $post_id, '1', time() + (86400 * 365), "/");
            }
        }

        // Incrementa Contadores
        $total_count = (int) get_post_meta($post_id, '_imz_download_count', true);
        update_post_meta($post_id, '_imz_download_count', $total_count + 1);

        // HOOK: Notifica o sistema de monetização por engajamento
        do_action('imz_download_completed', $post_id, $download_source);

        $daily_limit_per_post = get_post_meta($post_id, '_imz_daily_download_limit', true);
        $daily_limit = (is_numeric($daily_limit_per_post) && $daily_limit_per_post !== '') ? (int)$daily_limit_per_post : (int)get_option('imz_download_limit', 0);
        if ($daily_limit > 0) {
            $today = date('Y-m-d');
            $transient_key = 'imz_daily_downloads_' . $post_id . '_' . $today;
            $daily_count = (int) get_transient($transient_key);
            set_transient($transient_key, $daily_count + 1, DAY_IN_SECONDS);
        }

        // Entrega do Ficheiro
        $file_source_type = get_post_meta($post_id, '_imz_file_source_type', true);
        if ($file_source_type === 'url') {
             $file_url = get_post_meta($post_id, '_imz_download_file_url', true);
             if(empty($file_url)) wp_die('Ficheiro não encontrado.');
             wp_redirect($file_url);
             exit;
        } else {
             $file_id = get_post_meta($post_id, '_imz_download_file_id', true);
             $file_path = get_attached_file($file_id);
             if(empty($file_id) || !$file_path || !file_exists($file_path)) wp_die('Ficheiro não encontrado.');

             header('Content-Description: File Transfer');
             header('Content-Type: application/octet-stream');
             header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
             header('Expires: 0');
             header('Cache-Control: must-revalidate');
             header('Pragma: public');
             header('Content-Length: ' . filesize($file_path));

             @ob_end_clean();
             flush();
             readfile($file_path);
             exit;
        }
    }
}
?>