<?php
/**
 * Wally Monitor - Export Handler
 *
 * Gerencia exportação de relatórios (JSON, CSV, PDF).
 *
 * @package    WallyMonitor
 * @subpackage Includes
 * @since      1.1.0
 */

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

class Wally_Export {

    /**
     * Inicializa hooks de exportação
     */
    public static function init() {
        add_action( 'admin_init', array( new self(), 'handle_export' ) );
    }

    /**
     * Processa requisição de exportação
     */
    public function handle_export() {
        if ( ! isset( $_GET['page'] ) || 'wally-monitor' !== $_GET['page'] || ! isset( $_GET['export'] ) ) {
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Permissão negada.', 'wally-monitor' ) );
        }

        if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'wally_export' ) ) {
            wp_die( esc_html__( 'Ação inválida.', 'wally-monitor' ) );
        }

        $report = get_option( 'wally_monitor_full_report', array() );
        if ( empty( $report ) || ! isset( $report['violations'] ) ) {
            wp_die( esc_html__( 'Nenhum relatório para exportar. Por favor, execute uma análise primeiro.', 'wally-monitor' ) );
        }

        $export_type = sanitize_key( $_GET['export'] );
        $timestamp   = isset( $report['timestamp'] ) ? sanitize_file_name( $report['timestamp'] ) : gmdate( 'Y-m-d_H-i-s' );

        switch ( $export_type ) {
            case 'json':
                $this->export_json( $report, $timestamp );
                break;
            case 'csv':
                $this->export_csv( $report, $timestamp );
                break;
            case 'pdf':
                $this->export_pdf( $report );
                break;
        }
    }

    /**
     * Exporta relatório como JSON
     *
     * @param array  $report    Dados do relatório.
     * @param string $timestamp Timestamp formatado.
     */
    private function export_json( $report, $timestamp ) {
        header( 'Content-Type: application/json' );
        header( 'Content-Disposition: attachment; filename=wally-report-' . $timestamp . '.json' );
        header( 'X-Content-Type-Options: nosniff' );
        echo wp_json_encode( $report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );
        exit;
    }

    /**
     * Exporta relatório como CSV
     *
     * @param array  $report    Dados do relatório.
     * @param string $timestamp Timestamp formatado.
     */
    private function export_csv( $report, $timestamp ) {
        header( 'Content-Type: text/csv; charset=UTF-8' );
        header( 'Content-Disposition: attachment; filename=wally-report-' . $timestamp . '.csv' );
        header( 'X-Content-Type-Options: nosniff' );

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- UTF-8 BOM required for Excel
        echo "\xEF\xBB\xBF";

        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen
        $output = fopen( 'php://output', 'w' );
        fputcsv( $output, array(
            __( 'ID da Regra', 'wally-monitor' ),
            __( 'Impacto', 'wally-monitor' ),
            __( 'Descrição', 'wally-monitor' ),
            __( 'URL do Elemento', 'wally-monitor' ),
            __( 'Seletor do Elemento', 'wally-monitor' ),
        ) );

        foreach ( $report['violations'] as $violation ) {
            $nodes = isset( $violation['nodes'] ) ? $violation['nodes'] : array();
            foreach ( $nodes as $node ) {
                fputcsv( $output, array(
                    $violation['id'],
                    $violation['impact'],
                    $violation['description'],
                    isset( $node['pageUrl'] ) ? $node['pageUrl'] : '',
                    isset( $node['target'][0] ) ? $node['target'][0] : '',
                ) );
            }
        }

        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
        fclose( $output );
        exit;
    }

    /**
     * Exporta relatório como PDF executivo
     *
     * @param array $report Dados do relatório.
     */
    private function export_pdf( $report ) {
        require_once WALLY_MONITOR_PLUGIN_DIR . 'includes/class-wally-pdf-generator.php';

        try {
            // Generate PDF as string first (no output yet)
            $pdf_generator = new Wally_PDF_Generator();
            $pdf_content   = $pdf_generator->generate_executive_report( $report );
        } catch ( \Exception $e ) {
            wp_die(
                esc_html(
                    sprintf(
                        /* translators: %s: error message */
                        __( 'Erro ao gerar PDF: %s', 'wally-monitor' ),
                        $e->getMessage()
                    )
                ),
                esc_html__( 'Erro na Exportação', 'wally-monitor' ),
                array( 'response' => 500, 'back_link' => true )
            );
            return;
        } catch ( \Error $e ) {
            wp_die(
                esc_html(
                    sprintf(
                        /* translators: %s: error message */
                        __( 'Erro fatal ao gerar PDF: %s', 'wally-monitor' ),
                        $e->getMessage()
                    )
                ),
                esc_html__( 'Erro na Exportação', 'wally-monitor' ),
                array( 'response' => 500, 'back_link' => true )
            );
            return;
        }

        // Now clean ALL output buffers (WordPress stacks multiple levels)
        while ( ob_get_level() ) {
            ob_end_clean();
        }

        $timestamp = isset( $report['timestamp'] ) ? sanitize_file_name( $report['timestamp'] ) : gmdate( 'Y-m-d_H-i-s' );
        $filename  = 'wally-executive-report-' . $timestamp . '.pdf';

        // Send headers
        header( 'Content-Type: application/pdf' );
        header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
        header( 'Content-Length: ' . strlen( $pdf_content ) );
        header( 'Cache-Control: private, max-age=0, must-revalidate' );
        header( 'Pragma: public' );
        header( 'X-Content-Type-Options: nosniff' );

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Binary PDF data
        echo $pdf_content;
        exit;
    }
}
