<?php

namespace Bricksforge\ProForms;

if (!defined('ABSPATH')) exit; // Exit if accessed directly

class AdminNotifier
{
    /**
     * Send admin notification email for failed form submission
     *
     * @param int $form_id Form ID
     * @param int|null $post_id Post ID where form was submitted
     * @param array $failed_actions Array of failed actions
     * @param array $action_details Detailed action results
     */
    public static function notify_admin_form_failure($form_id, $post_id, $failed_actions, $action_details)
    {
        $email_sent = false;
        $webhook_sent = false;

        // Check if email notifications are enabled
        $notifications_enabled = get_option('brf_admin_notifications_enabled', true);
        if ($notifications_enabled) {
            // Get admin email (custom or default)
            $admin_email = get_option('brf_admin_notification_email', get_option('admin_email'));
            if ($admin_email) {
                // Prepare email content
                $site_name = get_bloginfo('name');
                $site_url = get_site_url();

                $subject = sprintf('[%s] Form Submission Failed - Form ID: %s', $site_name, $form_id);

                $message = self::build_failure_email_content($form_id, $post_id, $failed_actions, $action_details, $site_name, $site_url);

                // Email headers
                $headers = [
                    'Content-Type: text/html; charset=UTF-8',
                    'From: ' . $site_name . ' <' . $admin_email . '>'
                ];

                // Send email
                $email_sent = wp_mail($admin_email, $subject, $message, $headers);

                // Log the email notification attempt
                if ($email_sent) {
                    ProFormsLogger::log('form_submission', 'info', 'Admin notification email sent for failed form submission', [
                        'notification_type' => 'admin_failure_notification',
                        'admin_email' => $admin_email,
                        'failed_actions_count' => count($failed_actions)
                    ], $form_id, $post_id);
                } else {
                    ProFormsLogger::log('form_submission', 'error', 'Failed to send admin notification email', [
                        'notification_type' => 'admin_failure_notification',
                        'admin_email' => $admin_email,
                        'error' => 'wp_mail_failed'
                    ], $form_id, $post_id);
                }
            }
        }

        // Send webhook notification if enabled (independent of email)
        $webhook_sent = self::send_webhook_notification($form_id, $post_id, $failed_actions, $action_details, 'failure');

        return $email_sent || $webhook_sent;
    }

    /**
     * Build HTML email content for form failure notification
     */
    private static function build_failure_email_content($form_id, $post_id, $failed_actions, $action_details, $site_name, $site_url)
    {
        $timestamp = current_time('Y-m-d H:i:s');
        $post_title = $post_id ? get_the_title($post_id) : 'Unknown Page';
        $post_url = $post_id ? get_permalink($post_id) : $site_url;
        $admin_url = admin_url('admin.php?page=bricksforge#/logs');

        $html = '
        <html>
        <head>
            <meta charset="UTF-8">
            <title>Form Submission Failed</title>
            <style>
                body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background: #f5f5f5; }
                .container { max-width: 500px; margin: 40px auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); border: 1px solid #ddd; }
                .header { background: #333; color: white; padding: 24px; text-align: center; }
                .header h1 { margin: 0; font-size: 20px; font-weight: 600; }
                .header p { margin: 8px 0 0 0; opacity: 0.9; font-size: 14px; }
                .content { padding: 24px; }
                .info-row { display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #eee; }
                .info-row:last-child { border-bottom: none; }
                .info-label { font-weight: 500; color: #666; }
                .info-value { color: #333; }
                .failed-actions { background: #f8f8f8; border: 1px solid #ddd; border-radius: 6px; padding: 16px; margin: 20px 0; }
                .failed-actions h3 { margin: 0 0 12px 0; color: #333; font-size: 16px; }
                .action-list { margin: 0; padding: 0; list-style: none; }
                .action-list li { padding: 4px 0; color: #333; font-weight: 500; }
                .action-list li:before { content: "✗ "; margin-right: 8px; }
                .cta { text-align: center; margin: 24px 0; }
                .cta-button { display: inline-block; background: #333; color: white; text-decoration: none; padding: 12px 24px; border-radius: 6px; font-weight: 500; }
                .footer { background: #f8f8f8; padding: 16px 24px; text-align: center; font-size: 12px; color: #666; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>Form Submission Failed</h1>
                </div>
                
                <div class="content">
                    <div class="info-row">
                        <span class="info-label">Website</span>
                        <span class="info-value">' . esc_html($site_name) . '</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Form ID</span>
                        <span class="info-value">' . esc_html($form_id) . '</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Page</span>
                        <span class="info-value">' . esc_html($post_title) . '</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Time</span>
                        <span class="info-value">' . esc_html($timestamp) . '</span>
                    </div>

                    <div class="cta">
                        <a href="' . esc_url($admin_url) . '" class="cta-button">View Detailed Logs</a>
                    </div>
                
                <div class="footer">
                    <p>Sent automatically by Bricksforge</p>
                </div>
            </div>
        </body>
        </html>';

        return $html;
    }

    /**
     * Send admin notification for partial form failures (warnings)
     */
    public static function notify_admin_partial_failure($form_id, $post_id, $failed_actions, $successful_actions, $action_details)
    {
        $email_sent = false;
        $webhook_sent = false;

        // Check if partial failure email notifications are enabled
        $partial_notifications_enabled = get_option('brf_admin_partial_notifications_enabled', true);
        if ($partial_notifications_enabled) {
            // Get admin email (custom or default)
            $admin_email = get_option('brf_admin_notification_email', get_option('admin_email'));
            if ($admin_email) {
                $site_name = get_bloginfo('name');
                $site_url = get_site_url();

                $subject = sprintf('[%s] Form Submission Partially Failed - Form ID: %s', $site_name, $form_id);

                $message = self::build_partial_failure_email_content($form_id, $post_id, $failed_actions, $successful_actions, $action_details, $site_name, $site_url);

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

                $email_sent = wp_mail($admin_email, $subject, $message, $headers);
            }
        }

        // Send webhook notification if enabled (independent of email)
        $webhook_sent = self::send_webhook_notification($form_id, $post_id, $failed_actions, $action_details, 'partial_failure');

        return $email_sent || $webhook_sent;
    }

    /**
     * Build email content for partial failures
     */
    private static function build_partial_failure_email_content($form_id, $post_id, $failed_actions, $successful_actions, $action_details, $site_name, $site_url)
    {
        $timestamp = current_time('Y-m-d H:i:s');
        $post_title = $post_id ? get_the_title($post_id) : 'Unknown Page';
        $admin_url = admin_url('admin.php?page=bricksforge#/logs');

        $html = '
        <html>
        <head>
            <meta charset="UTF-8">
            <title>Form Submission Partially Failed</title>
            <style>
                body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background: #f5f5f5; }
                .container { max-width: 500px; margin: 40px auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); border: 1px solid #ddd; }
                .header { background: #666; color: white; padding: 24px; text-align: center; }
                .header h1 { margin: 0; font-size: 20px; font-weight: 600; }
                .header p { margin: 8px 0 0 0; opacity: 0.9; font-size: 14px; }
                .content { padding: 24px; }
                .info-row { display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #eee; }
                .info-row:last-child { border-bottom: none; }
                .info-label { font-weight: 500; color: #666; }
                .info-value { color: #333; }
                .status-summary { display: flex; gap: 16px; margin: 20px 0; }
                .status-box { flex: 1; padding: 16px; border-radius: 6px; text-align: center; border: 1px solid #ddd; }
                .status-success { background: #f8f8f8; }
                .status-error { background: #f0f0f0; }
                .status-number { font-size: 24px; font-weight: bold; margin-bottom: 4px; color: #333; }
                .status-label { font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; color: #666; }
                .cta { text-align: center; margin: 24px 0; }
                .cta-button { display: inline-block; background: #333; color: white; text-decoration: none; padding: 12px 24px; border-radius: 6px; font-weight: 500; }
                .footer { background: #f8f8f8; padding: 16px 24px; text-align: center; font-size: 12px; color: #666; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>Partial Form Failure</h1>
                </div>
                
                <div class="content">
                    <div class="info-row">
                        <span class="info-label">Website</span>
                        <span class="info-value">' . esc_html($site_name) . '</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Form ID</span>
                        <span class="info-value">' . esc_html($form_id) . '</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Page</span>
                        <span class="info-value">' . esc_html($post_title) . '</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Time</span>
                        <span class="info-value">' . esc_html($timestamp) . '</span>
                    </div>

                    <div class="status-summary">
                        <div class="status-box status-success">
                            <div class="status-number">' . count($successful_actions) . '</div>
                            <div class="status-label">Successful</div>
                        </div>
                        <div class="status-box status-error">
                            <div class="status-number">' . count($failed_actions) . '</div>
                            <div class="status-label">Failed</div>
                        </div>
                    </div>

                    <div class="cta">
                        <a href="' . esc_url($admin_url) . '" class="cta-button">View Detailed Logs</a>
                    </div>
                </div>
                
                <div class="footer">
                    <p>Sent automatically by Bricksforge</p>
                </div>
            </div>
        </body>
        </html>';

        return $html;
    }

    /**
     * Send webhook notification for form failures
     *
     * @param int $form_id Form ID
     * @param int|null $post_id Post ID where form was submitted
     * @param array $failed_actions Array of failed actions
     * @param array $action_details Detailed action results
     * @param string $type Type of failure ('failure' or 'partial_failure')
     * @return bool Success status
     */
    private static function send_webhook_notification($form_id, $post_id, $failed_actions, $action_details, $type)
    {
        // Check if webhook notifications are enabled
        $webhook_enabled = get_option('brf_webhook_notifications_enabled', false);
        if (!$webhook_enabled) {
            return false;
        }

        // Get webhook URL
        $webhook_url = get_option('brf_webhook_notification_url', '');
        if (!$webhook_url) {
            return false;
        }

        // Prepare webhook payload
        $site_name = get_bloginfo('name');
        $site_url = get_site_url();
        $timestamp = current_time('c'); // ISO 8601 format
        $post_title = $post_id ? get_the_title($post_id) : 'Unknown Page';
        $post_url = $post_id ? get_permalink($post_id) : $site_url;

        $payload = [
            'event' => 'form_submission_' . $type,
            'timestamp' => $timestamp,
            'site' => [
                'name' => $site_name,
                'url' => $site_url
            ],
            'form' => [
                'id' => $form_id,
                'page_title' => $post_title,
                'page_url' => $post_url,
                'post_id' => $post_id
            ],
            'failure' => [
                'type' => $type,
                'failed_actions' => $failed_actions,
                'failed_count' => count($failed_actions),
                'total_actions' => count($action_details)
            ]
        ];

        // Add successful actions for partial failures
        if ($type === 'partial_failure') {
            $successful_actions = array_filter($action_details, function ($action) {
                return $action['status'] === 'success';
            });
            $payload['failure']['successful_actions'] = array_keys($successful_actions);
            $payload['failure']['successful_count'] = count($successful_actions);
        }

        // Send webhook request
        $response = wp_remote_post($webhook_url, [
            'timeout' => 15,
            'headers' => [
                'Content-Type' => 'application/json',
                'User-Agent' => 'Bricksforge/' . BRICKSFORGE_VERSION . ' (WordPress/' . get_bloginfo('version') . ')'
            ],
            'body' => wp_json_encode($payload)
        ]);

        // Check if request was successful
        $success = !is_wp_error($response) && wp_remote_retrieve_response_code($response) < 400;

        // Log the webhook notification attempt
        if ($success) {
            ProFormsLogger::log('form_submission', 'info', 'Admin webhook notification sent for ' . str_replace('_', ' ', $type), [
                'notification_type' => 'admin_webhook_notification',
                'webhook_url' => $webhook_url,
                'response_code' => wp_remote_retrieve_response_code($response),
                'failed_actions_count' => count($failed_actions)
            ], $form_id, $post_id);
        } else {
            $error_message = is_wp_error($response) ? $response->get_error_message() : 'HTTP ' . wp_remote_retrieve_response_code($response);
            ProFormsLogger::log('form_submission', 'error', 'Failed to send admin webhook notification', [
                'notification_type' => 'admin_webhook_notification',
                'webhook_url' => $webhook_url,
                'error' => $error_message
            ], $form_id, $post_id);
        }

        return $success;
    }
}
