<?php
defined( 'ABSPATH' ) || exit;

class SITECL_Email_Report {

    public static function send_now(): bool|WP_Error {
        $last_scan = get_option( 'sitecl_last_scan' );

        if ( empty( $last_scan ) ) {
            return new WP_Error( 'sitecl_no_scan', __( 'Run a site scan first before sending a report.', 'site-cliniq' ) );
        }

        $to      = get_bloginfo( 'admin_email' );
        $subject = sprintf(
            /* translators: %1$s site name, %2$s date */
            __( '[Site CliniQ] Site Health Report for %1$s — %2$s', 'site-cliniq' ),
            get_bloginfo( 'name' ),
            wp_date( get_option( 'date_format' ), strtotime( $last_scan['scanned_at'] ) )
        );

        $html  = self::build_html( $last_scan );
        $plain = self::build_plain_text( $last_scan );

        $headers = [
            'Content-Type: text/html; charset=UTF-8',
            'From: Site CliniQ <' . $to . '>',
        ];

        // Attach plain-text alternative so clients that can't render HTML show real content.
        $set_alt_body = static function ( $phpmailer ) use ( $plain ) {
            $phpmailer->AltBody = $plain;
        };
        add_action( 'phpmailer_init', $set_alt_body );

        $sent = wp_mail( $to, $subject, $html, $headers );

        remove_action( 'phpmailer_init', $set_alt_body );

        if ( ! $sent ) {
            return new WP_Error( 'sitecl_mail_failed', __( 'Email failed to send. Check your WordPress email configuration.', 'site-cliniq' ) );
        }

        update_option( 'sitecl_last_report_sent', current_time( 'mysql' ) );
        return true;
    }

    // -------------------------------------------------------------------------

    private static function build_html( array $scan ): string {
        $summary  = $scan['summary'] ?? [];
        $grade    = SITECL_Health_Score::calculate_grade( $scan['issues'] ?? [] );
        $issues   = $scan['issues'] ?? [];

        $critical_rows = self::render_issue_rows( $issues, 'critical' );
        $warning_rows  = self::render_issue_rows( $issues, 'warning' );
        $info_rows     = self::render_issue_rows( $issues, 'info' );

        $critical_count = $summary['critical'] ?? 0;
        $warning_count  = $summary['warning']  ?? 0;
        $info_count     = $summary['info']     ?? 0;

        $admin_url = esc_url( admin_url( 'admin.php?page=sitecl' ) );
        $site_name = esc_html( get_bloginfo( 'name' ) );
        $grade_str = esc_html( $grade['grade'] );

        return '<!DOCTYPE html>' .
            '<html><head><meta charset="UTF-8"><title>Site CliniQ Report</title></head>' .
            '<body style="font-family:Arial,sans-serif;max-width:640px;margin:0 auto;padding:20px;color:#333;">' .
            '<h1 style="color:#2563eb;">Site CliniQ</h1>' .
            '<h2>Site Health Report &mdash; ' . $site_name . '</h2>' .
            '<p style="font-size:48px;font-weight:bold;color:#1d4ed8;margin:0;">' . $grade_str . '</p>' .
            '<p>' . $critical_count . ' critical &bull; ' . $warning_count . ' warnings &bull; ' . $info_count . ' info</p>' .
            '<hr>' .
            $critical_rows .
            $warning_rows .
            $info_rows .
            '<hr>' .
            '<p><a href="' . $admin_url . '" style="background:#2563eb;color:#fff;padding:10px 20px;text-decoration:none;border-radius:4px;">View Full Report in Dashboard</a></p>' .
            '<p style="color:#888;font-size:12px;">Sent by Site CliniQ &mdash; <a href="' . $admin_url . '">Manage settings</a></p>' .
            '</body></html>';
    }

    private static function render_issue_rows( array $issues, string $severity ): string {
        $colors = [
            'critical' => '#dc2626',
            'warning'  => '#d97706',
            'info'     => '#2563eb',
        ];

        $filtered = array_filter( $issues, fn( $i ) => ( $i['severity'] ?? '' ) === $severity );
        if ( empty( $filtered ) ) {
            return '';
        }

        $color  = $colors[ $severity ];
        $label  = strtoupper( $severity );
        $rows   = '';

        foreach ( $filtered as $issue ) {
            $title  = esc_html( $issue['title'] ?? '' );
            $detail = esc_html( $issue['diagnosis']['fix'] ?? $issue['detail'] ?? '' );
            $rows  .= "<tr><td style='padding:8px 0;border-bottom:1px solid #eee;'><strong style='color:{$color};'>[{$label}]</strong> {$title}<br><span style='color:#555;font-size:13px;'>{$detail}</span></td></tr>\n";
        }

        return "<table width='100%' cellpadding='0' cellspacing='0'>{$rows}</table>";
    }

    private static function build_plain_text( array $scan ): string {
        $summary = $scan['summary'] ?? [];
        $grade   = SITECL_Health_Score::calculate_grade( $scan['issues'] ?? [] );
        $lines   = [
            'Site CliniQ — Site Health Report',
            'Site: ' . get_bloginfo( 'name' ),
            'Grade: ' . $grade['grade'],
            'Critical: ' . ( $summary['critical'] ?? 0 ) . '  Warnings: ' . ( $summary['warning'] ?? 0 ) . '  Info: ' . ( $summary['info'] ?? 0 ),
            '',
        ];

        foreach ( $scan['issues'] ?? [] as $issue ) {
            $lines[] = '[' . strtoupper( $issue['severity'] ?? 'info' ) . '] ' . ( $issue['title'] ?? '' );
            $lines[] = '  ' . ( $issue['diagnosis']['fix'] ?? $issue['detail'] ?? '' );
            $lines[] = '';
        }

        $lines[] = 'View dashboard: ' . esc_url( admin_url( 'admin.php?page=sitecl' ) );

        return implode( "\n", $lines );
    }
}
