<?php
// includes/distribution/distribution-list-view.php

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

/**
 * Renderiza a Lista Detalhada de Lançamentos (Discografia)
 * @param string $user_telemovel O ID do artista.
 */
function rmbz_render_releases_list_view( $user_telemovel ) {
    global $wpdb;
    
    // 1. Preparar Filtros (Pode ser expandido com $_GET no futuro)
    $orderby = "created_at DESC"; // Padrão

    // 2. Buscar lançamentos do artista na BD
    $table_name = $wpdb->prefix . 'rmbz_distro_releases';

    // [1.5.180] Paginação clássica — 10 por página, query string ?lpage=2
    $per_page = 10;
    $total_releases = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM $table_name WHERE artist_telemovel = %s",
        $user_telemovel
    ) );
    $total_pages = max( 1, (int) ceil( $total_releases / $per_page ) );
    $current_page = isset($_GET['lpage']) ? max( 1, (int) $_GET['lpage'] ) : 1;
    if ( $current_page > $total_pages ) $current_page = $total_pages;
    $offset = ( $current_page - 1 ) * $per_page;

    $releases = $wpdb->get_results( $wpdb->prepare(
        "SELECT * FROM $table_name
         WHERE artist_telemovel = %s
         ORDER BY $orderby
         LIMIT %d OFFSET %d",
        $user_telemovel, $per_page, $offset
    ) );

    // [BUGFIX 1.5.19] Antes mostrávamos "by 1MZ Artist" hard-coded em todos
    // os cards, em vez do nome real do artista. Como esta lista é sempre
    // por um único artista (filtrada por $user_telemovel), basta uma query
    // antes do loop para obter o nome, mesmo padrão usado em single-view.
    $table_wallet = $wpdb->prefix . 'rmbz_wallets';
    $artist_display_name = $wpdb->get_var( $wpdb->prepare(
        "SELECT user_nome FROM $table_wallet WHERE user_telemovel = %s",
        $user_telemovel
    ) );
    if ( empty($artist_display_name) ) $artist_display_name = 'Artista 1MZ';

    // 3. Estado Vazio (Se não tiver músicas)
    if ( $total_releases === 0 ) {
        echo '<div style="padding:40px; text-align:center; color:#888; background:#181818; border:1px dashed #333; border-radius:8px;">
                <p style="font-size:16px;">Ainda não tem lançamentos.</p> 
                <a href="?page=rmbz-distribution&distro_action=create" class="onemz-btn btn-gradient" style="width:auto; margin-top:10px;">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                        <path d="M12 5v14M5 12h14" stroke="#fff" stroke-width="2.5" stroke-linecap="round"/>
                    </svg>
                    Criar Primeiro Lan&ccedil;amento
                </a>
              </div>';
        return;
    }

    ?>
    <div class="distro-list-container rmbz-fullbleed">
        
        <div class="distro-filters">
            <div class="filter-group">
                <label>Pesquisa</label>
                <input type="text" placeholder="Insira um título do lançamento...">
            </div>
            <div class="filter-group">
                <label>Tipo de Lançamento</label>
                <select>
                    <option value="">Todos os Lançamentos</option>
                    <option value="single">Single</option>
                    <option value="album">Álbum</option>
                    <option value="ep">EP</option>
                </select>
            </div>
            <div class="filter-group">
                <label>Status</label>
                <select>
                    <option value="">Todos os Status</option>
                    <option value="live">Live (Ao Vivo)</option>
                    <option value="pendente">Pendente</option>
                    <option value="incompleto">Incompleto</option>
                </select>
            </div>
            <div class="filter-group">
                <label>Ordenar por</label>
                <select>
                    <option value="date_desc">Data de Criação - mais recente</option>
                    <option value="title_asc">Título (A-Z)</option>
                </select>
            </div>
        </div>

        <div class="filter-actions">
            <button class="btn-filter-apply">APLICAR</button>
            <button class="btn-filter-reset">RESTABELECER</button>
        </div>

        <p class="results-count">
            <?php
            // [1.5.180] Mostrar total real + range desta página
            $start_n = $offset + 1;
            $end_n   = min( $offset + $per_page, $total_releases );
            if ( $total_releases > $per_page ) {
                printf( 'A mostrar %d–%d de <strong>%d</strong> lançamentos', $start_n, $end_n, $total_releases );
            } else {
                printf( '%d lançamento%s encontrado%s', $total_releases, $total_releases !== 1 ? 's' : '', $total_releases !== 1 ? 's' : '' );
            }
            ?>
        </p>

        <div class="releases-list">
            <?php foreach ($releases as $rel) : 
                
                // LÓGICA DE STATUS E CORES
                $status_class = 'status-processing'; // Padrão (Azul)
                $status_text = 'Pendente';
                $action_html = '';
                $link_view = '?page=rmbz-distribution&distro_action=view_release&id=' . $rel->id;

                // Status: LIVE (Distribuído)
                if ($rel->status === 'live' || $rel->status === 'distribuido') {
                    $status_class = 'status-live'; // Verde
                    $status_text = 'Live (Ao Vivo) >';
                    
                    // Ações disponíveis para música ativa.
                    // [1.5.144] Antes eram alert("em breve") falsos. Agora:
                    //   - "+ ADICIONAR/REMOVER LOJAS" → abre modal real
                    //     (rendered no single-view; aqui é shortcut para
                    //     o single-view com query string trigger).
                    //   - "DIVIDIR ROYALTIES (SPLITS)" → idem, leva para
                    //     o single-view onde o botão Configurar Splits
                    //     está disponível desde a 1.5.117.
                    $sv_url = '?page=rmbz-distribution&distro_action=view_release&id=' . (int) $rel->id;
                    $action_html = '
                        <a class="btn-text-action" href="' . esc_url( $sv_url . '#open-stores' ) . '">+ ADICIONAR / REMOVER LOJAS</a>
                        <a class="btn-text-action" href="' . esc_url( $sv_url . '#open-splits' ) . '">DIVIDIR ROYALTIES (SPLITS)</a>
                    ';
                
                // Status: PENDENTE (Em revisão)
                } elseif ($rel->status === 'pendente' || $rel->status === 'aprovado') {
                    $status_class = 'status-processing'; // Azul
                    $status_text = 'Em Revisão >';
                    $action_html = '<span style="color:#aaa; font-size:12px;">Aguardando aprovação da 1MZ...</span>';
                
                // Status: INCOMPLETO / REJEITADO
                } else {
                    $status_class = 'status-incomplete'; // Laranja
                    $status_text = 'Não finalizado >';
                    
                    // Botão para continuar edição ou corrigir
                    $link_edit = '?page=rmbz-distribution&distro_action=edit_release&id=' . $rel->id;
                    $action_html = '<a href="'.$link_edit.'" class="btn-distribute"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M5 12h14M13 5l7 7-7 7" stroke="#000" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>DISTRIBUIR</a>';
                }
                
                // Formatação de Dados
                $date_fmt = $rel->created_at ? date('m/d/Y', strtotime($rel->created_at)) : '-';
                $upc_display = $rel->upc_code ? esc_html($rel->upc_code) : '<em>Gerado após envio</em>';
                $cover_src = $rel->cover_image ? esc_url($rel->cover_image) : '';
                
            ?>
                <div class="release-item">
                    
                    <div class="release-cover">
                        <a href="<?php echo $link_view; ?>">
                            <?php if($cover_src): ?>
                                <img src="<?php echo $cover_src; ?>" alt="Capa">
                            <?php else: ?>
                                <div style="width:100%; height:100%; background:#333; display:flex; align-items:center; justify-content:center; border-radius:4px; color:#555;">Sem Capa</div>
                            <?php endif; ?>
                            
                            <?php if($rel->status === 'live'): ?>
                                <div class="icon-overlay" title="Smartlink Ativo">🔗</div>
                            <?php endif; ?>
                        </a>
                    </div>

                    <div class="release-main-info">
                        <a href="<?php echo $link_view; ?>" style="text-decoration:none;">
                            <h3 class="release-title"><?php echo esc_html($rel->title); ?></h3>
                        </a>
                        <span class="release-artist">by <strong><?php echo esc_html($artist_display_name); ?></strong></span> <div class="release-meta-grid">
                            <span class="meta-label">Tipo de Lançamento</span>
                            <span class="meta-value"><?php echo esc_html(ucfirst($rel->release_type)); ?></span>

                            <span class="meta-label">Data de Lançamento</span>
                            <span class="meta-value"><?php echo $date_fmt; ?></span>

                            <?php /* UPC ESCONDIDO da vista do artista — código técnico */ ?>

                            <span class="meta-label">ID de lançamento:</span>
                            <span class="meta-value">#<?php echo esc_html($rel->id); ?></span>
                        </div>

                        <a href="<?php echo $link_view; ?>" style="text-decoration:none;">
                            <span class="status-badge <?php echo $status_class; ?>">
                                <?php echo $status_text; ?>
                            </span>
                        </a>
                    </div>

                    <div class="release-actions">
                        <?php echo $action_html; ?>
                    </div>

                </div>
            <?php endforeach; ?>
        </div>

        <?php /* [1.5.180] PAGINAÇÃO clássica — links 1 2 3 4 → */ ?>
        <?php if ( $total_pages > 1 ):
            // Função inline para gerar URL preservando outros params
            $page_url = function( $p ) {
                $args = $_GET;
                $args['lpage'] = $p;
                return '?' . http_build_query( $args );
            };
            // Decidir páginas a mostrar (max ~9 visíveis)
            $pages_to_show = [];
            if ( $total_pages <= 9 ) {
                for ( $i = 1; $i <= $total_pages; $i++ ) $pages_to_show[] = $i;
            } else {
                $pages_to_show[] = 1;
                $start = max( 2, $current_page - 2 );
                $end   = min( $total_pages - 1, $current_page + 2 );
                if ( $start > 2 ) $pages_to_show[] = '...';
                for ( $i = $start; $i <= $end; $i++ ) $pages_to_show[] = $i;
                if ( $end < $total_pages - 1 ) $pages_to_show[] = '...';
                $pages_to_show[] = $total_pages;
            }
        ?>
        <div class="rmbz-discog-pagination">
            <?php if ( $current_page > 1 ): ?>
                <a href="<?php echo esc_url( $page_url( $current_page - 1 ) ); ?>" class="rmbz-dpg-btn">← Anterior</a>
            <?php else: ?>
                <span class="rmbz-dpg-btn rmbz-dpg-disabled">← Anterior</span>
            <?php endif; ?>

            <span class="rmbz-dpg-numbers">
                <?php foreach ( $pages_to_show as $p ): ?>
                    <?php if ( $p === '...' ): ?>
                        <span class="rmbz-dpg-ellipsis">…</span>
                    <?php elseif ( $p == $current_page ): ?>
                        <span class="rmbz-dpg-num active"><?php echo (int) $p; ?></span>
                    <?php else: ?>
                        <a href="<?php echo esc_url( $page_url( $p ) ); ?>" class="rmbz-dpg-num"><?php echo (int) $p; ?></a>
                    <?php endif; ?>
                <?php endforeach; ?>
            </span>

            <?php if ( $current_page < $total_pages ): ?>
                <a href="<?php echo esc_url( $page_url( $current_page + 1 ) ); ?>" class="rmbz-dpg-btn">Próxima →</a>
            <?php else: ?>
                <span class="rmbz-dpg-btn rmbz-dpg-disabled">Próxima →</span>
            <?php endif; ?>
        </div>

        <style>
        .rmbz-discog-pagination {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-top: 24px;
            padding: 16px 18px;
            background: #181818;
            border: 1px solid #2a2a2a;
            border-radius: 8px;
            flex-wrap: wrap;
            justify-content: center;
        }
        .rmbz-dpg-btn {
            padding: 8px 14px;
            border: 1px solid #333;
            background: #222;
            color: #ccc;
            border-radius: 5px;
            font-size: 13px;
            cursor: pointer;
            text-decoration: none;
            transition: all 0.15s ease;
        }
        .rmbz-dpg-btn:hover:not(.rmbz-dpg-disabled) {
            background: #f0b90b;
            border-color: #f0b90b;
            color: #000;
        }
        .rmbz-dpg-btn.rmbz-dpg-disabled {
            opacity: 0.4;
            cursor: not-allowed;
            color: #666;
        }
        .rmbz-dpg-numbers {
            display: inline-flex;
            gap: 6px;
            flex-wrap: wrap;
        }
        .rmbz-dpg-num {
            padding: 8px 13px;
            border: 1px solid #333;
            background: #1a1a1a;
            color: #ccc;
            border-radius: 5px;
            font-size: 13px;
            cursor: pointer;
            min-width: 38px;
            text-align: center;
            text-decoration: none;
            transition: all 0.15s ease;
            display: inline-block;
        }
        .rmbz-dpg-num:hover {
            background: #f0b90b;
            border-color: #f0b90b;
            color: #000;
        }
        .rmbz-dpg-num.active {
            background: #f0b90b;
            border-color: #d4a009;
            color: #000;
            font-weight: 700;
            cursor: default;
        }
        .rmbz-dpg-ellipsis {
            padding: 8px 6px;
            color: #666;
            font-size: 13px;
        }
        </style>
        <?php endif; ?>

    </div>
    <?php
}
?>