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

// =============================================================================
// 1. REGISTO DA PÁGINA DE ADMINISTRAÇÃO (Para substituir o menu de CPT)
// =============================================================================
add_action('admin_menu', 'imz_register_purchases_page');
function imz_register_purchases_page() {
    add_submenu_page(
        imz_admin_parent_slug(),
        'Vendas de Músicas (DB)',
        'Vendas de Músicas',
        'manage_options',
        'imz_purchases_manager',
        'imz_render_purchases_manager_page'
    );
}

// =============================================================================
// 2. SHORTCODE E FRONTEND [imz_purchase_flow] (Mantido visualmente igual)
// =============================================================================
add_shortcode('imz_purchase_flow', 'imz_render_purchase_flow_shortcode');
function imz_render_purchase_flow_shortcode() {
    if (!isset($_GET['music_id'])) return '<div class="imz-processing-message error">Música não especificada.</div>';
    
    $music_id = absint($_GET['music_id']);
    $music_post = get_post($music_id);
    
    if (!$music_post || $music_post->post_type !== 'post') return '<div class="imz-processing-message error">Música inválida.</div>';
    
    $is_paid_download_active = get_post_meta($music_id, '_imz_enable_paid_download', true) === 'yes';
    $artist_id = $music_post->post_author;
    $is_pro = function_exists('imz_is_artist_pro') ? imz_is_artist_pro($artist_id) : false;

    if (!$is_paid_download_active || !$is_pro) {
         return '<div class="imz-processing-message warning">Esta música não está disponível para compra neste momento.</div>';
    }

    $price = get_post_meta($music_id, '_imz_paid_download_price', true);
    $price_text = !empty($price) ? esc_html($price) . ' MT' : '';
    $site_key = get_option('imz_recaptcha_site_key');
    $thumbnail = get_the_post_thumbnail_url($music_id, 'medium');
    $artist_name = get_the_author_meta('display_name', $artist_id);

    // Remover selo do título
    remove_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);
    $music_title = get_the_title($music_id);
    add_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);

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

    /* --- Header com capa da música --- */
    .imz-pf-header {
        text-align: center;
        padding: 32px 24px 24px;
        background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
        border-radius: 16px 16px 0 0;
        position: relative;
        overflow: hidden;
    }
    .imz-pf-header::before {
        content: '';
        position: absolute;
        inset: 0;
        background: radial-gradient(circle at 30% 20%, rgba(255,255,255,0.05) 0%, transparent 60%);
    }
    .imz-pf-thumb {
        width: 88px;
        height: 88px;
        border-radius: 14px;
        object-fit: cover;
        box-shadow: 0 8px 24px rgba(0,0,0,0.4);
        margin-bottom: 14px;
        border: 3px solid rgba(255,255,255,0.15);
        position: relative;
    }
    .imz-pf-no-thumb {
        width: 88px;
        height: 88px;
        border-radius: 14px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        display: inline-flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 14px;
        box-shadow: 0 8px 24px rgba(0,0,0,0.4);
        border: 3px solid rgba(255,255,255,0.15);
    }
    .imz-pf-no-thumb svg { width: 36px; height: 36px; fill: rgba(255,255,255,0.8); }
    .imz-pf-title {
        font-size: 20px;
        font-weight: 700;
        color: #ffffff;
        margin: 0 0 4px 0;
        position: relative;
    }
    .imz-pf-artist {
        font-size: 14px;
        color: rgba(255,255,255,0.6);
        margin: 0 0 12px 0;
        position: relative;
    }
    .imz-pf-price-tag {
        display: inline-block;
        background: rgba(16, 185, 129, 0.15);
        border: 1px solid rgba(16, 185, 129, 0.3);
        color: #34d399;
        font-size: 18px;
        font-weight: 800;
        padding: 6px 20px;
        border-radius: 50px;
        position: relative;
    }

    /* --- Corpo / opções --- */
    .imz-pf-body {
        background: var(--imz-color-background-soft, #1a1a1a);
        border: 1px solid var(--imz-border-color, #2a2a2a);
        border-top: none;
        border-radius: 0 0 16px 16px;
        padding: 24px;
    }

    /* --- Botões de opção (tab-style) --- */
    .imz-pf-tabs {
        display: flex;
        gap: 8px;
        margin-bottom: 24px;
    }
    .imz-pf-tab {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 6px;
        padding: 14px 8px;
        background: var(--imz-color-background, #141414);
        border: 2px solid var(--imz-border-color, #2a2a2a);
        border-radius: 12px;
        cursor: pointer;
        transition: all 0.25s ease;
        color: var(--imz-color-text-light, #888);
        font-size: 11px;
        font-weight: 600;
        text-align: center;
        line-height: 1.3;
    }
    .imz-pf-tab:hover {
        border-color: rgba(255,255,255,0.15);
        color: var(--imz-color-text, #fff);
    }
    .imz-pf-tab.active {
        border-color: #10b981;
        background: rgba(16, 185, 129, 0.06);
        color: #10b981;
        box-shadow: 0 0 0 1px rgba(16,185,129,0.15);
    }
    .imz-pf-tab-icon {
        width: 28px;
        height: 28px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: var(--imz-border-color, #2a2a2a);
        transition: background 0.25s;
    }
    .imz-pf-tab.active .imz-pf-tab-icon {
        background: rgba(16,185,129,0.15);
    }
    .imz-pf-tab-icon svg {
        width: 16px;
        height: 16px;
        stroke: currentColor;
        fill: none;
        stroke-width: 2;
        stroke-linecap: round;
        stroke-linejoin: round;
    }

    /* --- Painéis de formulário --- */
    .imz-pf-panel {
        display: none;
        animation: imzPfFadeIn 0.3s ease;
    }
    .imz-pf-panel.active { display: block; }
    @keyframes imzPfFadeIn {
        from { opacity: 0; transform: translateY(8px); }
        to { opacity: 1; transform: translateY(0); }
    }

    .imz-pf-panel .imz-form-group { margin-bottom: 18px; }
    .imz-pf-panel .imz-form-group label {
        display: block;
        font-size: 13px;
        font-weight: 600;
        margin-bottom: 6px;
        color: var(--imz-color-text, #fff);
    }
    .imz-pf-panel input[type="text"],
    .imz-pf-panel input[type="tel"],
    .imz-pf-panel input[type="url"] {
        width: 100%;
        padding: 12px 16px;
        border: 1px solid var(--imz-border-color, #2a2a2a);
        border-radius: 10px;
        background: var(--imz-color-background, #141414);
        color: var(--imz-color-text, #fff);
        font-size: 15px;
        box-sizing: border-box;
        transition: border-color 0.2s, box-shadow 0.2s;
    }
    .imz-pf-panel input:focus {
        outline: none;
        border-color: #10b981;
        box-shadow: 0 0 0 3px rgba(16,185,129,0.12);
    }

    /* --- Code input especial --- */
    .imz-pf-code-input {
        text-align: center !important;
        font-size: 28px !important;
        font-weight: 700 !important;
        letter-spacing: 8px !important;
        padding: 16px !important;
        font-family: 'SF Mono', 'Consolas', 'Courier New', monospace !important;
    }
    .imz-pf-verify-input {
        text-align: center !important;
        font-size: 20px !important;
        font-weight: 600 !important;
        letter-spacing: 4px !important;
        text-transform: uppercase !important;
        font-family: 'SF Mono', 'Consolas', 'Courier New', monospace !important;
    }

    /* --- Info box --- */
    .imz-pf-info {
        display: flex;
        align-items: flex-start;
        gap: 10px;
        padding: 12px 14px;
        background: rgba(59, 130, 246, 0.08);
        border: 1px solid rgba(59, 130, 246, 0.15);
        border-radius: 10px;
        margin-bottom: 20px;
        font-size: 13px;
        line-height: 1.5;
        color: var(--imz-color-text-light, #888);
    }
    .imz-pf-info-icon {
        flex-shrink: 0;
        width: 18px;
        height: 18px;
        margin-top: 1px;
        stroke: #60a5fa;
        fill: none;
        stroke-width: 2;
    }

    /* --- Submit button override --- */
    .imz-pf-panel .imz-pf-submit {
        width: 100%;
        padding: 14px 24px;
        border: none;
        border-radius: 12px;
        font-size: 15px;
        font-weight: 700;
        cursor: pointer;
        transition: all 0.25s ease;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
    }
    .imz-pf-submit-buy {
        background: linear-gradient(135deg, #10b981, #059669);
        color: #fff;
    }
    .imz-pf-submit-buy:hover { box-shadow: 0 6px 20px rgba(16,185,129,0.35); transform: translateY(-1px); }
    .imz-pf-submit-code {
        background: linear-gradient(135deg, #3b82f6, #2563eb);
        color: #fff;
    }
    .imz-pf-submit-code:hover { box-shadow: 0 6px 20px rgba(59,130,246,0.35); transform: translateY(-1px); }
    .imz-pf-submit-verify {
        background: linear-gradient(135deg, #8b5cf6, #7c3aed);
        color: #fff;
    }
    .imz-pf-submit-verify:hover { box-shadow: 0 6px 20px rgba(139,92,246,0.35); transform: translateY(-1px); }
    .imz-pf-submit:disabled {
        opacity: 0.5;
        cursor: not-allowed;
        transform: none !important;
        box-shadow: none !important;
    }
    .imz-pf-submit svg {
        width: 18px;
        height: 18px;
        stroke: currentColor;
        fill: none;
        stroke-width: 2;
    }

    /* --- Messages / Results --- */
    .imz-pf-messages { margin-top: 16px; }

    .imz-pf-result {
        margin-top: 20px;
        padding: 18px;
        border-radius: 12px;
        background: rgba(16,185,129,0.06);
        border: 1px solid rgba(16,185,129,0.15);
    }
    .imz-pf-result-row {
        display: flex;
        justify-content: space-between;
        padding: 6px 0;
        font-size: 14px;
    }
    .imz-pf-result-label { color: var(--imz-color-text-light, #888); }
    .imz-pf-result-value { color: var(--imz-color-text, #fff); font-weight: 600; }

    @media (max-width: 480px) {
        .imz-pf-tabs { flex-direction: column; }
        .imz-pf-tab { flex-direction: row; padding: 12px 14px; font-size: 13px; }
        .imz-pf-code-input { font-size: 22px !important; letter-spacing: 5px !important; }
    }
    </style>

    <div class="imz-pf imz-purchase-flow-container">
        <!-- Header com capa -->
        <div class="imz-pf-header">
            <?php if ($thumbnail) : ?>
                <img src="<?php echo esc_url($thumbnail); ?>" alt="" class="imz-pf-thumb">
            <?php else : ?>
                <div class="imz-pf-no-thumb">
                    <svg viewBox="0 0 24 24"><path d="M9 18V5l12-2v13M9 18a3 3 0 1 1-6 0 3 3 0 0 1 6 0zm12-2a3 3 0 1 1-6 0 3 3 0 0 1 6 0z"/></svg>
                </div>
            <?php endif; ?>
            <p class="imz-pf-title"><?php echo esc_html($music_title); ?></p>
            <p class="imz-pf-artist"><?php echo esc_html($artist_name); ?></p>
            <?php if ($price_text) : ?>
                <span class="imz-pf-price-tag"><?php echo $price_text; ?></span>
            <?php endif; ?>
        </div>

        <!-- Body -->
        <div class="imz-pf-body">
            <!-- Tabs -->
            <div class="imz-pf-tabs">
                <button class="imz-pf-tab active" data-panel="buy" id="imz-show-buy-form">
                    <span class="imz-pf-tab-icon">
                        <svg viewBox="0 0 24 24"><path d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.3 2.3c-.6.6-.2 1.7.7 1.7H17m0 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-8 2a2 2 0 1 0 0 4 2 2 0 0 0 0-4z"/></svg>
                    </span>
                    Comprar
                </button>
                <button class="imz-pf-tab" data-panel="code" id="imz-show-code-form">
                    <span class="imz-pf-tab-icon">
                        <svg viewBox="0 0 24 24"><path d="M7 8l-4 4 4 4m10-8l4 4-4 4M14 4l-4 16"/></svg>
                    </span>
                    Código
                </button>
                <button class="imz-pf-tab" data-panel="verify" id="imz-show-verify-form">
                    <span class="imz-pf-tab-icon">
                        <svg viewBox="0 0 24 24"><path d="M9 12l2 2 4-4m5.6 2A9 9 0 1 1 12 3a9 9 0 0 1 8.6 9z"/></svg>
                    </span>
                    Verificar
                </button>
            </div>

            <!-- Painel 1: Comprar -->
            <div class="imz-pf-panel active" id="imz-buy-panel">
                <form id="imz-buy-request-form">
                    <?php wp_nonce_field('imz_request_purchase_code_nonce', 'imz_purchase_nonce'); ?>
                    <input type="hidden" name="music_id" value="<?php echo esc_attr($music_id); ?>">
                    <div class="imz-form-group">
                        <label for="user_name">Seu Nome</label>
                        <input type="text" name="user_name" id="user_name" required placeholder="Como quer ser contactado?">
                    </div>
                    <div class="imz-form-group">
                        <label for="user_phone">Número WhatsApp / SMS</label>
                        <input type="tel" name="user_phone" id="user_phone" required maxlength="9" pattern="[0-9]{9}" title="9 dígitos" placeholder="84 000 0000">
                    </div>
                    <div class="imz-pf-info">
                        <svg class="imz-pf-info-icon" viewBox="0 0 24 24"><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>A equipa do artista irá contactá-lo(a) para combinar o pagamento de <strong><?php echo $price_text; ?></strong>.</span>
                    </div>
                    <?php if (!empty($site_key)): ?>
                        <div class="imz-form-group imz-form-group-center">
                            <div id="imz-purchase-request-recaptcha" class="g-recaptcha" data-sitekey="<?php echo esc_attr($site_key); ?>"></div>
                        </div>
                    <?php endif; ?>
                    <button type="submit" class="imz-pf-submit imz-pf-submit-buy" <?php disabled(empty($site_key)); ?>>
                        <svg viewBox="0 0 24 24"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>
                        Contactem-me
                    </button>
                </form>
            </div>

            <!-- Painel 2: Introduzir Código -->
            <div class="imz-pf-panel" id="imz-code-panel">
                <form id="imz-use-code-form">
                    <?php wp_nonce_field('imz_validate_purchase_code_nonce', 'imz_validate_nonce'); ?>
                    <input type="hidden" name="music_id" value="<?php echo esc_attr($music_id); ?>">
                    <div class="imz-form-group">
                        <label for="download_code">Código de 6 Dígitos</label>
                        <input type="text" name="download_code" id="download_code" required maxlength="6" pattern="[0-9]{6}" class="imz-pf-code-input" placeholder="000000">
                    </div>
                    <?php if (!empty($site_key)): ?>
                        <div class="imz-form-group imz-form-group-center">
                            <div id="imz-purchase-code-recaptcha" class="g-recaptcha" data-sitekey="<?php echo esc_attr($site_key); ?>"></div>
                        </div>
                    <?php endif; ?>
                    <button type="submit" class="imz-pf-submit imz-pf-submit-code" <?php disabled(empty($site_key)); ?>>
                        <svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>
                        Baixar Música
                    </button>
                </form>
            </div>

            <!-- Painel 3: Verificar Artista -->
            <div class="imz-pf-panel" id="imz-verify-panel">
                <form id="imz-verify-artist-form">
                    <?php wp_nonce_field('imz_verify_artist_code_nonce', 'imz_verify_nonce_field'); ?>
                    <div class="imz-pf-info">
                        <svg class="imz-pf-info-icon" viewBox="0 0 24 24"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                        <span>Peça o código de verificação à pessoa que o contactou para confirmar que é o artista real.</span>
                    </div>
                    <div class="imz-form-group">
                        <label for="verification_code">Código de Verificação (9 caracteres)</label>
                        <input type="text" name="verification_code" id="verification_code" required maxlength="9" class="imz-pf-verify-input" placeholder="XXXXXXXXX">
                    </div>
                    <button type="submit" class="imz-pf-submit imz-pf-submit-verify">
                        <svg viewBox="0 0 24 24"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14M22 4L12 14.01l-3-3"/></svg>
                        Verificar Identidade
                    </button>
                    <div id="imz-verification-results" class="imz-pf-result" style="display: none;"></div>
                </form>
            </div>

            <div id="imz-purchase-messages" class="imz-pf-messages"></div>
        </div>
    </div>

    <script>
    (function(){
        var tabs = document.querySelectorAll('.imz-pf-tab');
        var panels = document.querySelectorAll('.imz-pf-panel');
        tabs.forEach(function(tab) {
            tab.addEventListener('click', function() {
                var target = this.getAttribute('data-panel');
                tabs.forEach(function(t) { t.classList.remove('active'); });
                panels.forEach(function(p) { p.classList.remove('active'); });
                this.classList.add('active');
                var panel = document.getElementById('imz-' + target + '-panel');
                if (panel) panel.classList.add('active');
                var msg = document.getElementById('imz-purchase-messages');
                if (msg) msg.innerHTML = '';
                var vr = document.getElementById('imz-verification-results');
                if (vr) vr.style.display = 'none';
            });
        });
    })();
    </script>
    <?php
    return ob_get_clean();
}

// =============================================================================
// 3. HANDLERS AJAX (ATUALIZADOS PARA SQL)
// =============================================================================

// Criar Pedido (Form 1)
add_action('wp_ajax_imz_request_purchase_code', 'imz_ajax_request_purchase_code');
add_action('wp_ajax_nopriv_imz_request_purchase_code', 'imz_ajax_request_purchase_code');
function imz_ajax_request_purchase_code() {
    check_ajax_referer('imz_request_purchase_code_nonce', 'imz_purchase_nonce');

    // ReCAPTCHA Check
    if (function_exists('imz_verify_recaptcha')) {
        $recaptcha_response = isset($_POST['g-recaptcha-response']) ? sanitize_text_field($_POST['g-recaptcha-response']) : '';
        if (!imz_verify_recaptcha($recaptcha_response)) {
            wp_send_json_error(['message' => 'Falha na verificação reCAPTCHA.']);
            return;
        }
    }

    $music_id = isset($_POST['music_id']) ? absint($_POST['music_id']) : 0;
    $user_name = isset($_POST['user_name']) ? sanitize_text_field($_POST['user_name']) : '';
    $user_phone = isset($_POST['user_phone']) ? sanitize_text_field($_POST['user_phone']) : '';

    if (empty($music_id) || empty($user_name) || !preg_match('/^[0-9]{9}$/', $user_phone)) {
        wp_send_json_error(['message' => 'Preencha todos os campos. O número deve ter 9 dígitos.']);
    }

    // Anti-duplicação (Transient)
    if (function_exists('imz_get_user_fingerprint')) {
        $transient_key = 'imz_dup_req_' . md5(imz_get_user_fingerprint() . '_' . $music_id);
        if (get_transient($transient_key)) {
            wp_send_json_error(['message' => 'Já enviou um pedido recentemente. Aguarde o contacto.']);
            return;
        }
    }

    $music_post = get_post($music_id);
    if (!$music_post) wp_send_json_error(['message' => 'Música não encontrada.']);

    $artist_id = $music_post->post_author;
    $verification_code = strtoupper(wp_generate_password(9, false, false));
    
    // INSERIR NA TABELA SQL
    global $wpdb;
    $table_name = $wpdb->prefix . 'imz_purchases';
    
    $inserted = $wpdb->insert(
        $table_name,
        [
            'music_id' => $music_id,
            'artist_id' => $artist_id,
            'user_name' => $user_name,
            'user_phone' => $user_phone,
            'status' => 'pendente',
            'verification_code' => $verification_code,
            'price' => 0.00, // Será atualizado quando o artista confirmar
            'date' => current_time('mysql')
        ],
        ['%d', '%d', '%s', '%s', '%s', '%s', '%f', '%s']
    );

    if ($inserted) {
        if (function_exists('imz_get_user_fingerprint')) {
            set_transient($transient_key, true, HOUR_IN_SECONDS);
        }
        // Limpa cache de notificações
        delete_transient('imz_pending_counts');
        wp_send_json_success(['message' => 'Pedido enviado! O artista irá contactá-lo(a).']);
    } else {
        wp_send_json_error(['message' => 'Erro ao gravar o pedido.']);
    }
    wp_die();
}

// Validar Código e Baixar (Form 2)
add_action('wp_ajax_imz_validate_purchase_code', 'imz_ajax_validate_purchase_code');
add_action('wp_ajax_nopriv_imz_validate_purchase_code', 'imz_ajax_validate_purchase_code');
function imz_ajax_validate_purchase_code() {
    check_ajax_referer('imz_validate_purchase_code_nonce', 'imz_validate_nonce');

    // ReCAPTCHA Check
    if (function_exists('imz_verify_recaptcha')) {
        $recaptcha_response = isset($_POST['g-recaptcha-response']) ? sanitize_text_field($_POST['g-recaptcha-response']) : '';
        if (!imz_verify_recaptcha($recaptcha_response)) {
            wp_send_json_error(['message' => 'Falha na verificação reCAPTCHA.']);
            return;
        }
    }

    $music_id = isset($_POST['music_id']) ? absint($_POST['music_id']) : 0;
    $download_code = isset($_POST['download_code']) ? sanitize_text_field($_POST['download_code']) : '';

    if (empty($music_id) || !preg_match('/^[0-9]{6}$/', $download_code)) {
        wp_send_json_error(['message' => 'Código inválido (deve ter 6 dígitos).']);
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'imz_purchases';

    // Verifica se existe um pedido CONCLUÍDO com este código para esta música
    $purchase = $wpdb->get_row($wpdb->prepare(
        "SELECT id FROM $table_name WHERE music_id = %d AND download_code = %s AND status = 'concluido'",
        $music_id, $download_code
    ));

    if ($purchase) {
        // Atualiza status para 'usado'
        $wpdb->update($table_name, ['status' => 'usado'], ['id' => $purchase->id]);

        // Gera link seguro
        $final_token = wp_generate_password(20, false);
        set_transient('imz_final_token_' . $final_token, ['music_id' => $music_id, 'source' => 'paid'], 5 * MINUTE_IN_SECONDS);
        $secure_link = add_query_arg(['download_key' => $final_token], home_url());

        wp_send_json_success(['message' => 'Código válido! A preparar download...', 'download_url' => $secure_link]);
    } else {
        wp_send_json_error(['message' => 'Código inválido, expirado ou já utilizado.']);
    }
    wp_die();
}

// Verificar Artista (Form 3)
add_action('wp_ajax_imz_verify_artist_code', 'imz_ajax_verify_artist_code');
add_action('wp_ajax_nopriv_imz_verify_artist_code', 'imz_ajax_verify_artist_code');
function imz_ajax_verify_artist_code() {
    check_ajax_referer('imz_verify_artist_code_nonce', 'imz_verify_nonce_field');
    $verification_code = isset($_POST['verification_code']) ? sanitize_text_field(strtoupper($_POST['verification_code'])) : '';

    if (strlen($verification_code) !== 9) wp_send_json_error(['message' => 'Código inválido.']);

    global $wpdb;
    $table_name = $wpdb->prefix . 'imz_purchases';

    // Procura pedido com este código que não esteja cancelado ou usado
    $purchase = $wpdb->get_row($wpdb->prepare(
        "SELECT music_id, artist_id FROM $table_name WHERE verification_code = %s AND status IN ('pendente', 'concluido')",
        $verification_code
    ));

    if ($purchase) {
        $music_title = get_the_title($purchase->music_id);
        $artist_name = get_the_author_meta('display_name', $purchase->artist_id);
        wp_send_json_success([
            'message' => 'Código válido! Está a falar com o representante correto.',
            'artist_name' => $artist_name,
            'music_title' => $music_title
        ]);
    } else {
        wp_send_json_error(['message' => 'Código não encontrado ou expirado.']);
    }
    wp_die();
}

// =============================================================================
// 4. RENDERIZAÇÃO DA PÁGINA DE ADMINISTRAÇÃO (Listagem)
// =============================================================================
function imz_render_purchases_manager_page() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'imz_purchases';
    
    // Filtro por status (opcional)
    $filter_status = isset($_GET['status']) ? sanitize_text_field($_GET['status']) : '';
    $where_clause = "";
    if ($filter_status) {
        $where_clause = $wpdb->prepare("WHERE status = %s", $filter_status);
    }

    // Paginação
    $per_page = 20;
    $page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
    $offset = ($page - 1) * $per_page;

    $total_items = $wpdb->get_var("SELECT COUNT(id) FROM $table_name $where_clause");
    $total_pages = ceil($total_items / $per_page);
    
    $results = $wpdb->get_results("SELECT * FROM $table_name $where_clause ORDER BY date DESC LIMIT $per_page OFFSET $offset");
    
    // Processar resets ou deletes
    if(isset($_GET['action']) && isset($_GET['pid']) && check_admin_referer('imz_admin_purchase_action')) {
        $pid = absint($_GET['pid']);
        if($_GET['action'] === 'reset') {
            $wpdb->update($table_name, ['status' => 'concluido'], ['id' => $pid]);
            echo '<div class="notice notice-success"><p>Código reiniciado.</p></div>';
        } elseif($_GET['action'] === 'delete') {
            $wpdb->delete($table_name, ['id' => $pid]);
            echo '<div class="notice notice-success"><p>Registo apagado.</p></div>';
        }
        // Refresh manual se necessário, ou apenas mostrar aviso
    }

    ?>
    <div class="wrap">
        <h1>Gestor de Vendas</h1>
        <ul class="subsubsub">
            <li><a href="?post_type=impulsionamento&page=imz_purchases_manager" class="<?php echo empty($filter_status) ? 'current' : ''; ?>">Tudo</a> |</li>
            <li><a href="?post_type=impulsionamento&page=imz_purchases_manager&status=pendente" class="<?php echo $filter_status=='pendente' ? 'current' : ''; ?>">Pendentes</a> |</li>
            <li><a href="?post_type=impulsionamento&page=imz_purchases_manager&status=concluido" class="<?php echo $filter_status=='concluido' ? 'current' : ''; ?>">Concluídos (Código Gerado)</a> |</li>
            <li><a href="?post_type=impulsionamento&page=imz_purchases_manager&status=usado" class="<?php echo $filter_status=='usado' ? 'current' : ''; ?>">Usados (Vendas)</a></li>
        </ul>
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th>Data</th>
                    <th>Música</th>
                    <th>Vendedor (Artista)</th>
                    <th>Comprador</th>
                    <th>Status</th>
                    <th>Preço</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($results): foreach ($results as $row): 
                    $artist = get_user_by('id', $row->artist_id);
                    $artist_name = $artist ? $artist->display_name : 'Desconhecido';
                    $music_title = get_the_title($row->music_id) ?: '(Apagada)';
                ?>
                <tr>
                    <td><?php echo date('d/m/Y H:i', strtotime($row->date)); ?></td>
                    <td><a href="<?php echo get_edit_post_link($row->music_id); ?>"><?php echo esc_html($music_title); ?></a></td>
                    <td><?php echo esc_html($artist_name); ?></td>
                    <td>
                        <?php echo esc_html($row->user_name); ?><br>
                        <small><?php echo esc_html($row->user_phone); ?></small>
                    </td>
                    <td><strong><?php echo ucfirst($row->status); ?></strong></td>
                    <td><?php echo number_format($row->price, 2); ?> MT</td>
                    <td>
                        <?php $nonce_url = wp_nonce_url("?post_type=impulsionamento&page=imz_purchases_manager&pid={$row->id}", 'imz_admin_purchase_action'); ?>
                        <?php if($row->status === 'usado'): ?>
                            <a href="<?php echo $nonce_url . '&action=reset'; ?>" class="button button-small">Reiniciar</a>
                        <?php endif; ?>
                        <a href="<?php echo $nonce_url . '&action=delete'; ?>" class="button button-small button-link-delete" onclick="return confirm('Apagar permanentemente?');">Apagar</a>
                    </td>
                </tr>
                <?php endforeach; else: ?>
                    <tr><td colspan="7">Nenhuma venda encontrada.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
        <?php if ($total_pages > 1): ?>
            <div class="tablenav bottom"><div class="tablenav-pages"><?php echo paginate_links(['base' => add_query_arg('paged', '%#%'), 'total' => $total_pages, 'current' => $page]); ?></div></div>
        <?php endif; ?>
    </div>
    <?php
}
?>
