<?php
/**
 * [FEAT 1.6.28] LOG DE AUDITORIA CENTRALIZADO
 *
 * Vista cronológica de TUDO o que aconteceu no sistema:
 *   - Imports aprovados/rejeitados/revertidos
 *   - Releases aprovados/rejeitados/devolvidos/takedown
 *   - Pagamentos criados/revertidos
 *   - Matches aprovados/rejeitados
 *
 * Filtros: tipo, utilizador, data, período.
 *
 * Acedido via:
 *   ?page=rmbz-admin-distribution&tab=royalties&rsub=audit
 */

defined('ABSPATH') or exit;


function rmbz_render_audit_log() {
    global $wpdb;
    $prefix = $wpdb->prefix;

    // ── Filtros ────────────────────────────────────────────────────────────
    $f_type   = isset($_GET['au_type'])   ? sanitize_key($_GET['au_type']) : '';
    $f_user   = isset($_GET['au_user'])   ? sanitize_text_field($_GET['au_user']) : '';
    $f_from   = isset($_GET['au_from'])   ? sanitize_text_field($_GET['au_from']) : '';
    $f_to     = isset($_GET['au_to'])     ? sanitize_text_field($_GET['au_to']) : '';
    $f_search = isset($_GET['au_search']) ? sanitize_text_field($_GET['au_search']) : '';

    // Janela default: últimos 60 dias se não houver filtros
    if ( ! $f_from ) $f_from = date('Y-m-d', strtotime('-60 days'));
    if ( ! $f_to )   $f_to   = date('Y-m-d');

    $from_dt = $f_from . ' 00:00:00';
    $to_dt   = $f_to   . ' 23:59:59';

    // ── Recolher eventos de várias fontes ──────────────────────────────────
    $events = [];

    // ─── Imports ──────────────────────────────────────────────────────────
    $t_logs = $prefix . 'rmbz_distro_import_logs';
    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_logs'") === $t_logs ) {
        if ( $f_type === '' || $f_type === 'import' ) {
            $rows = $wpdb->get_results( $wpdb->prepare(
                "SELECT id, source_name, reporting_period, file_hash, approved_by, approved_at,
                        reverted_by, reverted_at, approval_status, status, total_amount_usd
                   FROM $t_logs
                  WHERE (approved_at BETWEEN %s AND %s) OR (reverted_at BETWEEN %s AND %s)
                  LIMIT 200",
                $from_dt, $to_dt, $from_dt, $to_dt
            ) );
            foreach ( $rows as $r ) {
                if ( $r->approved_at && $r->approved_at >= $from_dt && $r->approved_at <= $to_dt ) {
                    $events[] = [
                        'type'   => 'import',
                        'sub'    => 'approved',
                        'icon'   => '✓',
                        'date'   => $r->approved_at,
                        'user'   => $r->approved_by ?: 'sistema',
                        'title'  => 'Import aprovado',
                        'detail' => $r->source_name . ' · ' . $r->reporting_period . ' · $' . number_format( (float) $r->total_amount_usd, 2),
                        'url'    => admin_url('admin.php?page=rmbz-admin-distribution&tab=royalties&rsub=imports'),
                        'color'  => 'success',
                    ];
                }
                if ( $r->reverted_at && $r->reverted_at >= $from_dt && $r->reverted_at <= $to_dt ) {
                    $events[] = [
                        'type'   => 'import',
                        'sub'    => 'reverted',
                        'icon'   => '⟲',
                        'date'   => $r->reverted_at,
                        'user'   => $r->reverted_by ?: 'sistema',
                        'title'  => 'Import revertido',
                        'detail' => $r->source_name . ' · ' . $r->reporting_period . ' · $' . number_format( (float) $r->total_amount_usd, 2),
                        'url'    => admin_url('admin.php?page=rmbz-admin-distribution&tab=royalties&rsub=imports'),
                        'color'  => 'danger',
                    ];
                }
            }
        }
    }

    // ─── Releases status changes ─────────────────────────────────────────
    $t_status = $prefix . 'rmbz_distro_status_history';
    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_status'") === $t_status ) {
        if ( $f_type === '' || $f_type === 'release' ) {
            $t_releases = $prefix . 'rmbz_distro_releases';
            $rows = $wpdb->get_results( $wpdb->prepare(
                "SELECT s.release_id, s.from_status, s.to_status, s.changed_by, s.reason_text, s.created_at,
                        r.title, r.artist_name
                   FROM $t_status s
              LEFT JOIN $t_releases r ON r.id = s.release_id
                  WHERE s.created_at BETWEEN %s AND %s
                  ORDER BY s.created_at DESC
                  LIMIT 200",
                $from_dt, $to_dt
            ) );
            foreach ( $rows as $r ) {
                $event_sub = $r->to_status;
                $icon = '📋';
                $color = 'info';
                $title = 'Release: ' . $r->from_status . ' → ' . $r->to_status;
                if ( strpos( $r->to_status, 'approved' ) !== false || $r->to_status === 'live' ) {
                    $icon = '✓'; $color = 'success';
                } elseif ( strpos( $r->to_status, 'reject' ) !== false || strpos( $r->to_status, 'taken_down' ) !== false ) {
                    $icon = '✗'; $color = 'danger';
                } elseif ( strpos( $r->to_status, 'return' ) !== false ) {
                    $icon = '⟲'; $color = 'warning';
                } elseif ( strpos( $r->to_status, 'takedown' ) !== false ) {
                    $icon = '⚠'; $color = 'warning';
                }
                $events[] = [
                    'type'   => 'release',
                    'sub'    => $event_sub,
                    'icon'   => $icon,
                    'date'   => $r->created_at,
                    'user'   => $r->changed_by ?: 'sistema',
                    'title'  => $title,
                    'detail' => ($r->title ?: 'Release #' . $r->release_id) . ' · ' . ($r->artist_name ?: '—') .
                                ( $r->reason_text ? ' — ' . $r->reason_text : '' ),
                    'url'    => admin_url('admin.php?page=rmbz-admin-distribution&tab=approval&release_id=' . $r->release_id),
                    'color'  => $color,
                ];
            }
        }
    }

    // ─── Payouts ─────────────────────────────────────────────────────────
    $t_payouts = $prefix . 'rmbz_distro_payouts';
    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_payouts'") === $t_payouts ) {
        if ( $f_type === '' || $f_type === 'payout' ) {
            $t_wallets = $prefix . 'rmbz_wallets';
            $rows = $wpdb->get_results( $wpdb->prepare(
                "SELECT p.id, p.artist_telemovel, p.amount_usd, p.method, p.status,
                        p.paid_at, p.paid_by, p.reverted_at,
                        w.user_nome
                   FROM $t_payouts p
              LEFT JOIN $t_wallets w ON w.user_telemovel = p.artist_telemovel
                  WHERE (p.paid_at BETWEEN %s AND %s) OR (p.reverted_at BETWEEN %s AND %s)
                  LIMIT 200",
                $from_dt, $to_dt, $from_dt, $to_dt
            ) );
            foreach ( $rows as $r ) {
                $artist = $r->user_nome ?: $r->artist_telemovel;
                if ( $r->paid_at && $r->paid_at >= $from_dt && $r->paid_at <= $to_dt ) {
                    $events[] = [
                        'type'   => 'payout',
                        'sub'    => 'created',
                        'icon'   => '💸',
                        'date'   => $r->paid_at,
                        'user'   => $r->paid_by ?: 'sistema',
                        'title'  => 'Pagamento registado',
                        'detail' => $artist . ' · $' . number_format( (float) $r->amount_usd, 2) . ' · ' . $r->method,
                        'url'    => admin_url('admin.php?page=rmbz-admin-distribution&tab=royalties&rsub=payouts'),
                        'color'  => 'success',
                    ];
                }
                if ( $r->reverted_at && $r->reverted_at >= $from_dt && $r->reverted_at <= $to_dt ) {
                    $events[] = [
                        'type'   => 'payout',
                        'sub'    => 'reverted',
                        'icon'   => '⟲',
                        'date'   => $r->reverted_at,
                        'user'   => 'sistema',
                        'title'  => 'Pagamento revertido',
                        'detail' => $artist . ' · $' . number_format( (float) $r->amount_usd, 2),
                        'url'    => admin_url('admin.php?page=rmbz-admin-distribution&tab=royalties&rsub=payouts'),
                        'color'  => 'danger',
                    ];
                }
            }
        }
    }

    // ─── Match review ────────────────────────────────────────────────────
    $t_mr = $prefix . 'rmbz_distro_match_review';
    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_mr'") === $t_mr ) {
        if ( $f_type === '' || $f_type === 'match' ) {
            // Agregar por reviewer/data — milhares de matches são geralmente em batch
            $rows = $wpdb->get_results( $wpdb->prepare(
                "SELECT DATE(reviewed_at) AS dt, reviewed_by, status,
                        COUNT(*) AS n,
                        SUM(csv_amount_usd) AS total_usd,
                        MIN(reviewed_at) AS earliest,
                        MAX(reviewed_at) AS latest
                   FROM $t_mr
                  WHERE reviewed_at BETWEEN %s AND %s
                    AND status IN ('approved', 'rejected')
                  GROUP BY DATE(reviewed_at), reviewed_by, status
                  ORDER BY latest DESC
                  LIMIT 100",
                $from_dt, $to_dt
            ) );
            foreach ( $rows as $r ) {
                $is_approved = ( $r->status === 'approved' );
                $events[] = [
                    'type'   => 'match',
                    'sub'    => $r->status,
                    'icon'   => $is_approved ? '🧩' : '✗',
                    'date'   => $r->latest,
                    'user'   => $r->reviewed_by ?: 'sistema',
                    'title'  => $is_approved ? "Matches aprovados ({$r->n})" : "Matches rejeitados ({$r->n})",
                    'detail' => '$' . number_format( (float) $r->total_usd, 2) . ' USD · ' . $r->n . ' linha(s)',
                    'url'    => admin_url('admin.php?page=rmbz-admin-distribution&tab=match_review'),
                    'color'  => $is_approved ? 'success' : 'warning',
                ];
            }
        }
    }

    // ── Aplicar filtros adicionais (user, search) ──────────────────────────
    if ( $f_user ) {
        $events = array_filter( $events, function ($e) use ($f_user) {
            return stripos( $e['user'], $f_user ) !== false;
        } );
    }
    if ( $f_search ) {
        $events = array_filter( $events, function ($e) use ($f_search) {
            return ( stripos( $e['title'], $f_search ) !== false ) ||
                   ( stripos( $e['detail'], $f_search ) !== false );
        } );
    }

    // ── Ordenar por data desc ─────────────────────────────────────────────
    usort( $events, function ($a, $b) {
        return strcmp( $b['date'], $a['date'] );
    } );
    $events = array_slice( $events, 0, 300 );

    // ── Estatísticas por tipo (para mostrar no header) ────────────────────
    $count_by_type = [
        'import'  => 0, 'release' => 0, 'payout'  => 0, 'match'   => 0,
    ];
    foreach ( $events as $e ) {
        if ( isset($count_by_type[$e['type']]) ) $count_by_type[$e['type']]++;
    }

    // ── Type labels ───────────────────────────────────────────────────────
    $type_labels = [
        ''         => 'Todos',
        'import'   => '📥 Imports',
        'release'  => '📋 Releases',
        'payout'   => '💸 Pagamentos',
        'match'    => '🧩 Matches',
    ];
    ?>

    <div class="rau-page">

        <div class="rau-head">
            <h2>📜 Log de auditoria</h2>
            <p>Quem fez o quê e quando · todas as alterações importantes do sistema</p>
        </div>

        <?php // ── Stats por tipo ────────────────────────────────────────── ?>
        <div class="rau-stats">
            <?php foreach ( $count_by_type as $tk => $n ):
                $url = add_query_arg([
                    'page' => 'rmbz-admin-distribution',
                    'tab'  => 'royalties',
                    'rsub' => 'audit',
                    'au_type' => $tk,
                    'au_from' => $f_from,
                    'au_to'   => $f_to,
                ], admin_url('admin.php'));
                $active = ($f_type === $tk);
            ?>
                <a href="<?php echo esc_url($url); ?>" class="rau-stat <?php echo $active ? 'active' : ''; ?>">
                    <div class="lbl"><?php echo esc_html( $type_labels[$tk] ); ?></div>
                    <div class="val"><?php echo $n; ?></div>
                </a>
            <?php endforeach; ?>
        </div>

        <?php // ── Filtros ──────────────────────────────────────────────── ?>
        <form method="get" class="rau-filters">
            <input type="hidden" name="page" value="rmbz-admin-distribution">
            <input type="hidden" name="tab" value="royalties">
            <input type="hidden" name="rsub" value="audit">

            <div class="fg">
                <label>Tipo</label>
                <select name="au_type">
                    <?php foreach ( $type_labels as $tk => $tl ): ?>
                        <option value="<?php echo esc_attr($tk); ?>" <?php selected($f_type, $tk); ?>><?php echo esc_html($tl); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fg">
                <label>De</label>
                <input type="date" name="au_from" value="<?php echo esc_attr($f_from); ?>">
            </div>
            <div class="fg">
                <label>Até</label>
                <input type="date" name="au_to" value="<?php echo esc_attr($f_to); ?>">
            </div>
            <div class="fg">
                <label>Utilizador</label>
                <input type="text" name="au_user" value="<?php echo esc_attr($f_user); ?>" placeholder="login...">
            </div>
            <div class="fg">
                <label>Pesquisa</label>
                <input type="text" name="au_search" value="<?php echo esc_attr($f_search); ?>" placeholder="texto livre...">
            </div>
            <div class="fa">
                <button type="submit" class="button button-primary">🔍 Filtrar</button>
                <a href="<?php echo esc_url( admin_url('admin.php?page=rmbz-admin-distribution&tab=royalties&rsub=audit') ); ?>" class="button">✗ Limpar</a>
            </div>
        </form>

        <?php // ── Timeline ─────────────────────────────────────────────── ?>
        <?php if ( empty($events) ): ?>
            <div class="rau-empty">
                <h3>📭 Nenhum evento neste período</h3>
                <p>Tenta alargar o intervalo de datas ou mudar os filtros.</p>
            </div>
        <?php else: ?>
            <?php
            // Agrupar por dia para mostrar separadores
            $current_day = '';
            $first_day = true;
            foreach ( $events as $e ):
                $event_day = date('Y-m-d', strtotime( $e['date'] ));
                if ( $event_day !== $current_day ):
                    if ( ! $first_day ): ?>
                        </div>
                    <?php endif;
                    $first_day = false;
                    $current_day = $event_day;
            ?>
                <div class="rau-day-group">
                    <div class="rau-day-header"><?php echo esc_html( date_i18n('l, j \d\e F \d\e Y', strtotime($event_day)) ); ?></div>
            <?php endif; ?>
                <div class="rau-event rau-color-<?php echo esc_attr($e['color']); ?>">
                    <div class="rau-event-icon"><?php echo esc_html($e['icon']); ?></div>
                    <div class="rau-event-time">
                        <?php echo esc_html( date('H:i', strtotime( $e['date'] )) ); ?>
                    </div>
                    <div class="rau-event-body">
                        <strong><?php echo esc_html($e['title']); ?></strong>
                        <p><?php echo esc_html($e['detail']); ?></p>
                    </div>
                    <div class="rau-event-user">
                        <code><?php echo esc_html($e['user']); ?></code>
                    </div>
                    <?php if ( ! empty($e['url']) ): ?>
                        <a href="<?php echo esc_url($e['url']); ?>" class="rau-event-link" title="Ir ao detalhe">→</a>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
            <?php if ( ! $first_day ): ?></div><?php endif; // fecha último grupo ?>
            <?php if ( count($events) >= 300 ): ?>
                <div class="rau-foot">
                    <small>⚠ Mostrando os 300 eventos mais recentes. Use filtros mais restritivos para refinar.</small>
                </div>
            <?php endif; ?>
        <?php endif; ?>

    </div>

    <style>
    .rau-page { font-family: -apple-system, system-ui, sans-serif; max-width: 1100px; }
    .rau-head h2 { margin: 0 0 4px 0; font-size: 18px; }
    .rau-head p { margin: 0 0 16px 0; color: #6b7280; font-size: 12px; }

    .rau-stats {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
        gap: 8px; margin-bottom: 14px;
    }
    .rau-stat {
        background: #fff; border: 1px solid #e5e5e5;
        border-radius: 8px; padding: 10px 14px;
        text-decoration: none; color: inherit;
        transition: all 0.15s;
        display: block;
    }
    .rau-stat:hover { background: #fffbeb; border-color: #fcd34d; }
    .rau-stat.active {
        background: linear-gradient(135deg, #fffbeb, #fef3c7);
        border-color: #f0b90b;
    }
    .rau-stat .lbl { font-size: 11px; color: #6b7280; }
    .rau-stat .val {
        font-size: 22px; font-weight: 600; color: #1a1a1a;
        font-variant-numeric: tabular-nums; margin-top: 2px;
    }

    .rau-filters {
        background: #fff; border: 1px solid #e5e5e5;
        border-radius: 8px; padding: 10px 14px; margin-bottom: 14px;
        display: flex; gap: 10px; align-items: flex-end; flex-wrap: wrap;
    }
    .rau-filters .fg label {
        display: block; font-size: 10px; color: #666;
        text-transform: uppercase; font-weight: 600; margin-bottom: 4px;
    }
    .rau-filters .fg input, .rau-filters .fg select {
        padding: 6px 9px; border: 1px solid #ddd;
        border-radius: 4px; font-size: 12px;
        min-width: 130px;
    }
    .rau-filters .fa { margin-left: auto; display: flex; gap: 6px; }

    .rau-day-group { margin-bottom: 18px; }
    .rau-day-header {
        font-size: 11px; color: #6b7280;
        text-transform: uppercase; letter-spacing: 0.05em;
        font-weight: 700;
        padding: 8px 14px;
        background: #f9fafb;
        border-radius: 6px;
        margin-bottom: 4px;
    }
    .rau-event {
        display: grid;
        grid-template-columns: 28px 50px 1fr auto 28px;
        gap: 10px; align-items: center;
        padding: 9px 14px;
        background: #fff;
        border: 1px solid #f3f4f6;
        border-left: 3px solid #ccc;
        border-radius: 6px;
        margin-bottom: 3px;
        font-size: 12px;
    }
    .rau-event.rau-color-success { border-left-color: #10b981; }
    .rau-event.rau-color-danger  { border-left-color: #dc2626; }
    .rau-event.rau-color-warning { border-left-color: #f59e0b; }
    .rau-event.rau-color-info    { border-left-color: #3b82f6; }
    .rau-event:hover { background: #fffbeb; }

    .rau-event-icon { font-size: 16px; text-align: center; }
    .rau-event-time {
        font-family: ui-monospace, monospace;
        font-size: 11px; color: #6b7280;
        text-align: right;
    }
    .rau-event-body { min-width: 0; }
    .rau-event-body strong {
        display: block; color: #1a1a1a;
        font-size: 12.5px;
        white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    }
    .rau-event-body p {
        margin: 2px 0 0 0;
        font-size: 11.5px; color: #6b7280;
        white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    }
    .rau-event-user code {
        background: #f3f4f6; padding: 2px 7px; border-radius: 3px;
        font-size: 10px; color: #6b7280;
    }
    .rau-event-link {
        text-align: center;
        text-decoration: none;
        color: #6b7280;
        font-size: 16px;
        border-radius: 50%;
        width: 24px; height: 24px;
        line-height: 24px;
    }
    .rau-event-link:hover { background: #f0b90b; color: #fff; }

    .rau-empty {
        background: #fafafa;
        border: 1px dashed #e5e7eb;
        border-radius: 8px;
        padding: 40px 20px;
        text-align: center;
        color: #6b7280;
    }
    .rau-empty h3 { margin: 0 0 6px 0; font-size: 14px; }

    .rau-foot {
        margin-top: 12px;
        padding: 8px 14px;
        background: #f9fafb;
        border-radius: 6px;
        text-align: center;
        color: #6b7280;
    }
    </style>
    <?php
}
