<?php

namespace UltraguardPro\modules\compliance_reports\pages;

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

use UltraguardPro\Plugin;
use UltraguardPro\modules\compliance_reports\ReportBuilderEngine;
use UltraguardPro\modules\core\BasePage;

class ComplianceReportsDashboard extends BasePage {

    private ?ReportBuilderEngine $engine = null;

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
        $this->ajax_nonce_action = 'ultraguard_admin_nonce';
    }

    public function get_scheme( $context ): array {
        $is_pro = \UltraguardPro\support\LicenseInfo::instance()->isPro();
        $preview_mode = $this->is_soft_gated_module_preview( 'compliance_reports' );

        $engine   = $this->engine();
        if ( $preview_mode ) {
            $reports = $this->preview_reports();
        } else {
            $table   = $this->plugin->modules->get_db_tables()->get_table( 'generated_reports' );
            $reports = $table && method_exists( $table, 'get_recent' ) ? $table->get_recent( 25 ) : [];
        }
        $sections = $engine->get_available_sections();
        $stats    = $this->build_stats( $reports );

        $data = [
            ! $is_pro ? $this->pro_upsell_card( 'compliance_reports' ) : [],
            $preview_mode ? $this->soft_gated_preview_data_notice(
                __( 'Compliance Reports', 'ultraguard-security-suite' ),
                __( 'These generated reports and evidence summaries are sample artifacts that demonstrate the final audit output. Upgrade to build reports from your site\'s real security activity.', 'ultraguard-security-suite' )
            ) : [],
        ];

        return [
            'type'      => 'page',
            'id'        => 'compliance-reports-dashboard',
            'page_slug' => 'compliance-reports',
            'header'    => [
                'title'    => __( 'Compliance Reports', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Generate audit-ready compliance reports from UltraGuard security activity. Open in browser and use Print → Save as PDF to download.', 'ultraguard-security-suite' ),
                'actions'  => [
                    $this->create_url_button( __( 'Settings', 'ultraguard-security-suite' ), $this->get_page_url( 'compliance-reports-settings' ), 'secondary', 'dashicons-admin-settings' ),
                    $this->create_ajax_button( __( 'Generate Security Audit', 'ultraguard-security-suite' ), 'ultraguard_compliance_generate', [
                        'report_type' => 'security_audit',
                        'report_title'=> __( 'Security Audit Report', 'ultraguard-security-suite' ),
                        'date_from'   => gmdate( 'Y-m-01' ),
                        'date_to'     => gmdate( 'Y-m-d' ),
                        'format'      => 'html',
                        'sections'    => $engine->get_default_sections_for_type( 'security_audit' ),
                    ], 'primary', 'dashicons-media-document' ),
                ],
            ],
            'data'      => $this->prepend_soft_gated_module_notice( 'compliance_reports', __( 'Compliance Reports', 'ultraguard-security-suite' ), array_merge( array_values( array_filter( $data ) ), [
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Reports Generated', 'ultraguard-security-suite' ), 'value' => $stats['total'], 'format' => 'number', 'icon' => 'dashicons-media-spreadsheet', 'class' => 'info' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Completed', 'ultraguard-security-suite' ), 'value' => $stats['complete'], 'format' => 'number', 'icon' => 'dashicons-yes-alt', 'class' => 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Failed', 'ultraguard-security-suite' ), 'value' => $stats['failed'], 'format' => 'number', 'icon' => 'dashicons-warning', 'class' => $stats['failed'] > 0 ? 'danger' : 'secondary' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Available Sections', 'ultraguard-security-suite' ), 'value' => count( $sections ), 'format' => 'number', 'icon' => 'dashicons-list-view', 'class' => 'secondary' ] ],
                    ],
                ],
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '18px',
                    'items'   => [
                        [ 'span' => 3, 'component' => $this->report_card( 'gdpr', __( 'GDPR Report', 'ultraguard-security-suite' ), __( 'Privacy, access control, and incident evidence for GDPR-oriented reviews.', 'ultraguard-security-suite' ), 'dashicons-shield-alt' ) ],
                        [ 'span' => 3, 'component' => $this->report_card( 'pci_dss', __( 'PCI-DSS Report', 'ultraguard-security-suite' ), __( 'Patch, firewall, and authentication controls aligned to Level 4 evidence needs.', 'ultraguard-security-suite' ), 'dashicons-lock' ) ],
                        [ 'span' => 3, 'component' => $this->report_card( 'security_audit', __( 'Security Audit', 'ultraguard-security-suite' ), __( 'A broad operational report for security reviews and client hand-offs.', 'ultraguard-security-suite' ), 'dashicons-search' ) ],
                        [ 'span' => 3, 'component' => $this->report_card( 'custom', __( 'Custom Report', 'ultraguard-security-suite' ), __( 'Choose the exact sections and export format you need.', 'ultraguard-security-suite' ), 'dashicons-admin-generic' ) ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Report Generator', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-media-document',
                    'data'  => [
                        [
                            'type'    => 'html',
                            'content' => '<div class="ug-compliance-generator"><p>' . esc_html__( 'Use the buttons above for one-click reports, or build a custom report by selecting a format and sections below.', 'ultraguard-security-suite' ) . '</p><p><strong>' . esc_html__( 'Default range:', 'ultraguard-security-suite' ) . '</strong> ' . esc_html( gmdate( 'Y-m-01' ) . ' to ' . gmdate( 'Y-m-d' ) ) . '</p></div>',
                        ],
                        [
                            'type'    => 'data-table',
                            'id'      => 'compliance-available-sections',
                            'columns' => [
                                'section'      => [ 'title' => __( 'Section', 'ultraguard-security-suite' ) ],
                                'availability' => [ 'title' => __( 'Availability', 'ultraguard-security-suite' ) ],
                            ],
                            'data'    => array_map( static function ( $id, $label ) {
                                return [
                                    'id'           => 'section-' . $id,
                                    'section'      => esc_html( $label ),
                                    'availability' => [ 'content' => esc_html__( 'Ready', 'ultraguard-security-suite' ), 'class' => 'success' ],
                                ];
                            }, array_keys( $sections ), array_values( $sections ) ),
                        ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Generated Reports', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-portfolio',
                    'data'  => [
                        [
                            'type'       => 'data-table',
                            'id'         => 'compliance-generated-reports',
                            'columns'    => [
                                'title'       => [ 'title' => __( 'Title', 'ultraguard-security-suite' ) ],
                                'type'        => [ 'title' => __( 'Type', 'ultraguard-security-suite' ) ],
                                'date_range'  => [ 'title' => __( 'Date Range', 'ultraguard-security-suite' ) ],
                                'generated_by'=> [ 'title' => __( 'Generated By', 'ultraguard-security-suite' ) ],
                                'created_at'  => [ 'title' => __( 'Date', 'ultraguard-security-suite' ) ],
                                'format'      => [ 'title' => __( 'Format', 'ultraguard-security-suite' ) ],
                                'size'        => [ 'title' => __( 'Size', 'ultraguard-security-suite' ) ],
                                'actions'     => [ 'title' => __( 'Actions', 'ultraguard-security-suite' ) ],
                            ],
                            'data'       => $this->build_report_rows( $reports ),
                            'searchable' => true,
                            'pagination' => [ 'enabled' => true, 'page_size' => 15 ],
                        ],
                    ],
                ],
            ] ) ),
            'form'      => [ 'enable' => false ],
        ];
    }

    private function report_card( string $type, string $title, string $description, string $icon ): array {
        return [
            'type'  => 'card',
            'title' => $title,
            'icon'  => $icon,
            'data'  => [
                [ 'type' => 'paragraph', 'content' => $description ],
                [ 'type' => 'paragraph', 'content' => __( 'Opens in a new tab. Use Print → Save as PDF to download.', 'ultraguard-security-suite' ) ],
                /* translators: %s: string */
                [ 'type' => 'paragraph', 'content' => sprintf( __( 'Includes: %s', 'ultraguard-security-suite' ), implode( ', ', $this->engine()->get_default_sections_for_type( $type ) ) ) ],
                [
                    'type'         => 'button',
                    'text'         => __( 'Generate', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                    'icon'         => 'dashicons-media-document',
                    'ajax'         => [
                        'action' => 'ultraguard_compliance_generate',
                        'nonce'  => $this->create_nonce( 'ultraguard_admin_nonce' ),
                        'data'   => [
                            'report_type'  => $type,
                            'report_title' => $title,
                            'date_from'    => gmdate( 'Y-m-01' ),
                            'date_to'      => gmdate( 'Y-m-d' ),
                            'format'       => 'html', // always HTML; browser print handles PDF
                        ],
                    ],
                ],
            ],
        ];
    }

    private function build_report_rows( array $reports ): array {
        $rows = [];
        foreach ( $reports as $index => $report ) {
            $report_id = (int) ( $report['id'] ?? 0 );
            $user      = ! empty( $report['generated_by'] ) ? get_userdata( (int) $report['generated_by'] ) : null;
            $has_file  = ! empty( $report['file_path'] ) && file_exists( $report['file_path'] );

            $rows[] = [
                'id'           => 'report-' . $index,
                'title'        => esc_html( (string) $report['report_title'] ),
                'type'         => [ 'content' => esc_html( strtoupper( str_replace( '_', ' ', (string) $report['report_type'] ) ) ), 'class' => 'info' ],
                'date_range'   => esc_html( (string) $report['date_range_from'] . ' → ' . (string) $report['date_range_to'] ),
                'generated_by' => esc_html( $user ? $user->display_name : __( 'System', 'ultraguard-security-suite' ) ),
                'created_at'   => esc_html( $this->format_date_time( (string) $report['created_at'] ) ),
                'format'       => [ 'content' => __( 'HTML (Print)', 'ultraguard-security-suite' ), 'class' => 'info' ],
                'size'         => esc_html( size_format( (int) ( $report['file_size'] ?? 0 ) ) ),
                'actions'      => $this->row_actions( array_filter( [
                    // Print / Download PDF button — opens the report in a new tab
                    // with a print toolbar and auto-opens the browser print dialog
                    $has_file ? [
                        'type'         => 'button',
                        'text'         => __( 'Print / Download PDF', 'ultraguard-security-suite' ),
                        'button_style' => 'primary',
                        'icon'         => 'dashicons-media-document',
                        'url'          => $this->get_print_url( $report_id ),
                        'target'       => '_blank',
                    ] : [
                        'type'         => 'button',
                        'text'         => __( 'File Missing', 'ultraguard-security-suite' ),
                        'button_style' => 'secondary',
                        'disabled'     => true,
                    ],
                    [
                        'type'         => 'button',
                        'text'         => __( 'Delete', 'ultraguard-security-suite' ),
                        'button_style' => 'secondary',
                        'ajax'         => [
                            'action' => 'ultraguard_compliance_delete_report',
                            'nonce'  => $this->create_nonce( 'ultraguard_admin_nonce' ),
                            'data'   => [ 'report_id' => $report_id ],
                        ],
                    ],
                ] ) ),
            ];
        }

        return $rows;
    }

    private function build_stats( array $reports ): array {
        $stats = [ 'total' => count( $reports ), 'complete' => 0, 'failed' => 0 ];
        foreach ( $reports as $report ) {
            if ( 'complete' === ( $report['status'] ?? '' ) ) {
                ++$stats['complete'];
            } elseif ( 'failed' === ( $report['status'] ?? '' ) ) {
                ++$stats['failed'];
            }
        }

        return $stats;
    }

    /**
     * Build the URL that opens the report in a standalone printable page.
     * The module's maybe_serve_print_view() handles this request on admin_init.
     */
    private function get_print_url( int $report_id ): string {
        return add_query_arg( [
            'page'             => 'ultraguard-security-suite-dashboard',
            'ug_print_report'  => $report_id,
            'nonce'            => wp_create_nonce( 'ultraguard_print_report_' . $report_id ),
        ], self_admin_url( 'admin.php' ) );
    }

    private function engine(): ReportBuilderEngine {
        if ( null === $this->engine ) {
            $this->engine = new ReportBuilderEngine( $this->plugin );
        }

        return $this->engine;
    }

    private function preview_reports(): array {
        return [
            [
                'id'              => 31,
                'report_title'    => 'Security Audit Report',
                'report_type'     => 'security_audit',
                'date_range_from' => gmdate( 'Y-m-01' ),
                'date_range_to'   => gmdate( 'Y-m-d' ),
                'generated_by'    => 1,
                'created_at'      => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 2 ),
                'file_size'       => 248300,
                'status'          => 'complete',
                'file_path'       => '',
            ],
            [
                'id'              => 32,
                'report_title'    => 'PCI-DSS Report',
                'report_type'     => 'pci_dss',
                'date_range_from' => gmdate( 'Y-m-01', strtotime( '-1 month' ) ),
                'date_range_to'   => gmdate( 'Y-m-t', strtotime( '-1 month' ) ),
                'generated_by'    => 1,
                'created_at'      => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 17 ),
                'file_size'       => 196420,
                'status'          => 'complete',
                'file_path'       => '',
            ],
        ];
    }
}
