<?php
/**
 * [1.5.232] FASE 2 — Conquistas + Histórico de atividade no site.
 *
 * Reconstrói no site (PHP) os ecrãs de Conquistas e Histórico que
 * a app tem, para quem entra pelo PC/mobile sem instalar a app.
 *
 * Reusa exactamente a lógica dos endpoints REST:
 *   - GET /me/milestones  → rmbz_milestones_catalog / compute_metrics
 *   - GET /me/history     → rmbz_api_history_collect_*
 */

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

/* ============================================================================
 * CONQUISTAS (milestones)
 * ============================================================================ */

/**
 * Renderiza a vista de Conquistas — marcos atingidos e bloqueados,
 * com barra de progresso. Igual ao ecrã "Conquistas" da app.
 *
 * @param string $telemovel  Telemóvel do artista.
 */
function rmbz_render_milestones_view( $telemovel ) {
    global $wpdb;

    // Recheck rápido (igual ao endpoint REST).
    if ( function_exists( 'rmbz_milestones_check_artist' ) ) {
        rmbz_milestones_check_artist( $telemovel );
    }

    $catalog = function_exists( 'rmbz_milestones_catalog' )
        ? rmbz_milestones_catalog() : [];

    $achieved_rows = $wpdb->get_results( $wpdb->prepare(
        "SELECT milestone_key, achieved_value, achieved_at, acknowledged
         FROM {$wpdb->prefix}rmbz_artist_milestones
         WHERE artist_telemovel = %s",
        $telemovel
    ) );
    $achieved = [];
    foreach ( (array) $achieved_rows as $r ) {
        $achieved[ $r->milestone_key ] = $r;
    }

    $metrics = function_exists( 'rmbz_milestones_compute_metrics' )
        ? rmbz_milestones_compute_metrics( $telemovel ) : [];

    // Montar items
    $items = [];
    foreach ( $catalog as $key => $def ) {
        $a = $achieved[ $key ] ?? null;
        $progress = function_exists( 'rmbz_api_milestone_progress' )
            ? rmbz_api_milestone_progress( $key, $def, $metrics )
            : [ 'ratio' => 0.0, 'text' => '' ];
        $items[] = [
            'key'        => $key,
            'category'   => $def['category'] ?? 'geral',
            'title'      => $def['title'] ?? $key,
            'desc'       => $def['description'] ?? '',
            'achieved'   => $a !== null,
            'achieved_at'=> $a ? $a->achieved_at : null,
            'progress'   => (float) $progress['ratio'],
            'progress_tx'=> (string) $progress['text'],
            'order'      => $def['order_hint'] ?? 999,
        ];
    }

    // Ordenar: atingidos primeiro, depois por order_hint
    usort( $items, function( $x, $y ) {
        if ( $x['achieved'] !== $y['achieved'] ) {
            return $x['achieved'] ? -1 : 1;
        }
        return $x['order'] <=> $y['order'];
    } );

    $total    = count( $items );
    $unlocked = count( array_filter( $items, fn($i) => $i['achieved'] ) );
    $pct      = $total > 0 ? round( ( $unlocked / $total ) * 100 ) : 0;
    ?>
    <div class="distro-dashboard rmbz-fullbleed">
        <div class="distro-header">
            <h1>🏆 Conquistas</h1>
            <a href="?distro_action=dashboard" class="back-link">&larr; Voltar</a>
        </div>

        <!-- Resumo de progresso -->
        <div style="background:var(--rmbz-bg-surface,#1a1a1a);
                    border:1px solid rgba(240,185,11,0.35); border-radius:16px;
                    padding:22px; margin-bottom:24px;">
            <div style="display:flex; align-items:baseline; gap:10px;">
                <strong style="color:#DAA520; font-size:34px;">
                    <?php echo $unlocked; ?>
                </strong>
                <span style="color:var(--rmbz-text-faint,#888); font-size:15px;">
                    de <?php echo $total; ?> conquistas
                </span>
            </div>
            <div style="margin-top:12px; height:8px; border-radius:4px;
                        background:rgba(255,255,255,0.07);">
                <div style="height:8px; border-radius:4px;
                            width:<?php echo $pct; ?>%;
                            background:linear-gradient(90deg,#DAA520,#FFD700);"></div>
            </div>
            <small style="color:var(--rmbz-text-faint,#888); font-size:12px;
                          display:block; margin-top:8px;">
                <?php echo $pct; ?>% completo
            </small>
        </div>

        <!-- Lista de conquistas -->
        <div style="display:flex; flex-direction:column; gap:10px;">
            <?php foreach ( $items as $it ):
                $done = $it['achieved'];
                $bar  = max( 0, min( 100, (int) round( $it['progress'] * 100 ) ) );
            ?>
                <div style="display:flex; align-items:center; gap:14px;
                            background:var(--rmbz-bg-surface,#1a1a1a);
                            border:1px solid <?php echo $done ? 'rgba(240,185,11,0.4)' : '#2a2a2a'; ?>;
                            border-radius:12px; padding:14px 16px;
                            <?php echo $done ? '' : 'opacity:0.75;'; ?>">
                    <div style="width:46px; height:46px; border-radius:12px;
                                background:<?php echo $done ? 'rgba(240,185,11,0.16)' : 'rgba(255,255,255,0.05)'; ?>;
                                display:flex; align-items:center; justify-content:center;
                                font-size:24px; flex-shrink:0;">
                        <?php echo $done ? '🏆' : '🔒'; ?>
                    </div>
                    <div style="flex:1; min-width:0;">
                        <strong style="color:var(--rmbz-text-primary,#fff);
                                       font-size:14px; display:block;">
                            <?php echo esc_html( $it['title'] ); ?>
                        </strong>
                        <?php if ( ! empty( $it['desc'] ) ): ?>
                            <small style="color:var(--rmbz-text-faint,#888); font-size:11px;">
                                <?php echo esc_html( $it['desc'] ); ?>
                            </small>
                        <?php endif; ?>

                        <?php if ( $done ): ?>
                            <div style="color:#2ecc71; font-size:11px; margin-top:4px;">
                                ✓ Conquistado<?php
                                if ( ! empty( $it['achieved_at'] ) ) {
                                    echo ' · ' . esc_html(
                                        date( 'd/m/Y', strtotime( $it['achieved_at'] ) )
                                    );
                                } ?>
                            </div>
                        <?php else: ?>
                            <div style="margin-top:6px; height:4px; border-radius:2px;
                                        background:rgba(255,255,255,0.06);">
                                <div style="height:4px; border-radius:2px;
                                            width:<?php echo $bar; ?>%;
                                            background:#DAA520;"></div>
                            </div>
                            <?php if ( ! empty( $it['progress_tx'] ) ): ?>
                                <small style="color:var(--rmbz-text-faint,#666);
                                               font-size:10px;">
                                    <?php echo esc_html( $it['progress_tx'] ); ?>
                                </small>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>

            <?php if ( empty( $items ) ): ?>
                <div style="background:var(--rmbz-bg-surface,#1a1a1a);
                            border-radius:12px; padding:30px; text-align:center;
                            color:var(--rmbz-text-faint,#888);">
                    Ainda não há conquistas disponíveis.
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php
}

/* ============================================================================
 * HISTÓRICO DE ATIVIDADE
 * ============================================================================ */

/**
 * Renderiza a vista de Histórico — linha do tempo de atividade
 * (releases, pagamentos, splits, conta). Igual ao ecrã da app.
 *
 * @param string $telemovel  Telemóvel do artista.
 */
function rmbz_render_history_view( $telemovel ) {

    // Filtro por categoria (?hfilter=)
    $allowed = [ 'all', 'releases', 'payments', 'splits', 'account' ];
    $filter  = isset( $_GET['hfilter'] ) && in_array( $_GET['hfilter'], $allowed, true )
        ? $_GET['hfilter'] : 'all';

    // Reusa exactamente os colectores do endpoint REST.
    $items = [];
    if ( ( $filter === 'all' || $filter === 'releases' )
         && function_exists( 'rmbz_api_history_collect_releases' ) ) {
        $items = array_merge( $items, rmbz_api_history_collect_releases( $telemovel ) );
    }
    if ( ( $filter === 'all' || $filter === 'payments' )
         && function_exists( 'rmbz_api_history_collect_payments' ) ) {
        $items = array_merge( $items, rmbz_api_history_collect_payments( $telemovel ) );
    }
    if ( ( $filter === 'all' || $filter === 'splits' )
         && function_exists( 'rmbz_api_history_collect_splits' ) ) {
        $items = array_merge( $items, rmbz_api_history_collect_splits( $telemovel ) );
    }
    if ( ( $filter === 'all' || $filter === 'account' )
         && function_exists( 'rmbz_api_history_collect_account' ) ) {
        $items = array_merge( $items, rmbz_api_history_collect_account( $telemovel ) );
    }

    // Ordenar por data desc
    usort( $items, function( $a, $b ) {
        return strcmp(
            (string) ( $b['created_at'] ?? '' ),
            (string) ( $a['created_at'] ?? '' )
        );
    } );

    // Cores por severidade
    $sev_color = [
        'info'    => '#3b82f6',
        'success' => '#2ecc71',
        'warning' => '#f0b90b',
        'error'   => '#e74c3c',
    ];
    ?>
    <div class="distro-dashboard rmbz-fullbleed">
        <div class="distro-header">
            <h1>📜 Histórico de atividade</h1>
            <a href="?distro_action=dashboard" class="back-link">&larr; Voltar</a>
        </div>

        <!-- Filtros -->
        <div style="display:flex; gap:8px; flex-wrap:wrap; margin-bottom:22px;">
            <?php
            $filters = [
                'all'      => 'Tudo',
                'releases' => 'Lançamentos',
                'payments' => 'Pagamentos',
                'splits'   => 'Splits',
                'account'  => 'Conta',
            ];
            foreach ( $filters as $fk => $flabel ):
                $active = ( $filter === $fk );
            ?>
                <a href="?distro_action=history&hfilter=<?php echo esc_attr( $fk ); ?>"
                   style="padding:7px 14px; border-radius:20px; text-decoration:none;
                          font-size:12px; font-weight:700;
                          <?php echo $active
                              ? 'background:#f0b90b; color:#000;'
                              : 'background:var(--rmbz-bg-surface,#1a1a1a); color:#aaa; border:1px solid #333;'; ?>">
                    <?php echo esc_html( $flabel ); ?>
                </a>
            <?php endforeach; ?>
        </div>

        <?php if ( empty( $items ) ): ?>
            <div style="background:var(--rmbz-bg-surface,#1a1a1a);
                        border-radius:12px; padding:40px 24px; text-align:center;">
                <div style="font-size:38px; margin-bottom:10px;">📭</div>
                <p style="color:var(--rmbz-text-faint,#888); font-size:13px; margin:0;">
                    Ainda não há atividade neste filtro.
                </p>
            </div>
        <?php else: ?>
            <!-- Linha do tempo -->
            <div style="display:flex; flex-direction:column; gap:2px;">
                <?php foreach ( $items as $it ):
                    $sev = $it['severity'] ?? 'info';
                    $col = $sev_color[ $sev ] ?? '#3b82f6';
                    $when = ! empty( $it['created_at'] )
                        ? date( 'd/m/Y · H:i', strtotime( $it['created_at'] ) )
                        : '';
                ?>
                    <div style="display:flex; gap:14px; padding:14px 4px;
                                border-bottom:1px solid #222;">
                        <!-- Marcador -->
                        <div style="display:flex; flex-direction:column;
                                    align-items:center; flex-shrink:0;">
                            <div style="width:12px; height:12px; border-radius:50%;
                                        background:<?php echo $col; ?>;
                                        border:2px solid rgba(0,0,0,0.3);"></div>
                            <div style="flex:1; width:2px;
                                        background:#222; margin-top:4px;"></div>
                        </div>
                        <!-- Conteúdo -->
                        <div style="flex:1; min-width:0; padding-bottom:4px;">
                            <strong style="color:var(--rmbz-text-primary,#fff);
                                           font-size:13px; display:block;">
                                <?php echo esc_html( $it['heading'] ?? 'Atividade' ); ?>
                            </strong>
                            <?php if ( ! empty( $it['sub'] ) ): ?>
                                <small style="color:var(--rmbz-text-faint,#999);
                                               font-size:12px; display:block; margin-top:2px;">
                                    <?php echo esc_html( $it['sub'] ); ?>
                                </small>
                            <?php endif; ?>
                            <small style="color:var(--rmbz-text-faint,#666);
                                           font-size:10px; display:block; margin-top:4px;">
                                <?php echo esc_html( $when ); ?>
                            </small>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    <?php
}
