<?php
/**
 * Download logs integrated into the platform overview.
 */

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

function rmbz_admin_download_logs_url( array $args = [] ) {
    return add_query_arg( array_merge( [ 'page' => 'rmbz-dashboard', 'view' => 'download-logs' ], $args ), admin_url( 'admin.php' ) );
}

function rmbz_admin_download_logs_valid_date( $value ) {
    $value = sanitize_text_field( wp_unslash( (string) $value ) );
    if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $value ) ) return '';
    $date = DateTimeImmutable::createFromFormat( '!Y-m-d', $value, wp_timezone() );
    return $date && $date->format( 'Y-m-d' ) === $value ? $value : '';
}

function rmbz_admin_download_logs_filters( $request = null ) {
    $request = is_array( $request ) ? $request : $_GET;
    $source = sanitize_key( wp_unslash( (string) ( $request['source'] ?? 'all' ) ) );
    if ( ! in_array( $source, [ 'all', 'free', 'paid' ], true ) ) $source = 'all';

    return [
        'search'    => sanitize_text_field( wp_unslash( (string) ( $request['s'] ?? '' ) ) ),
        'source'    => $source,
        'country'   => strtoupper( substr( sanitize_text_field( wp_unslash( (string) ( $request['country'] ?? '' ) ) ), 0, 10 ) ),
        'date_from' => rmbz_admin_download_logs_valid_date( $request['date_from'] ?? '' ),
        'date_to'   => rmbz_admin_download_logs_valid_date( $request['date_to'] ?? '' ),
    ];
}

function rmbz_admin_download_logs_where( array $filters ) {
    global $wpdb;
    $clauses = [ '1=1' ];
    $params = [];

    if ( $filters['search'] !== '' ) {
        $like = '%' . $wpdb->esc_like( $filters['search'] ) . '%';
        $clauses[] = '(p.post_title LIKE %s OR CAST(a.music_id AS CHAR) LIKE %s OR a.user_ip LIKE %s OR a.region LIKE %s OR a.country LIKE %s)';
        array_push( $params, $like, $like, $like, $like, $like );
    }
    if ( $filters['source'] !== 'all' ) {
        $clauses[] = 'a.source=%s';
        $params[] = $filters['source'];
    }
    if ( $filters['country'] !== '' ) {
        $clauses[] = 'a.country=%s';
        $params[] = $filters['country'];
    }
    if ( $filters['date_from'] !== '' ) {
        $clauses[] = 'a.download_date>=%s';
        $params[] = $filters['date_from'];
    }
    if ( $filters['date_to'] !== '' ) {
        $clauses[] = 'a.download_date<DATE_ADD(%s,INTERVAL 1 DAY)';
        $params[] = $filters['date_to'];
    }

    return [ implode( ' AND ', $clauses ), $params ];
}

function rmbz_admin_download_logs_prepare( $sql, array $params ) {
    global $wpdb;
    return $params ? $wpdb->prepare( $sql, $params ) : $sql;
}

function rmbz_admin_download_logs_device( $user_agent ) {
    $agent = strtolower( (string) $user_agent );
    if ( strpos( $agent, 'android' ) !== false ) return 'Android';
    if ( strpos( $agent, 'iphone' ) !== false || strpos( $agent, 'ipad' ) !== false ) return 'iPhone / iPad';
    if ( strpos( $agent, 'windows' ) !== false ) return 'Windows';
    if ( strpos( $agent, 'macintosh' ) !== false || strpos( $agent, 'mac os' ) !== false ) return 'macOS';
    if ( strpos( $agent, 'linux' ) !== false ) return 'Linux';
    return $agent === '' ? 'Não identificado' : 'Navegador';
}

function rmbz_admin_download_logs_query_args( array $filters ) {
    return array_filter( [
        's'         => $filters['search'],
        'source'    => $filters['source'] === 'all' ? '' : $filters['source'],
        'country'   => $filters['country'],
        'date_from' => $filters['date_from'],
        'date_to'   => $filters['date_to'],
    ], static function( $value ) { return $value !== ''; } );
}

function rmbz_admin_download_logs_csv_cell( $value ) {
    $value = (string) $value;
    return preg_match( '/^[=+\-@]/', $value ) ? "'" . $value : $value;
}

function rmbz_admin_export_download_logs() {
    if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Sem permissão.' );
    check_admin_referer( 'rmbz_export_download_logs' );

    global $wpdb;
    $table = $wpdb->prefix . 'imz_analytics';
    if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) wp_die( 'A tabela de downloads não existe.' );

    $filters = rmbz_admin_download_logs_filters( $_GET );
    [ $where, $params ] = rmbz_admin_download_logs_where( $filters );
    $sql = "SELECT a.id,a.download_date,a.music_id,COALESCE(p.post_title,'') music_title,a.source,a.user_ip,a.country,a.region,a.user_agent
            FROM {$table} a LEFT JOIN {$wpdb->posts} p ON p.ID=a.music_id
            WHERE {$where} ORDER BY a.download_date DESC,a.id DESC LIMIT 50000";
    $rows = $wpdb->get_results( rmbz_admin_download_logs_prepare( $sql, $params ), ARRAY_A );

    nocache_headers();
    header( 'Content-Type: text/csv; charset=UTF-8' );
    header( 'Content-Disposition: attachment; filename="1mz-downloads-' . gmdate( 'Y-m-d-His' ) . '.csv"' );
    echo "\xEF\xBB\xBF";
    $output = fopen( 'php://output', 'w' );
    fputcsv( $output, [ 'ID', 'Data', 'ID da música', 'Música', 'Origem', 'IP', 'País', 'Região', 'Dispositivo' ], ';', '"', '' );
    foreach ( $rows as $row ) {
        fputcsv( $output, array_map( 'rmbz_admin_download_logs_csv_cell', [
            $row['id'], $row['download_date'], $row['music_id'], $row['music_title'], $row['source'],
            $row['user_ip'], $row['country'], $row['region'], rmbz_admin_download_logs_device( $row['user_agent'] ),
        ] ), ';', '"', '' );
    }
    fclose( $output );
    exit;
}
add_action( 'admin_post_rmbz_export_download_logs', 'rmbz_admin_export_download_logs' );

function rmbz_admin_redirect_legacy_download_logs() {
    if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) return;
    $page = sanitize_key( wp_unslash( (string) ( $_GET['page'] ?? '' ) ) );
    if ( $page !== 'imz_analytics_logs' ) return;

    $filters = rmbz_admin_download_logs_filters( $_GET );
    $args = rmbz_admin_download_logs_query_args( $filters );
    if ( isset( $_GET['paged'] ) ) $args['paged'] = max( 1, absint( $_GET['paged'] ) );
    wp_safe_redirect( rmbz_admin_download_logs_url( $args ) );
    exit;
}
add_action( 'admin_init', 'rmbz_admin_redirect_legacy_download_logs', 1 );

function rmbz_render_admin_download_logs_page() {
    if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Não tem permissão para aceder a esta página.' );

    global $wpdb;
    $table = $wpdb->prefix . 'imz_analytics';
    $table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table;
    $filters = rmbz_admin_download_logs_filters();
    $page = max( 1, absint( $_GET['paged'] ?? 1 ) );
    $per_page = 30;
    $offset = ( $page - 1 ) * $per_page;
    $rows = [];
    $countries = [];
    $total = $filtered_total = $today = $paid = $unique_music = $unique_visitors = 0;

    if ( $table_exists ) {
        [ $where, $params ] = rmbz_admin_download_logs_where( $filters );
        $join = " FROM {$table} a LEFT JOIN {$wpdb->posts} p ON p.ID=a.music_id ";
        $filtered_total = (int) $wpdb->get_var( rmbz_admin_download_logs_prepare( "SELECT COUNT(*) {$join} WHERE {$where}", $params ) );
        $page = min( $page, max( 1, (int) ceil( $filtered_total / $per_page ) ) );
        $offset = ( $page - 1 ) * $per_page;
        $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );
        $today = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE download_date>=CURDATE()" );
        $paid = (int) $wpdb->get_var( rmbz_admin_download_logs_prepare( "SELECT COUNT(*) {$join} WHERE {$where} AND a.source='paid'", $params ) );
        $unique_music = (int) $wpdb->get_var( rmbz_admin_download_logs_prepare( "SELECT COUNT(DISTINCT a.music_id) {$join} WHERE {$where}", $params ) );
        $unique_visitors = (int) $wpdb->get_var( rmbz_admin_download_logs_prepare( "SELECT COUNT(DISTINCT NULLIF(a.user_ip,'')) {$join} WHERE {$where}", $params ) );
        $rows_sql = "SELECT a.*,COALESCE(p.post_title,'') music_title,p.post_status {$join} WHERE {$where} ORDER BY a.download_date DESC,a.id DESC LIMIT %d OFFSET %d";
        $row_params = array_merge( $params, [ $per_page, $offset ] );
        $rows = $wpdb->get_results( $wpdb->prepare( $rows_sql, $row_params ) );
        $countries = $wpdb->get_results( "SELECT country,COUNT(*) total FROM {$table} WHERE country<>'' GROUP BY country ORDER BY total DESC,country ASC LIMIT 100" );
    }

    $total_pages = max( 1, (int) ceil( $filtered_total / $per_page ) );
    $filter_args = rmbz_admin_download_logs_query_args( $filters );
    $pagination_base = str_replace(
        '999999999',
        '%#%',
        esc_url_raw( rmbz_admin_download_logs_url( array_merge( $filter_args, [ 'paged' => 999999999 ] ) ) )
    );
    $export_url = add_query_arg( array_merge( [
        'action'   => 'rmbz_export_download_logs',
        '_wpnonce' => wp_create_nonce( 'rmbz_export_download_logs' ),
    ], $filter_args ), admin_url( 'admin-post.php' ) );
    $icon = static function( $name ) {
        return function_exists( 'rmbz_admin_overview_icon' ) ? rmbz_admin_overview_icon( $name ) : '';
    };
    ?>
    <style>
        .rmbz-dl-page{--dl-bg:#f6f7f3;--dl-surface:#fff;--dl-soft:#eef2ed;--dl-line:#dce3dd;--dl-ink:#18201c;--dl-muted:#66716a;--dl-primary:#08664b;--dl-primary-soft:#dcefe7;--dl-gold:#efb700;--dl-danger:#b3261e;max-width:none;margin:0 20px 0 2px;padding:26px 24px 70px;min-height:100vh;background:var(--dl-bg);color:var(--dl-ink);font-family:Inter,"Segoe UI",Roboto,sans-serif}.rmbz-dl-page *{box-sizing:border-box}.rmbz-dl-page .rmbz-po-svg{display:block;width:22px;height:22px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;overflow:visible}.rmbz-dl-head{display:flex;justify-content:space-between;align-items:flex-start;gap:24px;margin-bottom:18px}.rmbz-dl-back{display:inline-flex;align-items:center;gap:7px;color:var(--dl-primary);text-decoration:none;font-size:13px;font-weight:800}.rmbz-dl-back .rmbz-po-svg{width:18px}.rmbz-dl-head h1{font-size:32px;line-height:1.08;letter-spacing:-.035em;margin:10px 0 7px}.rmbz-dl-head p{font-size:14px;color:var(--dl-muted);margin:0}.rmbz-dl-actions{display:flex;gap:8px;flex-wrap:wrap}.rmbz-dl-btn{min-height:42px;display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:0 16px;border:1px solid var(--dl-line);border-radius:999px;background:var(--dl-surface);color:var(--dl-ink);text-decoration:none;font-size:13px;font-weight:800;cursor:pointer}.rmbz-dl-btn.primary{background:var(--dl-primary);border-color:var(--dl-primary);color:#fff}.rmbz-dl-btn .rmbz-po-svg{width:18px}.rmbz-dl-hero{position:relative;overflow:hidden;display:grid;grid-template-columns:minmax(0,1fr) auto;gap:20px;padding:25px 27px;border-radius:27px;background:linear-gradient(135deg,#173447,#173e32 68%,#4c6125);color:#fff;margin-bottom:14px}.rmbz-dl-hero:after{content:"";position:absolute;width:220px;height:220px;border-radius:50%;right:-70px;top:-120px;background:rgba(239,183,0,.2)}.rmbz-dl-hero h2{font-size:22px;color:#fff;margin:0 0 7px}.rmbz-dl-hero p{font-size:13px;color:#c7d8d0;margin:0;max-width:720px}.rmbz-dl-live{position:relative;z-index:1;align-self:center;padding:9px 13px;border:1px solid rgba(255,255,255,.18);border-radius:999px;background:rgba(255,255,255,.09);font-size:12px;font-weight:800}.rmbz-dl-metrics{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px;margin:14px 0}.rmbz-dl-metric{display:grid;grid-template-columns:42px minmax(0,1fr);gap:12px;align-items:center;min-height:76px;height:100%;padding:16px;border:1px solid var(--dl-line);border-radius:19px;background:var(--dl-surface)}.rmbz-dl-tonal{width:42px;height:42px;display:grid;place-items:center;align-self:center;flex:0 0 auto;border-radius:14px;background:var(--dl-primary-soft);color:var(--dl-primary)}.rmbz-dl-tonal.gold{background:#fff0bd;color:#745800}.rmbz-dl-metric>div{min-width:0}.rmbz-dl-metric small,.rmbz-dl-metric strong{display:block}.rmbz-dl-metric small{font-size:11px;line-height:1.25;text-transform:uppercase;letter-spacing:.05em;color:var(--dl-muted);font-weight:850}.rmbz-dl-metric strong{font-size:23px;margin-top:5px;line-height:1.1;font-variant-numeric:tabular-nums}.rmbz-dl-filter{display:grid;grid-template-columns:minmax(230px,2fr) repeat(4,minmax(130px,.75fr)) auto;gap:9px;padding:14px;border:1px solid var(--dl-line);border-radius:21px;background:var(--dl-surface);margin:14px 0}.rmbz-dl-field{display:grid;gap:5px}.rmbz-dl-field label{font-size:10px;font-weight:850;text-transform:uppercase;color:var(--dl-muted);letter-spacing:.05em}.rmbz-dl-field input,.rmbz-dl-field select{width:100%;min-height:42px;margin:0;padding:0 12px;border:1px solid var(--dl-line);border-radius:12px;background:var(--dl-soft);box-shadow:none;color:var(--dl-ink);font-size:13px}.rmbz-dl-filter-actions{display:flex;align-items:end;gap:7px}.rmbz-dl-clear{min-height:42px;display:grid;place-items:center;padding:0 12px;color:var(--dl-muted);text-decoration:none;font-size:12px;font-weight:750}.rmbz-dl-panel{border:1px solid var(--dl-line);border-radius:24px;background:var(--dl-surface);overflow:hidden}.rmbz-dl-panel-head{display:flex;justify-content:space-between;align-items:center;gap:14px;padding:17px 19px;border-bottom:1px solid var(--dl-line)}.rmbz-dl-panel-head h2{font-size:17px;margin:0}.rmbz-dl-panel-head p{font-size:12px;color:var(--dl-muted);margin:3px 0 0}.rmbz-dl-count{padding:7px 10px;border-radius:999px;background:#ece8d8;color:#6d5700;font-size:11px;font-weight:850}.rmbz-dl-table-scroll{overflow:auto}.rmbz-dl-table{width:100%;border-collapse:collapse;min-width:980px}.rmbz-dl-table th{padding:11px 14px;background:#f1f4f0;color:var(--dl-muted);font-size:10px;text-align:left;text-transform:uppercase;letter-spacing:.055em}.rmbz-dl-table td{padding:13px 14px;border-top:1px solid #edf0ed;vertical-align:middle;font-size:13px}.rmbz-dl-id{font:700 12px ui-monospace,SFMono-Regular,Consolas,monospace;color:var(--dl-muted)}.rmbz-dl-music{display:flex;align-items:center;gap:11px;min-width:260px}.rmbz-dl-cover{width:44px;height:44px;border-radius:13px;object-fit:cover;background:var(--dl-primary-soft);color:var(--dl-primary);display:grid;place-items:center;flex:0 0 auto}.rmbz-dl-cover .rmbz-po-svg{width:20px}.rmbz-dl-music strong,.rmbz-dl-music span{display:block}.rmbz-dl-music strong{font-size:13px}.rmbz-dl-music a{color:inherit;text-decoration:none}.rmbz-dl-music span{font-size:11px;color:var(--dl-muted);margin-top:3px}.rmbz-dl-date strong,.rmbz-dl-date span{display:block;white-space:nowrap}.rmbz-dl-date strong{font-size:13px}.rmbz-dl-date span{font-size:11px;color:var(--dl-muted);margin-top:3px}.rmbz-dl-chip{display:inline-flex;align-items:center;padding:7px 10px;border-radius:999px;background:var(--dl-soft);font-size:11px;font-weight:850}.rmbz-dl-chip.paid{background:#dcefe7;color:var(--dl-primary)}.rmbz-dl-location strong,.rmbz-dl-location span,.rmbz-dl-visitor strong,.rmbz-dl-visitor span{display:block}.rmbz-dl-location span,.rmbz-dl-visitor span{font-size:11px;color:var(--dl-muted);margin-top:3px}.rmbz-dl-visitor strong{font:700 12px ui-monospace,SFMono-Regular,Consolas,monospace}.rmbz-dl-empty{padding:54px 20px;text-align:center}.rmbz-dl-empty .rmbz-dl-tonal{margin:0 auto 12px}.rmbz-dl-empty h3{font-size:17px;margin:0 0 5px}.rmbz-dl-empty p{font-size:13px;color:var(--dl-muted);margin:0}.rmbz-dl-pagination{display:flex;justify-content:flex-end;align-items:center;gap:12px;padding:16px 18px;border-top:1px solid var(--dl-line)}.rmbz-dl-pagination>span{font-size:12px;color:var(--dl-muted);white-space:nowrap}.rmbz-dl-pages .page-numbers{display:flex;gap:5px;list-style:none;margin:0;padding:0}.rmbz-dl-pages a,.rmbz-dl-pages span{min-width:34px;height:34px;padding:0 9px;display:grid;place-items:center;border:1px solid var(--dl-line);border-radius:10px;color:var(--dl-ink);text-decoration:none;font-size:12px;font-weight:800}.rmbz-dl-pages .current{background:var(--dl-primary);border-color:var(--dl-primary);color:#fff}@media(max-width:1280px){.rmbz-dl-metrics{grid-template-columns:repeat(3,1fr)}.rmbz-dl-filter{grid-template-columns:repeat(3,1fr)}.rmbz-dl-filter .search{grid-column:span 2}}@media(max-width:782px){.rmbz-dl-page{margin:0;padding:18px 10px 55px}.rmbz-dl-head,.rmbz-dl-hero{grid-template-columns:1fr}.rmbz-dl-head{display:grid}.rmbz-dl-actions{justify-content:flex-start}.rmbz-dl-live{justify-self:start}.rmbz-dl-metrics{grid-template-columns:1fr 1fr}.rmbz-dl-filter{grid-template-columns:1fr}.rmbz-dl-filter .search{grid-column:auto}.rmbz-dl-filter-actions{align-items:center}.rmbz-dl-panel-head,.rmbz-dl-pagination{align-items:flex-start;display:grid}.rmbz-dl-pagination{justify-content:stretch}.rmbz-dl-table-scroll{overflow:visible}.rmbz-dl-table{display:block;min-width:0}.rmbz-dl-table thead{display:none}.rmbz-dl-table tbody,.rmbz-dl-table tr,.rmbz-dl-table td{display:block;width:100%}.rmbz-dl-table tr{padding:14px;border-top:1px solid var(--dl-line)}.rmbz-dl-table tr:first-child{border-top:0}.rmbz-dl-table td{padding:7px 0;border:0}.rmbz-dl-table td:before{content:attr(data-label);display:block;margin-bottom:5px;color:var(--dl-muted);font-size:9px;font-weight:850;text-transform:uppercase;letter-spacing:.05em}.rmbz-dl-music{min-width:0}.rmbz-dl-pages{overflow:auto;max-width:100%}}@media(max-width:520px){.rmbz-dl-metrics{grid-template-columns:1fr}.rmbz-dl-actions{display:grid}.rmbz-dl-btn{width:100%}}
    </style>
    <div class="rmbz-dl-page">
        <header class="rmbz-dl-head">
            <div>
                <a class="rmbz-dl-back" href="<?php echo esc_url( admin_url( 'admin.php?page=rmbz-dashboard' ) ); ?>"><?php echo $icon( 'back' ); ?> Visão Geral</a>
                <h1>Downloads da plataforma</h1>
                <p>Histórico completo dos ficheiros entregues pelo site, com origem e localização.</p>
            </div>
            <div class="rmbz-dl-actions">
                <a class="rmbz-dl-btn" href="<?php echo esc_url( $export_url ); ?>"><?php echo $icon( 'download' ); ?> Exportar CSV</a>
                <a class="rmbz-dl-btn primary" href="<?php echo esc_url( rmbz_admin_download_logs_url( $filter_args ) ); ?>"><?php echo $icon( 'refresh' ); ?> Atualizar</a>
            </div>
        </header>

        <section class="rmbz-dl-hero">
            <div><h2>Leitura operacional dos downloads</h2><p>Pesquisa músicas, separa vendas de downloads gratuitos e acompanha os territórios sem sair da administração 1MZ.</p></div>
            <span class="rmbz-dl-live"><?php echo $table_exists ? 'Dados em tempo real' : 'Tabela indisponível'; ?></span>
        </section>

        <section class="rmbz-dl-metrics">
            <?php foreach ( [
                [ 'Total histórico', $total, 'download', '' ], [ 'Resultado atual', $filtered_total, 'report', 'gold' ],
                [ 'Hoje', $today, 'clock', '' ], [ 'Músicas', $unique_music, 'music', 'gold' ], [ 'Visitantes', $unique_visitors, 'groups', '' ],
            ] as $metric ): ?>
                <article class="rmbz-dl-metric"><span class="rmbz-dl-tonal <?php echo esc_attr( $metric[3] ); ?>"><?php echo $icon( $metric[2] ); ?></span><div><small><?php echo esc_html( $metric[0] ); ?></small><strong><?php echo esc_html( number_format_i18n( $metric[1] ) ); ?></strong></div></article>
            <?php endforeach; ?>
        </section>

        <form class="rmbz-dl-filter" method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>">
            <input type="hidden" name="page" value="rmbz-dashboard"><input type="hidden" name="view" value="download-logs">
            <div class="rmbz-dl-field search"><label for="rmbz-dl-search">Pesquisar</label><input id="rmbz-dl-search" type="search" name="s" value="<?php echo esc_attr( $filters['search'] ); ?>" placeholder="Música, ID, IP ou localização"></div>
            <div class="rmbz-dl-field"><label for="rmbz-dl-source">Origem</label><select id="rmbz-dl-source" name="source"><option value="all">Todas</option><option value="free" <?php selected( $filters['source'], 'free' ); ?>>Gratuito</option><option value="paid" <?php selected( $filters['source'], 'paid' ); ?>>Venda</option></select></div>
            <div class="rmbz-dl-field"><label for="rmbz-dl-country">País</label><select id="rmbz-dl-country" name="country"><option value="">Todos</option><?php foreach ( $countries as $country ): ?><option value="<?php echo esc_attr( $country->country ); ?>" <?php selected( $filters['country'], $country->country ); ?>><?php echo esc_html( $country->country . ' (' . number_format_i18n( $country->total ) . ')' ); ?></option><?php endforeach; ?></select></div>
            <div class="rmbz-dl-field"><label for="rmbz-dl-from">De</label><input id="rmbz-dl-from" type="date" name="date_from" value="<?php echo esc_attr( $filters['date_from'] ); ?>"></div>
            <div class="rmbz-dl-field"><label for="rmbz-dl-to">Até</label><input id="rmbz-dl-to" type="date" name="date_to" value="<?php echo esc_attr( $filters['date_to'] ); ?>"></div>
            <div class="rmbz-dl-filter-actions"><button class="rmbz-dl-btn primary" type="submit">Filtrar</button><a class="rmbz-dl-clear" href="<?php echo esc_url( rmbz_admin_download_logs_url() ); ?>">Limpar</a></div>
        </form>

        <section class="rmbz-dl-panel">
            <header class="rmbz-dl-panel-head"><div><h2>Registos de download</h2><p><?php echo esc_html( number_format_i18n( $paid ) ); ?> venda(s) no resultado atual.</p></div><span class="rmbz-dl-count"><?php echo esc_html( number_format_i18n( $filtered_total ) ); ?> registos</span></header>
            <?php if ( ! $table_exists || ! $rows ): ?>
                <div class="rmbz-dl-empty"><span class="rmbz-dl-tonal"><?php echo $icon( 'download' ); ?></span><h3><?php echo $table_exists ? 'Nenhum download encontrado' : 'Analytics ainda não instalado'; ?></h3><p><?php echo $table_exists ? 'Altera ou limpa os filtros para consultar outros registos.' : 'A tabela imz_analytics será criada pela instalação do módulo Artists.'; ?></p></div>
            <?php else: ?>
                <div class="rmbz-dl-table-scroll"><table class="rmbz-dl-table"><thead><tr><th>ID</th><th>Download</th><th>Música</th><th>Origem</th><th>Localização</th><th>Visitante</th></tr></thead><tbody>
                <?php foreach ( $rows as $row ):
                    $title = $row->music_title !== '' ? $row->music_title : 'Música removida';
                    $edit_url = get_edit_post_link( $row->music_id );
                    $cover = get_the_post_thumbnail_url( $row->music_id, 'thumbnail' );
                    $country = $row->country !== '' ? $row->country : 'País não identificado';
                    $region = $row->region !== '' && $row->region !== 'N/A' ? $row->region : 'Região não identificada';
                    $source_label = $row->source === 'paid' ? 'Venda' : ( $row->source === 'free' ? 'Gratuito' : ucfirst( $row->source ) );
                ?>
                    <tr>
                        <td data-label="ID"><span class="rmbz-dl-id">#<?php echo (int) $row->id; ?></span></td>
                        <td data-label="Download"><div class="rmbz-dl-date"><strong><?php echo esc_html( mysql2date( 'd/m/Y', $row->download_date ) ); ?></strong><span><?php echo esc_html( mysql2date( 'H:i:s', $row->download_date ) ); ?></span></div></td>
                        <td data-label="Música"><div class="rmbz-dl-music"><?php if ( $cover ): ?><img class="rmbz-dl-cover" src="<?php echo esc_url( $cover ); ?>" alt=""><?php else: ?><span class="rmbz-dl-cover"><?php echo $icon( 'music' ); ?></span><?php endif; ?><div><?php if ( $edit_url ): ?><a href="<?php echo esc_url( $edit_url ); ?>"><strong><?php echo esc_html( $title ); ?></strong></a><?php else: ?><strong><?php echo esc_html( $title ); ?></strong><?php endif; ?><span>Música #<?php echo (int) $row->music_id; ?></span></div></div></td>
                        <td data-label="Origem"><span class="rmbz-dl-chip <?php echo $row->source === 'paid' ? 'paid' : ''; ?>"><?php echo esc_html( $source_label ); ?></span></td>
                        <td data-label="Localização"><div class="rmbz-dl-location"><strong><?php echo esc_html( $region ); ?></strong><span><?php echo esc_html( $country ); ?></span></div></td>
                        <td data-label="Visitante"><div class="rmbz-dl-visitor"><strong><?php echo esc_html( $row->user_ip ?: 'Sem IP' ); ?></strong><span><?php echo esc_html( rmbz_admin_download_logs_device( $row->user_agent ) ); ?></span></div></td>
                    </tr>
                <?php endforeach; ?>
                </tbody></table></div>
                <?php if ( $total_pages > 1 ): ?>
                    <footer class="rmbz-dl-pagination"><span>Página <?php echo (int) $page; ?> de <?php echo (int) $total_pages; ?></span><nav class="rmbz-dl-pages" aria-label="Paginação"><?php echo paginate_links( [ 'base' => $pagination_base, 'format' => '', 'current' => $page, 'total' => $total_pages, 'type' => 'list', 'prev_text' => 'Anterior', 'next_text' => 'Seguinte' ] ); ?></nav></footer>
                <?php endif; ?>
            <?php endif; ?>
        </section>
    </div>
    <?php
}
