<?php

namespace UltraguardPro\modules\compliance_reports;

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

use UltraguardPro\Plugin;
use UltraguardPro\core\MailManager;
use UltraguardPro\modules\core\AbstractModule;

class ComplianceReportsModule extends AbstractModule {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
        $this->plugin->settings->register_module_prefix( 'compliance_reports_', 'compliance_reports' );
    }

    public function get_id(): string {
        return 'compliance_reports';
    }

    protected function requires_pro(): bool {
        return true;
    }

    protected function allow_preview_mode(): bool {
        return true;
    }

    public function boot(): void {
        $_db_tables = $this->plugin->modules->get_db_tables();
        if ( $_db_tables ) {
            $_db_tables->register_schema( new schema\ComplianceReportsSchema() );
        }

        if ( method_exists( $this->plugin->settings, 'register_settings_schema' ) ) {
            $this->plugin->settings->register_settings_schema( 'compliance_reports', 'compliance_reports_', [
                'compliance_reports_organization_name' => [ 'type' => 'text', 'default' => get_bloginfo( 'name' ) ],
                'compliance_reports_contact_name'      => [ 'type' => 'text', 'default' => '' ],
                'compliance_reports_contact_email'     => [ 'type' => 'email', 'default' => get_option( 'admin_email', '' ) ],
                'compliance_reports_include_logo'      => [ 'type' => 'bool', 'default' => false ],
                'compliance_reports_logo_url'          => [ 'type' => 'text', 'default' => '' ],
                'compliance_reports_auto_monthly'      => [ 'type' => 'bool', 'default' => false ],
                'compliance_reports_email_monthly'     => [ 'type' => 'bool', 'default' => false ],
                'compliance_reports_watermark'         => [ 'type' => 'text', 'default' => '' ],
                'compliance_reports_include_raw_logs'  => [ 'type' => 'bool', 'default' => false ],
            ] );
        }

        ( new ajax\ComplianceReportsAjax( $this->plugin ) )->register();
        add_action( 'ultraguard_register_admin_pages', [ $this, 'register_pages' ], 125, 1 );
        add_action( 'ultraguard_after_enqueue_assets', [ $this, 'enqueue_assets' ] );
        add_filter( 'ultraguard_pro/compliance/collect_data', [ $this, 'add_native_sections' ], 10, 4 );
        add_filter( 'ultraguard_pro/compliance/available_sections', [ $this, 'add_available_sections' ] );

        // Print-view handler — serves the saved HTML report as a standalone printable
        // page when ?ug_print_report=<id>&nonce=<nonce> is requested by an admin.
        // Fires on admin_init so WordPress auth is already available.
        add_action( 'admin_init', [ $this, 'maybe_serve_print_view' ] );

        if ( ! $this->is_preview_mode() ) {
            add_filter( 'cron_schedules', [ $this, 'register_cron_schedules' ] );
            add_action( 'wp_loaded', [ $this, 'maybe_setup_schedule' ] );
            add_action( 'ultraguard_compliance_monthly_report', [ $this, 'run_monthly_report' ] );
        }

        do_action( 'ultraguard_pro/compliance_reports/booted', $this );
    }

    public function register_pages( $admin ): void {
        $admin->register_page( [
            'id'              => 'compliance-reports',
            'page_title'      => __( 'Compliance Reports', 'ultraguard-security-suite' ),
            'menu_title'      => __( 'Compliance Reports', 'ultraguard-security-suite' ),
            'capability'      => 'manage_options',
            'scheme_callback' => [ new pages\ComplianceReportsDashboard( $this->plugin ), 'get_scheme' ],
            'parent_id'       => '',
            'priority'        => 125,
            'group'           => 'Management',
            'icon'            => 'dashicons-media-document',
        ] );

        $admin->register_page( [
            'id'              => 'compliance-reports-settings',
            'page_title'      => __( 'Compliance Reports Settings', 'ultraguard-security-suite' ),
            'menu_title'      => __( 'Settings', 'ultraguard-security-suite' ),
            'capability'      => 'manage_options',
            'scheme_callback' => [ new pages\ComplianceReportsSettings( $this->plugin ), 'get_scheme' ],
            'parent_id'       => 'compliance-reports',
            'priority'        => 126,
            'group'           => 'Management',
            'icon'            => 'dashicons-admin-settings',
        ] );
    }


    /**
     * Serve a saved compliance report HTML file as a standalone printable page.
     *
     * URL: wp-admin/admin.php?ug_print_report=<id>&nonce=<nonce>
     *
     * Security: requires manage_options + valid nonce.
     * The file path is resolved from the DB — user never supplies a path directly.
     */
    public function maybe_serve_print_view(): void {
        $report_id = absint( $_GET['ug_print_report'] ?? 0 );
        if ( ! $report_id ) {
            return;
        }

        if ( ! \UltraguardPro\ultraguard_current_user_can_manage() ) {
            wp_die( esc_html__( 'You do not have permission to view this report.', 'ultraguard-security-suite' ), 403 );
        }

        $nonce = sanitize_text_field( wp_unslash( $_GET['nonce'] ?? '' ) );
        if ( ! wp_verify_nonce( $nonce, 'ultraguard_print_report_' . $report_id ) ) {
            wp_die( esc_html__( 'Security check failed. Please reload the reports page and try again.', 'ultraguard-security-suite' ), 403 );
        }

        $db    = $this->plugin->modules->get_db_tables();
        $table = $db ? $db->get_table( 'generated_reports' ) : null;
        if ( ! $table ) {
            wp_die( esc_html__( 'Report database unavailable.', 'ultraguard-security-suite' ), 500 );
        }

        $report = $table->get( $report_id );
        if ( empty( $report['file_path'] ) || ! file_exists( $report['file_path'] ) ) {
            wp_die( esc_html__( 'Report file not found. It may have been deleted.', 'ultraguard-security-suite' ), 404 );
        }

        // Path traversal guard — file must be inside uploads directory
        $upload_base = wp_normalize_path( wp_upload_dir()['basedir'] );
        $real_path   = wp_normalize_path( (string) realpath( $report['file_path'] ) );
        if ( '' === $real_path || ! str_starts_with( $real_path, $upload_base ) ) {
            wp_die( esc_html__( 'Invalid report path.', 'ultraguard-security-suite' ), 403 );
        }

        $html_content = file_get_contents( $real_path );
        if ( false === $html_content ) {
            wp_die( esc_html__( 'Could not read the report file.', 'ultraguard-security-suite' ), 500 );
        }

        $report_title  = esc_html( (string) ( $report['report_title'] ?? 'Compliance Report' ) );
        $dashboard_url = esc_url( admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=compliance-reports' ) );

        $toolbar = '<div id="ug-print-toolbar" style="position:fixed;top:0;left:0;right:0;z-index:99999;background:#0f172a;color:#e2e8f0;padding:10px 24px;display:flex;align-items:center;gap:12px;font-family:system-ui,sans-serif;font-size:14px;box-shadow:0 2px 12px rgba(0,0,0,.4);">'
            . '<span style="flex:1;font-weight:600;color:#93c5fd;">&#128737; UltraGuard &mdash; ' . $report_title . '</span>'
            . '<button onclick="window.print()" style="background:#3b82f6;color:#fff;border:none;border-radius:6px;padding:8px 18px;font-size:13px;font-weight:700;cursor:pointer;">&#128424; Print / Save as PDF</button>'
            . '<button onclick="window.close()" style="background:transparent;color:#94a3b8;border:1px solid #334155;border-radius:6px;padding:8px 14px;font-size:13px;cursor:pointer;">&times; Close</button>'
            . '<a href="' . $dashboard_url . '" style="color:#64748b;font-size:12px;text-decoration:none;padding:8px 10px;border-radius:6px;border:1px solid #1e293b;">&larr; Reports</a>'
            . '</div>'
            . '<div style="height:54px;"></div>'
            . '<style>'
            . '@media print{'
            . '#ug-print-toolbar,div[style*="height:54px"]{display:none!important}'
            . 'body{margin:0!important}'
            . '*{-webkit-print-color-adjust:exact!important;print-color-adjust:exact!important}'
            . 'tr{page-break-inside:avoid}'
            . 'h1,h2,h3{page-break-after:avoid}'
            . '.section{page-break-inside:avoid}'
            . '@page{size:A4;margin:15mm 12mm}'
            . '}'
            . '</style>'
            . '<script>setTimeout(function(){window.print();},700);</script>';

        // Inject toolbar before </body>; append if tag is missing
        if ( false !== stripos( $html_content, '</body>' ) ) {
            $html_content = str_ireplace( '</body>', $toolbar . '</body>', $html_content );
        } else {
            $html_content .= $toolbar;
        }

        nocache_headers();
        header( 'Content-Type: text/html; charset=utf-8' );
        header( 'X-Frame-Options: SAMEORIGIN' );
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $html_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML report content escaped during generation  // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Renderer output, escaped internally via esc_* functions
        exit;
    }

    public function enqueue_assets(): void {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin screen detection.
        $ug_page = sanitize_key( wp_unslash( $_GET['ug_page'] ?? ''  ) );
        if ( ! in_array( $ug_page, [ 'compliance-reports', 'compliance-reports-settings' ], true ) ) {
            return;
        }

        $module_url = plugin_dir_url( __FILE__ );
        $version    = defined( 'ULTRAGUARD_PRO_VERSION' ) ? ULTRAGUARD_PRO_VERSION : '1.0.0';

        wp_enqueue_style(
            'ultraguard-compliance-reports-page',
            $module_url . 'assets/css/compliance-reports-page.css',
            [ 'admin-base', 'admin-components' ],
            $version
        );

        wp_enqueue_script(
            'ultraguard-compliance-reports-page',
            $module_url . 'assets/js/compliance-reports-page.js',
            [ 'jquery', 'ultraguard-core', 'ultraguard-managers' ],
            $version,
            true
        );

        wp_localize_script( 'ultraguard-compliance-reports-page', 'ultraguardComplianceReports', [
            'nonce'   => wp_create_nonce( 'ultraguard_admin_nonce' ),
            'ajaxUrl' => self_admin_url( 'admin-ajax.php' ),
            'i18n'    => [
                'generating' => __( 'Generating report…', 'ultraguard-security-suite' ),
                'generated'  => __( 'Report generated. Click Print / Save PDF in the table below.', 'ultraguard-security-suite' ),
                'failed'     => __( 'Unable to generate the report. Please try again.', 'ultraguard-security-suite' ),
            ],
        ] );
    }

    public function add_available_sections( array $sections ): array {
        return array_merge( $sections, [
            'cover_page'                => __( 'Cover Page', 'ultraguard-security-suite' ),
            'executive_summary'         => __( 'Executive Summary', 'ultraguard-security-suite' ),
            'active_security_controls'  => __( 'Active Security Controls', 'ultraguard-security-suite' ),
            'compliance_checklist'      => __( 'Compliance Checklist', 'ultraguard-security-suite' ),
        ] );
    }

    public function add_native_sections( array $sections, string $type, array $options, array $meta ): array {
        $native = [
            'cover_page'               => $this->build_cover_page( $meta ),
            'executive_summary'        => $this->build_executive_summary( $type, $options, $meta ),
            'active_security_controls' => $this->build_controls_section(),
            'compliance_checklist'     => $this->build_checklist_section( $type ),
        ];

        $requested = isset( $options['sections'] ) && is_array( $options['sections'] ) ? $options['sections'] : array_keys( $native );
        foreach ( $requested as $section_id ) {
            if ( isset( $native[ $section_id ] ) ) {
                $sections[ $section_id ] = $native[ $section_id ];
            }
        }

        return $sections;
    }

    public function register_cron_schedules( array $schedules ): array {
        $schedules['monthly'] = [
            'interval' => MONTH_IN_SECONDS,
            'display'  => 'Once Monthly',
        ];
        return $schedules;
    }

    public function maybe_setup_schedule(): void {
        $hook      = 'ultraguard_compliance_monthly_report';
        $enabled   = $this->option_enabled( 'compliance_reports_auto_monthly' );
        $scheduled = wp_next_scheduled( $hook );

        if ( ! $enabled ) {
            if ( $scheduled ) {
                wp_clear_scheduled_hook( $hook );
            }
            return;
        }

        if ( ! $scheduled ) {
            wp_schedule_event( time() + DAY_IN_SECONDS, 'monthly', $hook );
        }
    }

    public function run_monthly_report(): void {
        $engine = new ReportBuilderEngine( $this->plugin );
        $from   = gmdate( 'Y-m-01', strtotime( 'first day of last month' ) );
        $to     = gmdate( 'Y-m-t', strtotime( 'last day of last month' ) );
        $title  = sprintf( 'Monthly Security Audit %s', gmdate( 'F Y', strtotime( $to ) ) );

        $result = $engine->build_report( 'security_audit', [
            'date_from' => $from,
            'date_to'   => $to,
            'format'    => 'pdf',
            'title'     => $title,
            'sections'  => $engine->get_default_sections_for_type( 'security_audit' ),
        ] );

        if ( ! $this->option_enabled( 'compliance_reports_email_monthly' ) || empty( $result['success'] ) ) {
            return;
        }

        $email = sanitize_email( (string) $this->option( 'compliance_reports_contact_email', get_option( 'admin_email', '' ) ) );
        if ( ! is_email( $email ) ) {
            $email = sanitize_email( (string) get_option( 'admin_email', '' ) );
        }

        if ( ! is_email( $email ) ) {
            return;
        }

        MailManager::report( [
            'to'          => $email,
            /* translators: %s: string */
            'subject'     => sprintf( __( 'UltraGuard Monthly Compliance Report: %s', 'ultraguard-security-suite' ), gmdate( 'F Y', strtotime( $to ) ) ),
            'title'       => __( 'Monthly Compliance Report Ready', 'ultraguard-security-suite' ),
            'message'     => __( 'UltraGuard generated your scheduled monthly security audit report and attached it to this email.', 'ultraguard-security-suite' ),
            'tone'        => 'info',
            'details'     => [
                __( 'Report', 'ultraguard-security-suite' ) => $title,
                __( 'Period', 'ultraguard-security-suite' ) => $from . ' to ' . $to,
                __( 'Format', 'ultraguard-security-suite' ) => strtoupper( (string) ( $result['format'] ?? 'pdf' ) ),
            ],
            'file_path'   => (string) ( $result['file_path'] ?? '' ),
            'filename'    => basename( (string) ( $result['file_path'] ?? '' ) ),
            'mime'        => 'application/pdf',
            'cta_url'     => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=compliance-reports' ),
            'cta_label'   => __( 'Open Compliance Reports', 'ultraguard-security-suite' ),
            'footer_note' => __( 'Scheduled delivery from UltraGuard Compliance Reports.', 'ultraguard-security-suite' ),
        ] );
    }

    private function build_cover_page( array $meta ): array {
        return [
            'title'   => __( 'Cover Page', 'ultraguard-security-suite' ),
            'content' => [
                'site_url'     => home_url(),
                'report_title' => $meta['title'] ?? __( 'Compliance Report', 'ultraguard-security-suite' ),
                'report_date'  => $meta['generated_at'] ?? current_time( 'mysql', true ),
                'generated_by' => $meta['generated_by_name'] ?? __( 'System', 'ultraguard-security-suite' ),
                'organization' => (string) $this->option( 'compliance_reports_organization_name', get_bloginfo( 'name' ) ),
            ],
        ];
    }

    private function build_executive_summary( string $type, array $options, array $meta ): array {
        $security_score  = (int) apply_filters( 'ultraguard_pro/compliance/security_score', 82, $type, $options );
        $critical_issues = (int) apply_filters( 'ultraguard_pro/compliance/critical_issues', 0, $type, $options );
        $incidents       = (int) apply_filters( 'ultraguard_pro/compliance/total_incidents', 0, $type, $options );

        return [
            'title'   => __( 'Executive Summary', 'ultraguard-security-suite' ),
            'content' => [
                'security_score'  => $security_score,
                'critical_issues' => $critical_issues,
                'total_incidents' => $incidents,
                'period'          => [
                    'from' => $meta['date_from'] ?? '',
                    'to'   => $meta['date_to'] ?? '',
                ],
            ],
        ];
    }

    private function build_controls_section(): array {
        $controls = [];
        foreach ( [ 'firewall', 'hardening', 'security_headers', 'antivirus', 'vulnerability', 'loginlimiter', 'authenticator' ] as $module_id ) {
            $module     = $this->plugin->modules->get( $module_id );
            $controls[] = [
                'module_id' => $module_id,
                'label'     => ucwords( str_replace( '_', ' ', $module_id ) ),
                'status'    => $module ? __( 'Active', 'ultraguard-security-suite' ) : __( 'Unavailable', 'ultraguard-security-suite' ),
            ];
        }

        return [
            'title'   => __( 'Active Security Controls', 'ultraguard-security-suite' ),
            'content' => $controls,
        ];
    }

    private function build_checklist_section( string $type ): array {
        $requirements = [
            'gdpr' => [
                [ 'requirement' => 'Security event logging', 'status' => 'pass' ],
                [ 'requirement' => 'Access protection', 'status' => 'pass' ],
                [ 'requirement' => 'Incident visibility', 'status' => 'partial' ],
            ],
            'pci_dss' => [
                [ 'requirement' => 'Patch management', 'status' => 'pass' ],
                [ 'requirement' => 'Authentication controls', 'status' => 'pass' ],
                [ 'requirement' => 'Ongoing monitoring', 'status' => 'partial' ],
            ],
            'security_audit' => [
                [ 'requirement' => 'Hardening baseline', 'status' => 'pass' ],
                [ 'requirement' => 'Threat detection', 'status' => 'pass' ],
                [ 'requirement' => 'Vulnerability review', 'status' => 'pass' ],
            ],
        ];

        return [
            'title'   => __( 'Compliance Checklist', 'ultraguard-security-suite' ),
            'content' => $requirements[ $type ] ?? $requirements['security_audit'],
        ];
    }
}
