<?php
/**
 * [1.6.117] PEDIDOS DE REMOÇÃO DE CONTENT ID — FRONTEND
 *
 * Função para renderizar a secção no detalhe do release (no site).
 * Apenas aparece em releases LIVE/distribuido.
 *
 * Handler AJAX para submeter pedido (e listar pedidos prévios desse
 * artista para esse release).
 *
 * @package 1MZ_For_Artists
 * @since 1.6.117
 */

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


/**
 * [1.6.117.8] Renderiza UI INLINE DENTRO do card YouTube Content ID.
 *
 *   - Botão pequeno "Pedir remoção de claim"
 *   - Secção expansível com histórico (clica para mostrar/esconder)
 *
 * O MODAL é renderizado em separado por `rmbz_contentid_render_section()`
 * (compatibilidade) — basta chamar essa 1× no fim da página.
 *
 * Chamada esperada DENTRO do bloco `elseif ( $status === 'approved' )`
 * do serviço 'yt_content_id' em distribution-single-view.php.
 *
 * @param object $release Linha de rmbz_distro_releases
 */
function rmbz_contentid_render_inline( $release ) {
    if ( ! $release || empty( $release->id ) ) return;
    if ( ! rmbz_contentid_release_is_in_content_id( (int) $release->id ) ) return;

    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_contentid_requests';
    $prior_requests = [];
    if ( $wpdb->get_var( "SHOW TABLES LIKE '$t'" ) === $t ) {
        $prior_requests = $wpdb->get_results( $wpdb->prepare(
            "SELECT id, video_url, status, created_at, processed_at, admin_response
               FROM $t
              WHERE release_id = %d AND artist_telemovel = %s
              ORDER BY id DESC
              LIMIT 10",
            (int) $release->id, $release->artist_telemovel
        ) );
    }
    $count = count( $prior_requests );
    $uid = (int) $release->id;
    ?>

    <div class="rmbz-cid-inline">
        <div class="rmbz-cid-inline-actions">
            <button type="button" class="rmbz-cid-inline-btn" onclick="rmbzCidOpenModal()">
                ➕ Pedir remoção de claim
            </button>
            <?php if ( $count > 0 ): ?>
                <button type="button"
                        class="rmbz-cid-inline-toggle"
                        onclick="rmbzCidToggleHistory(<?php echo $uid; ?>)"
                        aria-expanded="false"
                        id="rmbz-cid-toggle-<?php echo $uid; ?>">
                    Ver histórico (<?php echo $count; ?>) <span class="rmbz-cid-arrow">▾</span>
                </button>
            <?php endif; ?>
        </div>

        <?php if ( $count > 0 ): ?>
            <div class="rmbz-cid-history" id="rmbz-cid-history-<?php echo $uid; ?>" style="display:none;">
                <?php foreach ( $prior_requests as $pr ):
                    $st_class = $pr->status;
                    $when = human_time_diff( strtotime( $pr->created_at ), time() );
                ?>
                    <div class="rmbz-cid-history-item rmbz-cid-st-<?php echo esc_attr( $st_class ); ?>">
                        <div class="rmbz-cid-history-main">
                            <a href="<?php echo esc_url( $pr->video_url ); ?>" target="_blank" rel="noopener">
                                <?php echo esc_html( wp_trim_words( $pr->video_url, 8, '...' ) ); ?>
                            </a>
                            <div class="rmbz-cid-history-meta">
                                há <?php echo esc_html( $when ); ?>
                                <?php if ( ! empty( $pr->admin_response ) ): ?>
                                    · <em>"<?php echo esc_html( wp_trim_words( $pr->admin_response, 10, '...' ) ); ?>"</em>
                                <?php endif; ?>
                            </div>
                        </div>
                        <span class="rmbz-cid-pill rmbz-cid-pill-<?php echo esc_attr( $st_class ); ?>">
                            <?php
                            echo $pr->status === 'pendente'  ? '⏳ Em análise'
                               : ( $pr->status === 'aprovado' ? '✓ Aprovado'
                               : '✗ Rejeitado' );
                            ?>
                        </span>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <style>
    .rmbz-cid-inline { margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(255,255,255,0.08); }
    .rmbz-cid-inline-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
    .rmbz-cid-inline-btn {
        background: #FF0000; color: #fff; border: none;
        padding: 6px 12px; border-radius: 5px;
        font-size: 12.5px; font-weight: 600; cursor: pointer;
        transition: background 0.15s;
    }
    .rmbz-cid-inline-btn:hover { background: #cc0000; }
    .rmbz-cid-inline-toggle {
        background: transparent; color: var(--rmbz-text-muted, #888);
        border: none; cursor: pointer; font-size: 12px;
        padding: 4px 0; text-decoration: underline;
    }
    .rmbz-cid-inline-toggle:hover { color: var(--rmbz-text-primary, #fff); }
    .rmbz-cid-arrow { display: inline-block; transition: transform 0.2s; }
    .rmbz-cid-inline-toggle[aria-expanded="true"] .rmbz-cid-arrow { transform: rotate(180deg); }
    .rmbz-cid-history { margin-top: 10px; display: flex; flex-direction: column; gap: 6px; }
    .rmbz-cid-history-item {
        display: flex; align-items: center; gap: 10px;
        background: rgba(255,255,255,0.02);
        border: 1px solid #2a2a2a;
        border-radius: 5px;
        padding: 8px 10px;
    }
    .rmbz-cid-st-pendente  { border-left: 3px solid #f59e0b; }
    .rmbz-cid-st-aprovado  { border-left: 3px solid #10b981; }
    .rmbz-cid-st-rejeitado { border-left: 3px solid #ef4444; }
    .rmbz-cid-history-main { flex: 1; min-width: 0; }
    .rmbz-cid-history-main a {
        color: var(--rmbz-text-primary, #fff);
        font-size: 12.5px; text-decoration: none; word-break: break-all;
    }
    .rmbz-cid-history-meta { color: var(--rmbz-text-muted, #888); font-size: 11px; margin-top: 2px; }
    .rmbz-cid-pill { font-size: 10.5px; padding: 2px 8px; border-radius: 10px; font-weight: 600; white-space: nowrap; }
    .rmbz-cid-pill-pendente  { background: rgba(245,158,11,0.18); color: #f59e0b; }
    .rmbz-cid-pill-aprovado  { background: rgba(16,185,129,0.18); color: #10b981; }
    .rmbz-cid-pill-rejeitado { background: rgba(239,68,68,0.18);  color: #ef4444; }
    </style>

    <script>
    if (typeof window.rmbzCidToggleHistory !== 'function') {
        window.rmbzCidToggleHistory = function(uid) {
            var panel = document.getElementById('rmbz-cid-history-' + uid);
            var btn = document.getElementById('rmbz-cid-toggle-' + uid);
            if (!panel) return;
            var open = panel.style.display !== 'none';
            panel.style.display = open ? 'none' : 'flex';
            if (btn) btn.setAttribute('aria-expanded', open ? 'false' : 'true');
        };
    }
    </script>
    <?php
}


/**
 * Renderiza a secção "Content ID" no detalhe do release.
 *
 * Chamado a partir de distribution-single-view.php (uma única linha).
 * Mostra apenas se o release está LIVE.
 *
 * @param object $release Linha de rmbz_distro_releases
 * @param array  $tracks  Array de faixas do release
 */
function rmbz_contentid_render_section( $release, $tracks = [] ) {
    if ( ! $release || empty( $release->id ) ) return;
    if ( ! rmbz_contentid_release_is_in_content_id( (int) $release->id ) ) return;

    // [1.6.117.8] Esta função agora só renderiza o MODAL.
    // O botão e histórico foram movidos para DENTRO do card YouTube
    // Content ID via `rmbz_contentid_render_inline()`. Chamamos ambas
    // do distribution-single-view.php em sítios diferentes.

    // Faixas para o form (id, número, título)
    $tracks_for_js = [];
    foreach ( $tracks as $idx => $tr ) {
        $tracks_for_js[] = [
            'id'    => (int) ( $tr->id ?? 0 ),
            'num'   => (int) ( $tr->track_number ?? ( $idx + 1 ) ),
            'title' => (string) ( $tr->track_title ?? $tr->title ?? 'Faixa ' . ( $idx + 1 ) ),
        ];
    }
    $is_album = count( $tracks_for_js ) > 1;
    ?>

    <!-- Modal -->
    <div id="rmbz-cid-fe-overlay" class="rmbz-cid-fe-overlay" role="dialog" aria-modal="true">
        <div class="rmbz-cid-fe-modal">
            <div class="rmbz-cid-fe-head">
                <h3 style="margin:0; font-size:16px;">📺 Pedir remoção de claim Content ID</h3>
                <button type="button" class="rmbz-cid-fe-close" onclick="rmbzCidCloseModal()" aria-label="Fechar">×</button>
            </div>
            <div class="rmbz-cid-fe-body">

                <div class="rmbz-cid-fe-field">
                    <label>URL do vídeo YouTube <span style="color:#ef4444;">*</span></label>
                    <input type="url" id="rmbz-cid-video-url" placeholder="https://www.youtube.com/watch?v=..." autocomplete="off">
                    <p class="rmbz-cid-fe-hint">Aceita formatos: youtube.com/watch?v=…, youtu.be/…, youtube.com/shorts/…</p>
                    <div id="rmbz-cid-pending-warning" class="rmbz-cid-fe-warning" style="display:none;">
                        ⚠ Já existe um pedido pendente para este vídeo. Podes submeter mesmo assim mas será marcado como duplicado.
                    </div>
                </div>

                <?php if ( $is_album ): ?>
                    <div class="rmbz-cid-fe-field">
                        <label>Faixas afectadas <span style="color:#ef4444;">*</span></label>
                        <p class="rmbz-cid-fe-hint" style="margin-top:0; margin-bottom:8px;">Marca pelo menos uma. Se for o álbum inteiro, marca "Todas".</p>
                        <div class="rmbz-cid-fe-tracks">
                            <label class="rmbz-cid-fe-track-all">
                                <input type="checkbox" id="rmbz-cid-track-all" onchange="rmbzCidToggleAll(this.checked)">
                                <strong>Todas as faixas</strong>
                            </label>
                            <?php foreach ( $tracks_for_js as $t ): ?>
                                <label class="rmbz-cid-fe-track">
                                    <input type="checkbox" class="rmbz-cid-fe-track-cb" data-track-id="<?php echo (int) $t['id']; ?>">
                                    <span>#<?php echo (int) $t['num']; ?> — <?php echo esc_html( $t['title'] ); ?></span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php else: ?>
                    <input type="hidden" id="rmbz-cid-single-track-id" value="<?php echo (int) ( $tracks_for_js[0]['id'] ?? 0 ); ?>">
                <?php endif; ?>

                <div class="rmbz-cid-fe-field">
                    <label>Motivo <small>(opcional, ajuda a equipa a entender)</small></label>
                    <textarea id="rmbz-cid-reason" rows="4" placeholder="Ex: este vídeo é meu (canal X). O meu próprio áudio está a bloquear. Por favor remover claim."></textarea>
                </div>

                <div id="rmbz-cid-fe-feedback" class="rmbz-cid-fe-feedback"></div>
            </div>
            <div class="rmbz-cid-fe-foot">
                <button type="button" class="button" onclick="rmbzCidCloseModal()">Cancelar</button>
                <button type="button" class="button button-primary rmbz-cid-fe-submit-btn" onclick="rmbzCidSubmit()">📨 Enviar pedido</button>
            </div>
        </div>
    </div>

    <style>
    .rmbz-cid-frontend-card {
        background: var(--rmbz-bg-surface, #1a1a1a);
        border: 1px solid var(--rmbz-border-subtle, #2a2a2a);
        border-left: 3px solid #ff0000; /* YouTube red */
        border-radius: 10px;
        padding: 18px 20px;
    }
    .rmbz-cid-fe-open-btn {
        background: linear-gradient(135deg, #ff0000 0%, #cc0000 100%);
        color: #fff;
        border: none;
        padding: 10px 18px;
        border-radius: 6px;
        font-weight: 600;
        cursor: pointer;
        font-size: 13px;
        transition: transform 0.15s;
    }
    .rmbz-cid-fe-open-btn:hover { transform: translateY(-1px); }
    .rmbz-cid-fe-history {
        display: flex;
        flex-direction: column;
        gap: 6px;
    }
    .rmbz-cid-fe-history-item {
        display: flex;
        align-items: center;
        gap: 12px;
        background: rgba(255,255,255,0.02);
        border: 1px solid #2a2a2a;
        border-radius: 6px;
        padding: 10px 12px;
    }
    .rmbz-cid-fe-history-item.rmbz-cid-fe-st-pendente  { border-left: 3px solid #f59e0b; }
    .rmbz-cid-fe-history-item.rmbz-cid-fe-st-aprovado  { border-left: 3px solid #10b981; }
    .rmbz-cid-fe-history-item.rmbz-cid-fe-st-rejeitado { border-left: 3px solid #ef4444; }
    .rmbz-cid-fe-pill {
        font-size: 11px;
        padding: 3px 9px;
        border-radius: 12px;
        font-weight: 600;
        white-space: nowrap;
    }
    .rmbz-cid-fe-pill-pendente  { background: rgba(245,158,11,0.18); color: #f59e0b; }
    .rmbz-cid-fe-pill-aprovado  { background: rgba(16,185,129,0.18); color: #10b981; }
    .rmbz-cid-fe-pill-rejeitado { background: rgba(239,68,68,0.18);  color: #ef4444; }

    /* Modal */
    .rmbz-cid-fe-overlay {
        display: none;
        position: fixed; inset: 0;
        background: rgba(0,0,0,0.75);
        z-index: 9999;
        align-items: center; justify-content: center;
        padding: 20px;
    }
    .rmbz-cid-fe-overlay.is-open { display: flex; }
    .rmbz-cid-fe-modal {
        background: #1a1a1a;
        border-radius: 12px;
        max-width: 540px; width: 100%;
        max-height: 92vh;
        display: flex; flex-direction: column;
        border: 1px solid #333;
    }
    .rmbz-cid-fe-head {
        display: flex; justify-content: space-between; align-items: center;
        padding: 16px 22px;
        border-bottom: 1px solid #333;
    }
    .rmbz-cid-fe-close {
        background: none; border: none; color: #888;
        font-size: 26px; cursor: pointer; padding: 0; width: 30px; height: 30px;
    }
    .rmbz-cid-fe-close:hover { color: #fff; }
    .rmbz-cid-fe-body { padding: 18px 22px; overflow-y: auto; }
    .rmbz-cid-fe-field { margin-bottom: 16px; }
    .rmbz-cid-fe-field label { display: block; font-size: 13px; font-weight: 600; color: #ddd; margin-bottom: 5px; }
    .rmbz-cid-fe-field input[type=url], .rmbz-cid-fe-field textarea {
        width: 100%; padding: 9px 11px;
        background: #111; border: 1px solid #333; color: #fff;
        border-radius: 5px; font-size: 13px; font-family: inherit;
        box-sizing: border-box;
    }
    .rmbz-cid-fe-field textarea { resize: vertical; min-height: 70px; }
    .rmbz-cid-fe-hint { font-size: 11.5px; color: #888; margin: 4px 0 0; }
    .rmbz-cid-fe-warning {
        background: rgba(245,158,11,0.12);
        border: 1px solid rgba(245,158,11,0.3);
        color: #f59e0b;
        padding: 8px 11px; border-radius: 5px; font-size: 12px;
        margin-top: 8px;
    }
    .rmbz-cid-fe-tracks {
        display: flex; flex-direction: column; gap: 4px;
        max-height: 200px; overflow-y: auto;
        background: #111; border: 1px solid #333;
        border-radius: 5px; padding: 6px;
    }
    .rmbz-cid-fe-tracks label {
        display: flex; align-items: center; gap: 8px;
        padding: 6px 8px; border-radius: 4px; cursor: pointer;
        font-size: 12.5px; font-weight: 400; color: #ddd;
        margin: 0;
    }
    .rmbz-cid-fe-tracks label:hover { background: rgba(255,255,255,0.04); }
    .rmbz-cid-fe-track-all {
        background: rgba(240,185,11,0.06) !important;
        border-bottom: 1px solid #333;
        padding-bottom: 8px !important; margin-bottom: 4px !important;
    }
    .rmbz-cid-fe-feedback { color: #ef4444; font-size: 12px; min-height: 14px; }
    .rmbz-cid-fe-feedback.success { color: #10b981; }
    .rmbz-cid-fe-foot {
        padding: 14px 22px; border-top: 1px solid #333;
        display: flex; gap: 8px; justify-content: flex-end;
    }
    </style>

    <script>
    (function(){
        var tracksData = <?php echo wp_json_encode( $tracks_for_js ); ?>;
        var isAlbum = <?php echo $is_album ? 'true' : 'false'; ?>;
        var ajaxUrl = '<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>';
        var nonce = '<?php echo esc_js( wp_create_nonce( 'rmbz_cid_submit' ) ); ?>';
        var releaseId = <?php echo (int) $release->id; ?>;

        window.rmbzCidOpenModal = function() {
            document.getElementById('rmbz-cid-fe-overlay').classList.add('is-open');
            document.getElementById('rmbz-cid-video-url').value = '';
            document.getElementById('rmbz-cid-reason').value = '';
            document.getElementById('rmbz-cid-fe-feedback').textContent = '';
            document.getElementById('rmbz-cid-fe-feedback').className = 'rmbz-cid-fe-feedback';
            document.getElementById('rmbz-cid-pending-warning').style.display = 'none';
            if (isAlbum) {
                document.getElementById('rmbz-cid-track-all').checked = false;
                document.querySelectorAll('.rmbz-cid-fe-track-cb').forEach(function(cb){ cb.checked = false; });
            }
            setTimeout(function(){ document.getElementById('rmbz-cid-video-url').focus(); }, 100);
        };

        window.rmbzCidCloseModal = function() {
            document.getElementById('rmbz-cid-fe-overlay').classList.remove('is-open');
        };

        window.rmbzCidToggleAll = function(checked) {
            document.querySelectorAll('.rmbz-cid-fe-track-cb').forEach(function(cb){
                cb.checked = checked;
            });
        };

        window.rmbzCidSubmit = function() {
            var url = document.getElementById('rmbz-cid-video-url').value.trim();
            var reason = document.getElementById('rmbz-cid-reason').value.trim();
            var fb = document.getElementById('rmbz-cid-fe-feedback');
            fb.textContent = '';
            fb.className = 'rmbz-cid-fe-feedback';

            if (!url) {
                fb.textContent = 'A URL do vídeo é obrigatória.';
                return;
            }
            if (!/youtube\.com|youtu\.be/i.test(url)) {
                fb.textContent = 'A URL tem que ser de YouTube.';
                return;
            }

            // Recolher faixas
            var trackIds;
            if (isAlbum) {
                if (document.getElementById('rmbz-cid-track-all').checked) {
                    trackIds = ['all'];
                } else {
                    trackIds = [];
                    document.querySelectorAll('.rmbz-cid-fe-track-cb:checked').forEach(function(cb){
                        trackIds.push(parseInt(cb.dataset.trackId, 10));
                    });
                    if (trackIds.length === 0) {
                        fb.textContent = 'Selecciona pelo menos uma faixa.';
                        return;
                    }
                }
            } else {
                var singleId = parseInt(document.getElementById('rmbz-cid-single-track-id').value, 10);
                trackIds = singleId > 0 ? [singleId] : ['all'];
            }

            var btn = document.querySelector('.rmbz-cid-fe-submit-btn');
            btn.disabled = true;
            btn.textContent = 'A enviar...';

            var formData = new FormData();
            formData.append('action', 'rmbz_contentid_submit');
            formData.append('_nonce', nonce);
            formData.append('release_id', releaseId);
            formData.append('video_url', url);
            formData.append('reason', reason);
            formData.append('tracks', JSON.stringify(trackIds));

            fetch(ajaxUrl, { method: 'POST', body: formData, credentials: 'same-origin' })
                .then(function(r){ return r.json(); })
                .then(function(json){
                    btn.disabled = false;
                    btn.textContent = '📨 Enviar pedido';
                    if (json && json.success) {
                        fb.className = 'rmbz-cid-fe-feedback success';
                        fb.textContent = '✓ Pedido enviado. A equipa será notificada e vai analisar.';
                        setTimeout(function(){
                            window.location.reload();
                        }, 1500);
                    } else {
                        var msg = (json && json.data && json.data.message) ? json.data.message : 'Erro ao enviar pedido.';
                        fb.textContent = '✗ ' + msg;
                    }
                })
                .catch(function(e){
                    btn.disabled = false;
                    btn.textContent = '📨 Enviar pedido';
                    fb.textContent = '✗ Erro de rede. Tenta de novo.';
                });
        };

        // Detectar pedido pendente para o mesmo vídeo
        var urlInput = document.getElementById('rmbz-cid-video-url');
        if (urlInput) {
            var debounce;
            urlInput.addEventListener('input', function() {
                clearTimeout(debounce);
                var v = urlInput.value.trim();
                debounce = setTimeout(function(){
                    var warn = document.getElementById('rmbz-cid-pending-warning');
                    if (!v || !/youtube\.com|youtu\.be/i.test(v)) {
                        warn.style.display = 'none';
                        return;
                    }
                    var fd = new FormData();
                    fd.append('action', 'rmbz_contentid_check_pending');
                    fd.append('_nonce', nonce);
                    fd.append('video_url', v);
                    fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
                        .then(function(r){ return r.json(); })
                        .then(function(j){
                            warn.style.display = (j && j.success && j.data && j.data.has_pending) ? 'block' : 'none';
                        })
                        .catch(function(){});
                }, 500);
            });
        }
    })();
    </script>
    <?php
}


/* ─────────────────────────────────────────────────────────────────── */
/* AJAX: submeter pedido                                               */
/* ─────────────────────────────────────────────────────────────────── */

add_action( 'wp_ajax_rmbz_contentid_submit', 'rmbz_contentid_ajax_submit' );
add_action( 'wp_ajax_nopriv_rmbz_contentid_submit', 'rmbz_contentid_ajax_submit' );

function rmbz_contentid_ajax_submit() {
    if ( ! function_exists( 'rmbz_is_user_logged_in' ) || ! rmbz_is_user_logged_in() ) {
        wp_send_json_error( [ 'message' => 'Sessão expirada. Faz login.' ], 401 );
    }
    if ( ! isset( $_POST['_nonce'] ) || ! wp_verify_nonce( $_POST['_nonce'], 'rmbz_cid_submit' ) ) {
        wp_send_json_error( [ 'message' => 'Token inválido.' ], 403 );
    }

    $telemovel = '';
    if ( function_exists( 'rmbz_get_current_user_telemovel' ) ) {
        $telemovel = rmbz_get_current_user_telemovel();
    }
    if ( empty( $telemovel ) ) {
        wp_send_json_error( [ 'message' => 'Não consegui identificar o teu telemóvel.' ], 401 );
    }

    $release_id = (int) ( $_POST['release_id'] ?? 0 );
    $video_url  = esc_url_raw( $_POST['video_url'] ?? '' );
    $reason     = sanitize_textarea_field( $_POST['reason'] ?? '' );
    $tracks_raw = (string) ( $_POST['tracks'] ?? '[]' );

    // Validar
    if ( $release_id <= 0 ) {
        wp_send_json_error( [ 'message' => 'Release inválido.' ] );
    }
    if ( ! rmbz_contentid_release_belongs_to_artist( $release_id, $telemovel ) ) {
        wp_send_json_error( [ 'message' => 'Este release não te pertence.' ], 403 );
    }
    if ( ! rmbz_contentid_release_is_in_content_id( $release_id ) ) {
        wp_send_json_error( [ 'message' => 'Este release não está aprovado no programa YouTube Content ID.' ] );
    }
    $url_check = rmbz_contentid_validate_url( $video_url );
    if ( is_wp_error( $url_check ) ) {
        wp_send_json_error( [ 'message' => $url_check->get_error_message() ] );
    }

    // Parse tracks (array de IDs ou ["all"])
    $tracks_decoded = json_decode( $tracks_raw, true );
    if ( ! is_array( $tracks_decoded ) || empty( $tracks_decoded ) ) {
        wp_send_json_error( [ 'message' => 'Selecciona pelo menos uma faixa.' ] );
    }
    // Sanitizar: ou ["all"] ou lista de IDs inteiros
    if ( in_array( 'all', $tracks_decoded, true ) ) {
        $tracks_clean = [ 'all' ];
    } else {
        $tracks_clean = array_values( array_unique( array_map( 'intval', $tracks_decoded ) ) );
        $tracks_clean = array_filter( $tracks_clean, function ( $i ) { return $i > 0; } );
        if ( empty( $tracks_clean ) ) {
            wp_send_json_error( [ 'message' => 'Selecciona pelo menos uma faixa válida.' ] );
        }
    }

    // INSERT
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_contentid_requests';
    $video_id = rmbz_contentid_extract_video_id( $video_url );
    $inserted = $wpdb->insert( $t, [
        'release_id'       => $release_id,
        'artist_telemovel' => $telemovel,
        'video_url'        => $video_url,
        'video_id'         => $video_id,
        'tracks_affected'  => wp_json_encode( $tracks_clean ),
        'reason'           => $reason,
        'status'           => 'pendente',
        'created_at'       => gmdate( 'Y-m-d H:i:s' ),
    ], [ '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ] );

    if ( ! $inserted ) {
        wp_send_json_error( [ 'message' => 'Erro técnico ao gravar. Tenta de novo.' ] );
    }
    $request_id = (int) $wpdb->insert_id;

    // Notificar admin
    rmbz_contentid_notify_admin_new( $request_id );

    wp_send_json_success( [
        'request_id' => $request_id,
        'message'    => 'Pedido enviado.',
    ] );
}


/* ─────────────────────────────────────────────────────────────────── */
/* AJAX: detectar duplicação                                           */
/* ─────────────────────────────────────────────────────────────────── */

add_action( 'wp_ajax_rmbz_contentid_check_pending', 'rmbz_contentid_ajax_check_pending' );
add_action( 'wp_ajax_nopriv_rmbz_contentid_check_pending', 'rmbz_contentid_ajax_check_pending' );

function rmbz_contentid_ajax_check_pending() {
    if ( ! function_exists( 'rmbz_is_user_logged_in' ) || ! rmbz_is_user_logged_in() ) {
        wp_send_json_error();
    }
    if ( ! isset( $_POST['_nonce'] ) || ! wp_verify_nonce( $_POST['_nonce'], 'rmbz_cid_submit' ) ) {
        wp_send_json_error();
    }
    $telemovel = function_exists( 'rmbz_get_current_user_telemovel' )
        ? rmbz_get_current_user_telemovel() : '';
    if ( empty( $telemovel ) ) wp_send_json_error();

    $video_url = esc_url_raw( $_POST['video_url'] ?? '' );
    $video_id = rmbz_contentid_extract_video_id( $video_url );
    if ( empty( $video_id ) ) {
        wp_send_json_success( [ 'has_pending' => false ] );
    }
    $pending_id = rmbz_contentid_get_pending_for_video( $telemovel, $video_id );
    wp_send_json_success( [
        'has_pending' => $pending_id !== null,
        'pending_id'  => $pending_id,
    ] );
}
