<?php
/**
 * includes/admin/import-export-report.php
 *
 * ============================================================================
 * EXPORTAR RELATÓRIO DE IMPORT + VER ERROS DETALHADOS
 * ============================================================================
 *
 * Endpoints:
 *
 *   admin-post.php?action=rmbz_export_import_report&import_id=X
 *     → Download CSV com a distribuição completa do import:
 *       artista, telemóvel, faixa, ISRC, valor, % do total
 *
 *   admin-post.php?action=rmbz_view_import_errors&import_id=X
 *     → Mostra página com a lista de linhas que deram erro/foram skipped
 *
 * Ambos requerem manage_options.
 */

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


/* ============================================================================
 * 1. EXPORTAR RELATÓRIO — CSV download
 * ============================================================================ */

function rmbz_handle_export_import_report() {
    if ( ! current_user_can('manage_options') ) wp_die('Sem permissão.');
    check_admin_referer( 'rmbz_export_import_' . ($_GET['import_id'] ?? ''), '_nonce' );

    global $wpdb;
    $import_id = (int) ($_GET['import_id'] ?? 0);
    if ( $import_id <= 0 ) wp_die('Import ID inválido.');

    $t_logs = $wpdb->prefix . 'rmbz_distro_import_logs';
    $t_ledger = $wpdb->prefix . 'rmbz_distro_ledger';
    $t_wallets = $wpdb->prefix . 'rmbz_wallets';
    $t_tracks = $wpdb->prefix . 'rmbz_distro_tracks';
    $t_releases = $wpdb->prefix . 'rmbz_distro_releases';

    $imp = $wpdb->get_row( $wpdb->prepare(
        "SELECT * FROM {$t_logs} WHERE id = %d", $import_id
    ) );
    if ( ! $imp ) wp_die('Import não encontrado.');

    // Buscar todas as linhas do ledger associadas a este import
    $rows = $wpdb->get_results( $wpdb->prepare(
        "SELECT l.artist_telemovel,
                l.amount,
                l.track_id,
                l.created_at,
                l.reverted_at,
                w.user_nome AS artist_name,
                t.track_title AS track_title,
                t.isrc_code AS track_isrc,
                r.title AS release_title
         FROM {$t_ledger} l
         LEFT JOIN {$t_wallets} w ON w.user_telemovel = l.artist_telemovel
         LEFT JOIN {$t_tracks} t ON t.id = l.track_id
         LEFT JOIN {$t_releases} r ON r.id = t.release_id
         WHERE l.import_hash = %s
         ORDER BY l.amount DESC",
        $imp->file_hash
    ) );

    // Calcular total para % de distribuição
    $total = 0.0;
    foreach ( $rows as $r ) { if ( ! $r->reverted_at ) $total += (float) $r->amount; }

    // Gerar CSV
    $filename = 'import_' . $import_id . '_' . sanitize_file_name( $imp->source_name ?: 'report' ) . '_' . date('Y-m-d') . '.csv';
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Pragma: no-cache');

    $out = fopen('php://output', 'w');
    fwrite($out, "\xEF\xBB\xBF"); // BOM UTF-8 para Excel reconhecer acentos

    fputcsv($out, [
        'Artista (nome)',
        'Telemóvel',
        'Faixa',
        'ISRC interno',
        'Release',
        'Valor (USD)',
        '% do total',
        'Estado',
        'Data do crédito',
    ]);

    foreach ( $rows as $r ) {
        $pct = $total > 0 ? ( (float)$r->amount / $total * 100 ) : 0;
        $estado = $r->reverted_at ? 'REVERTIDO em ' . date_i18n('d/m/Y', strtotime($r->reverted_at)) : 'Activo';
        fputcsv($out, [
            $r->artist_name ?: '(sem nome)',
            $r->artist_telemovel,
            $r->track_title ?: '(faixa apagada)',
            $r->track_isrc ?: '—',
            $r->release_title ?: '—',
            number_format((float)$r->amount, 4, '.', ''),
            number_format($pct, 2, '.', '') . '%',
            $estado,
            date_i18n('d/m/Y H:i', strtotime($r->created_at)),
        ]);
    }

    // Linha de total
    fputcsv($out, []);
    fputcsv($out, ['', '', '', '', 'TOTAL', number_format($total, 4, '.', ''), '100.00%', '', '']);

    fclose($out);
    exit;
}
add_action('admin_post_rmbz_export_import_report', 'rmbz_handle_export_import_report');


/* ============================================================================
 * 2. VER ERROS DETALHADOS — página HTML
 * ============================================================================ */

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

    global $wpdb;
    $import_id = (int) ($_GET['import_id'] ?? 0);
    if ( $import_id <= 0 ) wp_die('Import ID inválido.');

    $t_logs = $wpdb->prefix . 'rmbz_distro_import_logs';
    $imp = $wpdb->get_row( $wpdb->prepare(
        "SELECT * FROM {$t_logs} WHERE id = %d", $import_id
    ) );
    if ( ! $imp ) wp_die('Import não encontrado.');

    $errors = [];
    if ( ! empty($imp->errors_json) ) {
        $errors = json_decode( $imp->errors_json, true ) ?: [];
    }

    $back_url = admin_url('admin.php?page=rmbz-admin-distribution&tab=royalties&rsub=imports');
    ?>
    <div class="wrap">
        <h1>📋 Erros e linhas saltadas — Import #<?php echo $import_id; ?></h1>
        <p><a href="<?php echo esc_url($back_url); ?>" class="button">← Voltar à lista</a></p>

        <div class="card" style="max-width:1000px; padding:20px;">
            <h3 style="margin-top:0;">Resumo</h3>
            <p>
                <strong>Ficheiro:</strong> <?php echo esc_html($imp->file_name ?: '(sem nome)'); ?><br>
                <strong>Distribuidora:</strong> <?php echo esc_html($imp->source_name ?: '—'); ?><br>
                <strong>Período:</strong> <?php echo esc_html($imp->reporting_period ?: '—'); ?><br>
                <strong>Importado em:</strong> <?php echo esc_html( date_i18n('d/m/Y H:i', strtotime($imp->imported_at)) ); ?>
            </p>
            <ul>
                <li>✅ Linhas processadas com sucesso: <strong><?php echo (int) $imp->processed_rows; ?></strong></li>
                <li>📦 Linhas para Não Reclamado: <strong><?php echo (int) $imp->unclaimed_rows; ?></strong></li>
                <li>⏭ Linhas saltadas (erro/inválidas): <strong><?php echo (int) $imp->skipped_rows; ?></strong></li>
                <?php if ( isset($imp->excluded_rows) && (int)$imp->excluded_rows > 0 ): ?>
                    <li>🚫 Linhas excluídas pelo admin: <strong><?php echo (int) $imp->excluded_rows; ?></strong></li>
                <?php endif; ?>
            </ul>
        </div>

        <?php if ( empty($errors) ): ?>
            <div class="card" style="max-width:1000px; padding:20px; margin-top:16px;">
                <p style="margin:0; color:#2ecc71;">
                    <strong>✓ Sem erros detalhados registados.</strong>
                    Se a contagem de "saltadas" é > 0, eram linhas com ISRC vazio ou número de colunas incompatível.
                </p>
            </div>
        <?php else: ?>
            <div class="card" style="max-width:1000px; padding:20px; margin-top:16px;">
                <h3 style="margin-top:0;">Detalhe das linhas com problema (<?php echo count($errors); ?>)</h3>
                <p style="color:#888; font-size:12px;">
                    Mostra até 500 linhas. Se o teu CSV tem mais erros do que isto, considera limpar o CSV antes de re-importar.
                </p>
                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th style="width:80px;">Linha</th>
                            <th>Erro</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ( $errors as $err ): ?>
                        <tr>
                            <td><strong><?php echo (int) ($err['line'] ?? 0); ?></strong></td>
                            <td><?php echo esc_html($err['msg'] ?? ''); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
    <?php
}
