<?php

/**
 * Audit Alert Service
 *
 * Handles notifications via Email, Slack, and Webhooks for audit completion and alerts
 *
 * @package ProRank\SEO\Services
 * @since   1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Services;

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


/**
 * AuditAlertService class
 */


class AuditAlertService {

    /**
     * Alert channels
     */
    private const CHANNEL_EMAIL = 'email';
    private const CHANNEL_SLACK = 'slack';
    private const CHANNEL_WEBHOOK = 'webhook';
    private const CHANNEL_DISCORD = 'discord';
    private const CHANNEL_TEAMS = 'teams';

    /**
     * Alert severity levels
     */
    private const SEVERITY_CRITICAL = 'critical';
    private const SEVERITY_HIGH = 'high';
    private const SEVERITY_MEDIUM = 'medium';
    private const SEVERITY_LOW = 'low';

    /**
     * Constructor
     */
    public function __construct() {
        // Initialize
    }

    /**
     * Send audit completion alert
     *
     * @param array $audit_data
     * @return array Results for each channel
     */
    public function send_completion_alert(array $audit_data): array {
        $results = [];
        $channels = $this->get_enabled_channels();
        $settings = $this->get_alert_settings();

        // Check if alert should be sent based on conditions
        if (!$this->should_send_alert($audit_data, $settings)) {
            return ['skipped' => true, 'reason' => 'Alert conditions not met'];
        }

        foreach ($channels as $channel) {
            try {
                switch ($channel) {
                    case self::CHANNEL_EMAIL:
                        $results[$channel] = $this->send_email_alert($audit_data);
                        break;
                    case self::CHANNEL_SLACK:
                        $results[$channel] = $this->send_slack_alert($audit_data);
                        break;
                    case self::CHANNEL_DISCORD:
                        $results[$channel] = $this->send_discord_alert($audit_data);
                        break;
                    case self::CHANNEL_TEAMS:
                        $results[$channel] = $this->send_teams_alert($audit_data);
                        break;
                    case self::CHANNEL_WEBHOOK:
                        $results[$channel] = $this->send_webhook_alert($audit_data);
                        break;
                }
            } catch (\Exception $e) {
                $results[$channel] = ['success' => false, 'error' => $e->getMessage()];
            }
        }

        return $results;
    }

    /**
     * Check if alert should be sent based on settings
     *
     * @param array $audit_data
     * @param array $settings
     * @return bool
     */
    private function should_send_alert(array $audit_data, array $settings): bool {
        // Check score threshold
        $score_threshold = $settings['score_threshold'] ?? 70;
        if (($audit_data['score'] ?? 100) >= $score_threshold) {
            // Score is good, check if we still want to notify
            if (!($settings['notify_on_success'] ?? false)) {
                // Check for critical/high issues
                $critical = $audit_data['issue_counts']['critical'] ?? 0;
                $high = $audit_data['issue_counts']['high'] ?? 0;

                if ($critical === 0 && $high === 0) {
                    return false;
                }
            }
        }

        // Check issue thresholds
        $critical_threshold = $settings['critical_threshold'] ?? 1;
        $high_threshold = $settings['high_threshold'] ?? 5;

        $critical = $audit_data['issue_counts']['critical'] ?? 0;
        $high = $audit_data['issue_counts']['high'] ?? 0;

        if ($critical >= $critical_threshold || $high >= $high_threshold) {
            return true;
        }

        // Check score drop
        if (isset($audit_data['score_delta']) && $audit_data['score_delta'] < -10) {
            return true;
        }

        return ($settings['always_notify'] ?? false);
    }

    /**
     * Get enabled alert channels
     *
     * @return array
     */
    private function get_enabled_channels(): array {
        $channels = [];

        if (get_option('prorank_alert_email_enabled', true)) {
            $channels[] = self::CHANNEL_EMAIL;
        }

        if (get_option('prorank_alert_slack_enabled', false)) {
            $channels[] = self::CHANNEL_SLACK;
        }

        if (get_option('prorank_alert_discord_enabled', false)) {
            $channels[] = self::CHANNEL_DISCORD;
        }

        if (get_option('prorank_alert_teams_enabled', false)) {
            $channels[] = self::CHANNEL_TEAMS;
        }

        if (get_option('prorank_alert_webhook_enabled', false)) {
            $channels[] = self::CHANNEL_WEBHOOK;
        }

        return $channels;
    }

    /**
     * Get alert settings
     *
     * @return array
     */
    private function get_alert_settings(): array {
        return [
            'score_threshold' => (int) get_option('prorank_alert_score_threshold', 70),
            'critical_threshold' => (int) get_option('prorank_alert_critical_threshold', 1),
            'high_threshold' => (int) get_option('prorank_alert_high_threshold', 5),
            'notify_on_success' => (bool) get_option('prorank_alert_notify_success', false),
            'always_notify' => (bool) get_option('prorank_alert_always_notify', false),
            'include_details' => (bool) get_option('prorank_alert_include_details', true),
        ];
    }

    /**
     * Send email alert
     *
     * @param array $audit_data
     * @return array
     */
    private function send_email_alert(array $audit_data): array {
        $to = get_option('prorank_alert_email_address', get_option('admin_email'));

        if (empty($to)) {
            return ['success' => false, 'error' => 'No email address configured'];
        }

        $site_name = get_bloginfo('name');
        $score = $audit_data['score'] ?? 0;
        $critical = $audit_data['issue_counts']['critical'] ?? 0;
        $high = $audit_data['issue_counts']['high'] ?? 0;
        $medium = $audit_data['issue_counts']['medium'] ?? 0;
        $total = $audit_data['issue_counts']['total'] ?? 0;

        $subject = sprintf(
            '[%s] Site Audit Complete - Score: %d/100',
            $site_name,
            $score
        );

        $body = $this->build_email_body($audit_data, $site_name);

        $headers = [
            'Content-Type: text/html; charset=UTF-8',
            'From: ProRank SEO <noreply@' . wp_parse_url(home_url(), PHP_URL_HOST) . '>',
        ];

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

        return [
            'success' => $sent,
            'to' => $to,
        ];
    }

    /**
     * Build email body
     *
     * @param array $audit_data
     * @param string $site_name
     * @return string
     */
    private function build_email_body(array $audit_data, string $site_name): string {
        $score = $audit_data['score'] ?? 0;
        $critical = $audit_data['issue_counts']['critical'] ?? 0;
        $high = $audit_data['issue_counts']['high'] ?? 0;
        $medium = $audit_data['issue_counts']['medium'] ?? 0;
        $low = $audit_data['issue_counts']['low'] ?? 0;
        $total = $audit_data['issue_counts']['total'] ?? 0;

        $score_color = $score >= 90 ? '#00ba37' : ($score >= 70 ? '#f0b849' : '#d63638');
        $audit_url = admin_url('admin.php?page=prorank-site-audit');

        $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: white; padding: 30px; border-radius: 10px 10px 0 0; }
        .content { background: #fff; padding: 30px; border: 1px solid #e0e0e0; border-top: none; }
        .score-circle { width: 100px; height: 100px; border-radius: 50%; background: ' . $score_color . '; color: white; display: flex; align-items: center; justify-content: center; font-size: 32px; font-weight: bold; margin: 0 auto 20px; }
        .issue-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; margin: 20px 0; }
        .issue-box { padding: 15px; border-radius: 8px; text-align: center; }
        .critical { background: #fef2f2; color: #dc2626; }
        .high { background: #fffbeb; color: #d97706; }
        .medium { background: #eff6ff; color: #2563eb; }
        .low { background: #f0fdf4; color: #16a34a; }
        .issue-count { font-size: 28px; font-weight: bold; }
        .issue-label { font-size: 14px; opacity: 0.8; }
        .btn { display: inline-block; padding: 12px 30px; background: #2563eb; color: white; text-decoration: none; border-radius: 6px; margin-top: 20px; }
        .footer { text-align: center; padding: 20px; color: #666; font-size: 13px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 style="margin:0;">Site Audit Complete</h1>
            <p style="margin:10px 0 0;opacity:0.9;">' . esc_html($site_name) . '</p>
        </div>
        <div class="content">
            <div class="score-circle">' . $score . '</div>
            <p style="text-align:center;color:#666;">SEO Health Score</p>

            <div class="issue-grid">
                <div class="issue-box critical">
                    <div class="issue-count">' . $critical . '</div>
                    <div class="issue-label">Critical</div>
                </div>
                <div class="issue-box high">
                    <div class="issue-count">' . $high . '</div>
                    <div class="issue-label">High</div>
                </div>
                <div class="issue-box medium">
                    <div class="issue-count">' . $medium . '</div>
                    <div class="issue-label">Medium</div>
                </div>
                <div class="issue-box low">
                    <div class="issue-count">' . $low . '</div>
                    <div class="issue-label">Low</div>
                </div>
            </div>

            <p style="text-align:center;"><strong>Total Issues Found: ' . $total . '</strong></p>';

        // Add top issues if available
        if (!empty($audit_data['top_issues'])) {
            $html .= '<h3>Top Issues to Fix:</h3><ul>';
            foreach (array_slice($audit_data['top_issues'], 0, 5) as $issue) {
                $html .= '<li><strong>' . esc_html($issue['title'] ?? $issue['type']) . '</strong> - ' . esc_html($issue['message'] ?? '') . '</li>';
            }
            $html .= '</ul>';
        }

        $html .= '
            <p style="text-align:center;">
                <a href="' . esc_url($audit_url) . '" class="btn">View Full Report</a>
            </p>
        </div>
        <div class="footer">
            <p>This email was sent by ProRank SEO plugin.<br>
            <a href="' . admin_url('admin.php?page=prorank-site-audit#?tab=audit&audit_tab=settings') . '">Manage Alert Settings</a></p>
        </div>
    </div>
</body>
</html>';

        return $html;
    }

    /**
     * Send Slack alert
     *
     * @param array $audit_data
     * @return array
     */
    private function send_slack_alert(array $audit_data): array {
        $webhook_url = get_option('prorank_alert_slack_webhook', '');

        if (empty($webhook_url)) {
            return ['success' => false, 'error' => 'Slack webhook URL not configured'];
        }

        $site_name = get_bloginfo('name');
        $site_url = home_url();
        $score = $audit_data['score'] ?? 0;
        $critical = $audit_data['issue_counts']['critical'] ?? 0;
        $high = $audit_data['issue_counts']['high'] ?? 0;
        $total = $audit_data['issue_counts']['total'] ?? 0;

        $score_emoji = $score >= 90 ? ':white_check_mark:' : ($score >= 70 ? ':warning:' : ':x:');
        $score_color = $score >= 90 ? 'good' : ($score >= 70 ? 'warning' : 'danger');

        $payload = [
            'username' => 'ProRank SEO',
            'icon_emoji' => ':chart_with_upwards_trend:',
            'attachments' => [
                [
                    'color' => $score_color,
                    'fallback' => "Site Audit Complete for $site_name - Score: $score/100",
                    'pretext' => "$score_emoji *Site Audit Complete*",
                    'author_name' => $site_name,
                    'author_link' => $site_url,
                    'title' => "SEO Health Score: $score/100",
                    'title_link' => admin_url('admin.php?page=prorank-site-audit'),
                    'fields' => [
                        [
                            'title' => 'Critical Issues',
                            'value' => (string) $critical,
                            'short' => true,
                        ],
                        [
                            'title' => 'High Priority',
                            'value' => (string) $high,
                            'short' => true,
                        ],
                        [
                            'title' => 'Total Issues',
                            'value' => (string) $total,
                            'short' => true,
                        ],
                        [
                            'title' => 'Audit Time',
                            'value' => current_time('Y-m-d H:i:s'),
                            'short' => true,
                        ],
                    ],
                    'footer' => 'ProRank SEO',
                    'footer_icon' => 'https://prorank.io/favicon.ico',
                    'ts' => time(),
                ],
            ],
        ];

        $response = wp_remote_post($webhook_url, [
            'body' => json_encode($payload),
            'headers' => ['Content-Type' => 'application/json'],
            'timeout' => 15,
        ]);

        if (is_wp_error($response)) {
            return ['success' => false, 'error' => $response->get_error_message()];
        }

        $code = wp_remote_retrieve_response_code($response);
        return [
            'success' => $code === 200,
            'response_code' => $code,
        ];
    }

    /**
     * Send Discord alert
     *
     * @param array $audit_data
     * @return array
     */
    private function send_discord_alert(array $audit_data): array {
        $webhook_url = get_option('prorank_alert_discord_webhook', '');

        if (empty($webhook_url)) {
            return ['success' => false, 'error' => 'Discord webhook URL not configured'];
        }

        $site_name = get_bloginfo('name');
        $score = $audit_data['score'] ?? 0;
        $critical = $audit_data['issue_counts']['critical'] ?? 0;
        $high = $audit_data['issue_counts']['high'] ?? 0;
        $total = $audit_data['issue_counts']['total'] ?? 0;

        $color = $score >= 90 ? 0x00ba37 : ($score >= 70 ? 0xf0b849 : 0xd63638);

        $payload = [
            'username' => 'ProRank SEO',
            'embeds' => [
                [
                    'title' => 'Site Audit Complete',
                    'description' => "**$site_name** audit has finished",
                    'color' => $color,
                    'fields' => [
                        ['name' => 'SEO Score', 'value' => "$score/100", 'inline' => true],
                        ['name' => 'Critical', 'value' => (string) $critical, 'inline' => true],
                        ['name' => 'High', 'value' => (string) $high, 'inline' => true],
                        ['name' => 'Total Issues', 'value' => (string) $total, 'inline' => true],
                    ],
                    'url' => admin_url('admin.php?page=prorank-site-audit'),
                    'timestamp' => wp_date('c'),
                    'footer' => ['text' => 'ProRank SEO'],
                ],
            ],
        ];

        $response = wp_remote_post($webhook_url, [
            'body' => json_encode($payload),
            'headers' => ['Content-Type' => 'application/json'],
            'timeout' => 15,
        ]);

        if (is_wp_error($response)) {
            return ['success' => false, 'error' => $response->get_error_message()];
        }

        $code = wp_remote_retrieve_response_code($response);
        return ['success' => $code >= 200 && $code < 300, 'response_code' => $code];
    }

    /**
     * Send Microsoft Teams alert
     *
     * @param array $audit_data
     * @return array
     */
    private function send_teams_alert(array $audit_data): array {
        $webhook_url = get_option('prorank_alert_teams_webhook', '');

        if (empty($webhook_url)) {
            return ['success' => false, 'error' => 'Teams webhook URL not configured'];
        }

        $site_name = get_bloginfo('name');
        $score = $audit_data['score'] ?? 0;
        $critical = $audit_data['issue_counts']['critical'] ?? 0;
        $high = $audit_data['issue_counts']['high'] ?? 0;
        $total = $audit_data['issue_counts']['total'] ?? 0;

        $color = $score >= 90 ? '00ba37' : ($score >= 70 ? 'f0b849' : 'd63638');

        $payload = [
            '@type' => 'MessageCard',
            '@context' => 'http://schema.org/extensions',
            'themeColor' => $color,
            'summary' => "Site Audit Complete - Score: $score/100",
            'sections' => [
                [
                    'activityTitle' => "Site Audit Complete for $site_name",
                    'activitySubtitle' => current_time('Y-m-d H:i:s'),
                    'activityImage' => 'https://prorank.io/favicon.ico',
                    'facts' => [
                        ['name' => 'SEO Score', 'value' => "$score/100"],
                        ['name' => 'Critical Issues', 'value' => (string) $critical],
                        ['name' => 'High Priority', 'value' => (string) $high],
                        ['name' => 'Total Issues', 'value' => (string) $total],
                    ],
                    'markdown' => true,
                ],
            ],
            'potentialAction' => [
                [
                    '@type' => 'OpenUri',
                    'name' => 'View Report',
                    'targets' => [
                        ['os' => 'default', 'uri' => admin_url('admin.php?page=prorank-site-audit')],
                    ],
                ],
            ],
        ];

        $response = wp_remote_post($webhook_url, [
            'body' => json_encode($payload),
            'headers' => ['Content-Type' => 'application/json'],
            'timeout' => 15,
        ]);

        if (is_wp_error($response)) {
            return ['success' => false, 'error' => $response->get_error_message()];
        }

        $code = wp_remote_retrieve_response_code($response);
        return ['success' => $code >= 200 && $code < 300, 'response_code' => $code];
    }

    /**
     * Send generic webhook alert
     *
     * @param array $audit_data
     * @return array
     */
    private function send_webhook_alert(array $audit_data): array {
        $webhook_url = get_option('prorank_alert_webhook_url', '');

        if (empty($webhook_url)) {
            return ['success' => false, 'error' => 'Webhook URL not configured'];
        }

        $webhook_secret = get_option('prorank_alert_webhook_secret', '');

        $payload = [
            'event' => 'audit_complete',
            'timestamp' => time(),
            'site_url' => home_url(),
            'site_name' => get_bloginfo('name'),
            'audit_id' => $audit_data['audit_id'] ?? null,
            'score' => $audit_data['score'] ?? 0,
            'issue_counts' => $audit_data['issue_counts'] ?? [],
            'duration' => $audit_data['duration'] ?? null,
        ];

        $headers = ['Content-Type' => 'application/json'];

        // Add signature if secret is configured
        if (!empty($webhook_secret)) {
            $signature = hash_hmac('sha256', json_encode($payload), $webhook_secret);
            $headers['X-ProRank-Signature'] = $signature;
        }

        $response = wp_remote_post($webhook_url, [
            'body' => json_encode($payload),
            'headers' => $headers,
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            return ['success' => false, 'error' => $response->get_error_message()];
        }

        $code = wp_remote_retrieve_response_code($response);
        return [
            'success' => $code >= 200 && $code < 300,
            'response_code' => $code,
            'response_body' => wp_remote_retrieve_body($response),
        ];
    }

    /**
     * Test alert channel
     *
     * @param string $channel
     * @return array
     */
    public function test_channel(string $channel): array {
        $test_data = [
            'score' => 75,
            'audit_id' => 'test-' . time(),
            'issue_counts' => [
                'critical' => 2,
                'high' => 5,
                'medium' => 10,
                'low' => 15,
                'warning' => 8,
                'total' => 40,
            ],
            'top_issues' => [
                ['type' => 'missing_meta_description', 'title' => 'Missing Meta Description', 'message' => '5 pages missing meta descriptions'],
                ['type' => 'no_https', 'title' => 'HTTPS Not Enabled', 'message' => 'Site is not using HTTPS'],
            ],
        ];

        switch ($channel) {
            case self::CHANNEL_EMAIL:
                return $this->send_email_alert($test_data);
            case self::CHANNEL_SLACK:
                return $this->send_slack_alert($test_data);
            case self::CHANNEL_DISCORD:
                return $this->send_discord_alert($test_data);
            case self::CHANNEL_TEAMS:
                return $this->send_teams_alert($test_data);
            case self::CHANNEL_WEBHOOK:
                return $this->send_webhook_alert($test_data);
            default:
                return ['success' => false, 'error' => 'Unknown channel'];
        }
    }
}
