<?php
/**
 * [1.6.117] PEDIDOS DE REMOÇÃO DE CONTENT ID — PÁGINA ADMIN
 *
 * URL: ?page=rmbz-admin-distribution&tab=contentid
 * (integrado como tab em "Gestão de Distribuição Digital")
 *
 * - Lista todos os pedidos (filtros por estado)
 * - Vista de detalhe com botões aprovar/rejeitar
 *
 * Padrão segue o de announcements-admin.php — handlers em admin_init
 * para evitar "headers already sent".
 *
 * @package 1MZ_For_Artists
 * @since 1.6.117
 */

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


// [1.6.117.7] Integrado como tab na página "Gestão de Distribuição Digital".
// REMOVIDO add_menu_page — agora é submenu/tab em rmbz-admin-distribution.
// Mantemos as funções render que o controller chama.


/**
 * Handlers em admin_init (antes do output) para que wp_safe_redirect
 * funcione sem warnings.
 *
 * [1.6.117.7] Reconhece a nova tab dentro de rmbz-admin-distribution.
 */
add_action( 'admin_init', 'rmbz_contentid_handle_actions' );

function rmbz_contentid_handle_actions() {
    // Aceitar 2 contextos:
    //   - URL antigo (?page=rmbz-contentid) — para compatibilidade
    //   - URL novo (?page=rmbz-admin-distribution&tab=contentid)
    $page = $_GET['page'] ?? '';
    $tab  = $_GET['tab']  ?? '';
    $is_contentid_page = ( $page === 'rmbz-contentid' )
        || ( $page === 'rmbz-admin-distribution' && $tab === 'contentid' );

    if ( ! $is_contentid_page ) return;
    if ( ! current_user_can( 'manage_options' ) ) return;

    // POST: processar aprovação/rejeição
    if ( $_SERVER['REQUEST_METHOD'] === 'POST' && isset( $_POST['rmbz_cid_action'] ) ) {
        rmbz_contentid_handle_process();
    }
}


/**
 * URL base da página Content ID — usado em redirects e links internos.
 *
 * [1.6.117.7] Agora aponta para a tab dentro de rmbz-admin-distribution.
 */
function rmbz_contentid_admin_url( $args = [] ) {
    $base = admin_url( 'admin.php' );
    $defaults = [
        'page' => 'rmbz-admin-distribution',
        'tab'  => 'contentid',
    ];
    return add_query_arg( array_merge( $defaults, $args ), $base );
}


function rmbz_contentid_handle_process() {
    if ( ! isset( $_POST['_rmbz_cid_nonce'] ) || ! wp_verify_nonce( $_POST['_rmbz_cid_nonce'], 'rmbz_cid_process' ) ) {
        wp_die( 'Nonce inválido.' );
    }

    $id = (int) ( $_POST['id'] ?? 0 );
    $action = sanitize_key( $_POST['rmbz_cid_action'] );
    $response = sanitize_textarea_field( $_POST['admin_response'] ?? '' );

    if ( $id <= 0 || ! in_array( $action, [ 'approve', 'reject' ], true ) ) {
        wp_die( 'Dados inválidos.' );
    }

    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_contentid_requests';

    $current = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $t WHERE id = %d", $id ) );
    if ( ! $current ) {
        wp_die( 'Pedido não encontrado.' );
    }
    if ( $current->status !== 'pendente' ) {
        wp_safe_redirect( rmbz_contentid_admin_url( [ 'cid_msg' => 'already_processed' ] ) );
        exit;
    }

    $new_status = $action === 'approve' ? 'aprovado' : 'rejeitado';
    $user = wp_get_current_user();

    $wpdb->update( $t, [
        'status'         => $new_status,
        'admin_response' => $response,
        'processed_at'   => gmdate( 'Y-m-d H:i:s' ),
        'processed_by'   => $user->user_login ?? 'admin',
    ], [ 'id' => $id ] );

    // Notificar artista (email + push)
    rmbz_contentid_notify_artist_processed( $id );

    wp_safe_redirect( rmbz_contentid_admin_url( [ 'cid_msg' => $new_status ] ) );
    exit;
}


/**
 * [1.6.117.7] Função wrapper antiga — mantida só por se algum sítio
 * antigo chamar `rmbz_contentid_admin_render`. Agora redirecciona para
 * a nova localização.
 */
function rmbz_contentid_admin_render() {
    wp_safe_redirect( rmbz_contentid_admin_url() );
    exit;
}


function rmbz_contentid_render_styles() {
    ?>
    <style>
    .rmbz-cid-wrap { font-family: -apple-system, system-ui, sans-serif; max-width: 1200px; }
    .rmbz-cid-tabs { margin-bottom: 14px; }
    .rmbz-cid-tabs a {
        display: inline-block; padding: 6px 14px; margin-right: 6px;
        border-radius: 14px; background:#fff; border:1px solid #ddd;
        font-size: 12px; color: #555; text-decoration: none;
    }
    .rmbz-cid-tabs a.active { background: #1e3a8a; color: #fff; border-color: #1e3a8a; }
    .rmbz-cid-tabs a .count { opacity: 0.7; margin-left: 4px; }
    .rmbz-cid-card { background:#fff; border:1px solid #e5e5e5; border-radius:8px; padding:16px 20px; margin-bottom:14px; }
    .rmbz-cid-list { width: 100%; border-collapse: collapse; font-size: 13px; background:#fff; border-radius:8px; overflow:hidden; border:1px solid #e5e5e5; }
    .rmbz-cid-list th { background:#fafafa; padding:10px 12px; text-align:left; font-size:10px; text-transform:uppercase; color:#666; font-weight:600; border-bottom:1px solid #e5e5e5; }
    .rmbz-cid-list td { padding:12px; border-bottom:1px solid #f3f4f6; vertical-align:top; }
    .rmbz-cid-list tr:hover { background:#fffbeb; }
    .rmbz-cid-status { display:inline-block; padding:2px 9px; border-radius:11px; font-size:11px; font-weight:600; }
    .rmbz-cid-status.pendente { background:#fef3c7; color:#92400e; }
    .rmbz-cid-status.aprovado { background:#d1fae5; color:#065f46; }
    .rmbz-cid-status.rejeitado { background:#fee2e2; color:#991b1b; }
    .rmbz-cid-empty { text-align:center; padding:40px; color:#888; }
    .rmbz-cid-detail-grid { display:grid; grid-template-columns: 2fr 1fr; gap:20px; }
    @media (max-width: 900px) { .rmbz-cid-detail-grid { grid-template-columns: 1fr; } }
    .rmbz-cid-actions { display:flex; gap:8px; margin-top:14px; }
    .rmbz-cid-approve-btn { background:#065f46 !important; color:#fff !important; border-color:#065f46 !important; }
    .rmbz-cid-reject-btn { background:#991b1b !important; color:#fff !important; border-color:#991b1b !important; }
    .rmbz-cid-video-preview iframe { width: 100%; border:none; aspect-ratio: 16/9; border-radius:8px; }
    </style>
    <?php
}


function rmbz_contentid_render_list() {
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_contentid_requests';

    $filter = isset( $_GET['st'] ) ? sanitize_key( $_GET['st'] ) : 'pendente';

    // Contadores por estado
    $counts = [];
    foreach ( [ 'pendente', 'aprovado', 'rejeitado' ] as $st ) {
        $counts[ $st ] = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT COUNT(*) FROM $t WHERE status = %s", $st
        ) );
    }
    $counts['all'] = $counts['pendente'] + $counts['aprovado'] + $counts['rejeitado'];

    // Tabs
    echo '<div class="rmbz-cid-tabs">';
    foreach ( [ 'pendente' => '⏳ Pendentes', 'aprovado' => '✓ Aprovados', 'rejeitado' => '✗ Rejeitados', 'all' => 'Todos' ] as $k => $label ) {
        $cls = $filter === $k ? 'active' : '';
        $url = esc_url( rmbz_contentid_admin_url( [ 'st' => $k ] ) );
        echo '<a class="' . $cls . '" href="' . $url . '">' . esc_html( $label ) . ' <span class="count">(' . $counts[ $k ] . ')</span></a>';
    }
    echo '</div>';

    // Query
    $where = $filter === 'all' ? '' : $wpdb->prepare( 'WHERE c.status = %s', $filter );
    $tr = $wpdb->prefix . 'rmbz_distro_releases';
    $rows = $wpdb->get_results(
        "SELECT c.*, r.title AS release_title
           FROM $t c
           LEFT JOIN $tr r ON r.id = c.release_id
           $where
          ORDER BY
            CASE WHEN c.status = 'pendente' THEN 0 ELSE 1 END,
            c.id DESC
          LIMIT 200"
    );

    if ( empty( $rows ) ) {
        echo '<div class="rmbz-cid-card rmbz-cid-empty">';
        echo '<p style="font-size:14px; margin:0;">📭 Sem pedidos nesta categoria.</p>';
        echo '</div>';
        return;
    }

    echo '<table class="rmbz-cid-list">';
    echo '<thead><tr>
        <th>#</th>
        <th>Release</th>
        <th>Artista</th>
        <th>Vídeo</th>
        <th>Faixas</th>
        <th>Quando</th>
        <th>Estado</th>
        <th></th>
    </tr></thead><tbody>';

    foreach ( $rows as $r ) {
        $detail_url = esc_url( rmbz_contentid_admin_url( [ 'view' => 'detail', 'id' => $r->id ] ) );
        $tracks = json_decode( $r->tracks_affected ?: '[]', true );
        $tracks_label = is_array( $tracks ) ? ( $tracks === [ 'all' ] ? 'Todas' : count( $tracks ) . ' faixa(s)' ) : '?';
        $when = human_time_diff( strtotime( $r->created_at ), time() );

        echo '<tr>';
        echo '<td>' . (int) $r->id . '</td>';
        echo '<td><strong>' . esc_html( $r->release_title ?: 'Release #' . $r->release_id ) . '</strong></td>';
        echo '<td><code style="font-size:11px;">' . esc_html( $r->artist_telemovel ) . '</code></td>';
        echo '<td><a href="' . esc_url( $r->video_url ) . '" target="_blank" style="font-size:11.5px;">' . esc_html( wp_trim_words( $r->video_url, 6, '...' ) ) . '</a></td>';
        echo '<td>' . esc_html( $tracks_label ) . '</td>';
        echo '<td style="color:#666; font-size:11.5px;">há ' . esc_html( $when ) . '</td>';
        echo '<td><span class="rmbz-cid-status ' . esc_attr( $r->status ) . '">' . esc_html( $r->status ) . '</span></td>';
        echo '<td><a href="' . $detail_url . '" class="button button-small">Ver →</a></td>';
        echo '</tr>';
    }

    echo '</tbody></table>';
}


function rmbz_contentid_render_detail( $id ) {
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_contentid_requests';
    $tr = $wpdb->prefix . 'rmbz_distro_releases';

    $req = $wpdb->get_row( $wpdb->prepare(
        "SELECT c.*, r.title AS release_title, r.artist_telemovel AS release_artist, r.status AS release_status, r.cover_image
           FROM $t c
           LEFT JOIN $tr r ON r.id = c.release_id
          WHERE c.id = %d",
        $id
    ) );

    if ( ! $req ) {
        echo '<div class="rmbz-cid-card"><p>Pedido não encontrado.</p></div>';
        echo '<p><a href="' . esc_url( rmbz_contentid_admin_url() ) . '">← Voltar</a></p>';
        return;
    }

    $back_url = esc_url( rmbz_contentid_admin_url() );
    $video_id = rmbz_contentid_extract_video_id( $req->video_url );

    // Detalhes das faixas afectadas
    $track_ids = json_decode( $req->tracks_affected ?: '[]', true );
    $all_tracks = rmbz_contentid_get_release_tracks( $req->release_id );
    $tracks_display = [];
    if ( is_array( $track_ids ) && $track_ids === [ 'all' ] ) {
        foreach ( $all_tracks as $t ) {
            $tracks_display[] = '#' . $t->track_number . ' — ' . $t->title;
        }
    } elseif ( is_array( $track_ids ) ) {
        foreach ( $all_tracks as $t ) {
            if ( in_array( (int) $t->id, array_map( 'intval', $track_ids ), true ) ) {
                $tracks_display[] = '#' . $t->track_number . ' — ' . $t->title;
            }
        }
    }

    ?>
    <p><a href="<?php echo $back_url; ?>">← Voltar à lista</a></p>

    <div class="rmbz-cid-card">
        <div style="display:flex; align-items:center; gap:14px;">
            <?php if ( ! empty( $req->cover_image ) ): ?>
                <img src="<?php echo esc_url( $req->cover_image ); ?>" alt="" style="width:60px; height:60px; object-fit:cover; border-radius:6px;">
            <?php endif; ?>
            <div style="flex:1;">
                <h2 style="margin:0; font-size:16px;"><?php echo esc_html( $req->release_title ?: 'Release #' . $req->release_id ); ?></h2>
                <p style="margin:4px 0 0; color:#666; font-size:12.5px;">
                    Artista: <code><?php echo esc_html( $req->release_artist ); ?></code>
                    &nbsp; · &nbsp;
                    Estado release: <strong><?php echo esc_html( $req->release_status ); ?></strong>
                </p>
            </div>
            <div>
                <span class="rmbz-cid-status <?php echo esc_attr( $req->status ); ?>" style="font-size:13px; padding:5px 13px;">
                    <?php echo esc_html( $req->status ); ?>
                </span>
            </div>
        </div>
    </div>

    <div class="rmbz-cid-detail-grid">
        <!-- COLUNA ESQUERDA: detalhes do pedido -->
        <div>
            <div class="rmbz-cid-card">
                <h3 style="margin:0 0 10px; font-size:13px; text-transform:uppercase; color:#666; letter-spacing:0.06em;">📺 Vídeo</h3>
                <p style="margin:0 0 8px;">
                    <a href="<?php echo esc_url( $req->video_url ); ?>" target="_blank" style="font-size:13px; word-break:break-all;">
                        <?php echo esc_html( $req->video_url ); ?>
                    </a>
                </p>
                <?php if ( $video_id ): ?>
                    <div class="rmbz-cid-video-preview" style="margin-top:10px;">
                        <iframe src="https://www.youtube.com/embed/<?php echo esc_attr( $video_id ); ?>" allowfullscreen></iframe>
                    </div>
                <?php endif; ?>
            </div>

            <div class="rmbz-cid-card">
                <h3 style="margin:0 0 10px; font-size:13px; text-transform:uppercase; color:#666; letter-spacing:0.06em;">🎵 Faixas Afectadas</h3>
                <?php if ( empty( $tracks_display ) ): ?>
                    <p style="color:#888; margin:0;">(sem faixas marcadas)</p>
                <?php else: ?>
                    <ul style="margin:0; padding-left:20px; font-size:13px;">
                        <?php foreach ( $tracks_display as $td ): ?>
                            <li style="margin-bottom:4px;"><?php echo esc_html( $td ); ?></li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>

            <?php if ( ! empty( $req->reason ) ): ?>
                <div class="rmbz-cid-card">
                    <h3 style="margin:0 0 10px; font-size:13px; text-transform:uppercase; color:#666; letter-spacing:0.06em;">📝 Motivo do Pedido</h3>
                    <p style="margin:0; font-size:13px; white-space:pre-wrap; color:#333;"><?php echo esc_html( $req->reason ); ?></p>
                </div>
            <?php endif; ?>
        </div>

        <!-- COLUNA DIREITA: acções e meta -->
        <div>
            <div class="rmbz-cid-card">
                <h3 style="margin:0 0 10px; font-size:13px; text-transform:uppercase; color:#666; letter-spacing:0.06em;">📅 Cronologia</h3>
                <p style="font-size:12.5px; margin:0; line-height:1.7;">
                    <strong>Submetido:</strong> <?php echo esc_html( date( 'd/m/Y H:i', strtotime( $req->created_at ) ) ); ?><br>
                    <?php if ( $req->processed_at ): ?>
                        <strong>Processado:</strong> <?php echo esc_html( date( 'd/m/Y H:i', strtotime( $req->processed_at ) ) ); ?><br>
                        <strong>Por:</strong> <?php echo esc_html( $req->processed_by ); ?>
                    <?php endif; ?>
                </p>
            </div>

            <?php if ( $req->status === 'pendente' ): ?>
                <div class="rmbz-cid-card">
                    <h3 style="margin:0 0 10px; font-size:13px; text-transform:uppercase; color:#666; letter-spacing:0.06em;">✅ Processar</h3>
                    <form method="post">
                        <?php wp_nonce_field( 'rmbz_cid_process', '_rmbz_cid_nonce' ); ?>
                        <input type="hidden" name="id" value="<?php echo (int) $req->id; ?>">

                        <label style="font-size:12px; font-weight:600; display:block; margin-bottom:5px;">Resposta ao artista <small>(opcional, vai por email)</small></label>
                        <textarea name="admin_response" rows="4" style="width:100%; padding:6px 8px; border:1px solid #ddd; border-radius:4px; font-size:12.5px;" placeholder="Ex: Claim removido com sucesso. O vídeo já pode ser monetizado normalmente."></textarea>

                        <div class="rmbz-cid-actions">
                            <button type="submit" name="rmbz_cid_action" value="approve" class="button rmbz-cid-approve-btn" onclick="return confirm('Aprovar este pedido? O artista será notificado.');">
                                ✓ Aprovar (Claim Removido)
                            </button>
                            <button type="submit" name="rmbz_cid_action" value="reject" class="button rmbz-cid-reject-btn" onclick="return confirm('Rejeitar este pedido? O artista será notificado.');">
                                ✗ Rejeitar
                            </button>
                        </div>
                        <p style="font-size:11px; color:#888; margin:10px 0 0;">
                            ⚠ Aprovar significa que <strong>já removeste o claim no Content ID/AdRev</strong>. O artista será notificado.
                        </p>
                    </form>
                </div>
            <?php else: ?>
                <div class="rmbz-cid-card">
                    <h3 style="margin:0 0 10px; font-size:13px; text-transform:uppercase; color:#666; letter-spacing:0.06em;">💬 Resposta Enviada</h3>
                    <?php if ( ! empty( $req->admin_response ) ): ?>
                        <p style="font-size:12.5px; margin:0; white-space:pre-wrap;"><?php echo esc_html( $req->admin_response ); ?></p>
                    <?php else: ?>
                        <p style="font-size:12.5px; margin:0; color:#888;">(sem resposta adicional)</p>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php
}
