<?php

namespace WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers;

use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\IpHelper;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

/**
 * Feedback Controller
 *
 * Handles feedback submission with comprehensive user and system information
 */
class FeedbackController
{
    /**
     * Submit feedback
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response|WP_Error
     */
    public static function submit_feedback(WP_REST_Request $request)
    {
        $subject = sanitize_text_field(wp_unslash($request->get_param('subject')));
        $message = sanitize_textarea_field(wp_unslash($request->get_param('message')));
        $nonce = $request->get_param('_wpnonce');

        if (!isset($nonce) || !wp_verify_nonce($nonce, 'ultimate_security_nonce')) {
            return new WP_Error('invalid_nonce', __('Invalid nonce', 'ultimate-security'), array('status' => 403));
        }

        if (empty($message)) {
            return new WP_Error('empty_message', __('Message cannot be empty.', 'ultimate-security'), array('status' => 400));
        }

        if (empty($subject)) {
            return new WP_Error('empty_subject', __('Subject cannot be empty.', 'ultimate-security'), array('status' => 400));
        }

        $email = 'support@wpultimatesecurity.com';
        $output = self::build_email_content($subject, $message);

        $headers = array(
            'Content-Type: text/html; charset=UTF-8'
        );
        // Add rate limiting
        $rate_limit_key = 'feedback_' . get_current_user_id();
        if (get_transient($rate_limit_key)) {
            $response = [
                'success' => false,
                'msg' => esc_html__('Rate limit exceeded.', 'ultimate-security'),
            ];
            return new WP_REST_Response($response, 200);
            // wp_send_json_error('Rate limit exceeded', 429);
        }
        set_transient($rate_limit_key, 1, 300);  // 5 minutes

        wp_mail($email, 'Feedback from Contact form of Ultimate Security Plugin', $output, $headers);

        $response = [
            'success' => true,
            'msg' => esc_html__('Email Send successfully.', 'ultimate-security'),
        ];

        return new WP_REST_Response($response, 200);
    }

    /**
     * Build email content with user and system information
     *
     * @param string $subject
     * @param string $message
     * @return string
     */
    private static function build_email_content($subject, $message)
    {
        $user_info = self::get_user_info();
        $site_info = self::get_site_info();
        $tech_info = self::get_tech_info();
        $request_info = self::get_request_info();

        // Build email output with modern styling
        $output = '<div style="font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; color: #333;">';
        $output .= '<div style="background: #7C3AED; color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0;">';
        $output .= '<h1 style="margin: 0; font-size: 28px;">💬 Ultimate Security Feedback</h1>';
        $output .= '<p style="margin: 10px 0 0 0; opacity: 0.9;">New feedback received from your plugin</p>';
        $output .= '</div>';

        $output .= '<div style="background-color: #ffffff; padding: 20px; border: 1px solid #e0e0e0; border-top: none;">';

        // Feedback Details
        $output .= '<div style="background-color: #fff3cd; padding: 15px; margin: 10px 0; border-left: 4px solid #ffc107; border-radius: 4px;">';
        $output .= '<h3 style="margin-top: 0; color: #856404;">📝 Feedback Message</h3>';
        $output .= '<div style="background-color: #ffffff; padding: 15px; border-radius: 4px; margin-top: 10px;">';
        $output .= '<p style="margin: 0 0 10px 0;"><strong style="color: #856404;">Subject:</strong></p>';
        $output .= '<p style="margin: 0 0 15px 0; font-size: 16px;">' . esc_html($subject) . '</p>';
        $output .= '<p style="margin: 0 0 10px 0;"><strong style="color: #856404;">Message:</strong></p>';
        $output .= '<p style="margin: 0; font-size: 14px; line-height: 1.6;">' . nl2br(esc_html($message)) . '</p>';
        $output .= '</div>';
        $output .= '</div>';

        $output .= $user_info;
        $output .= $site_info;
        $output .= $tech_info;
        $output .= $request_info;

        $output .= '</div>';

        // Footer
        $output .= '<div style="background-color: #f8f9fa; padding: 20px; text-align: center; border-radius: 0 0 10px 10px; border: 1px solid #e0e0e0; border-top: none;">';
        $output .= '<p style="margin: 0; color: #6c757d; font-size: 12px;">This email was automatically generated by Ultimate Security Plugin</p>';
        $output .= '<p style="margin: 5px 0 0 0; color: #6c757d; font-size: 12px;">🔒 WP Ultimate Security | <a href="https://wpultimatesecurity.com" style="color: #7C3AED; text-decoration: none;">wpultimatesecurity.com</a></p>';
        $output .= '</div>';
        $output .= '</div>';

        return $output;
    }

    /**
     * Get user information HTML
     *
     * @return string
     */
    private static function get_user_info()
    {
        $current_user = wp_get_current_user();
        $user_info = '';

        if ($current_user->ID) {
            $user_login_count = get_user_meta($current_user->ID, 'ultimate_security_user_logged_count', true);
            $user_last_login = get_user_meta($current_user->ID, 'ultimate_security_user_last_logged_in', true);

            $user_info .= '<div style="background-color: #f8f9fa; padding: 15px; margin: 10px 0; border-left: 4px solid #007bff;">';
            $user_info .= '<h3 style="margin-top: 0; color: #007bff;">👤 User Information</h3>';
            $user_info .= '<table style="width: 100%; border-collapse: collapse;">';
            $user_info .= '<tr><td style="padding: 5px 10px; width: 40%;"><strong>User ID:</strong></td><td style="padding: 5px 10px;">' . $current_user->ID . '</td></tr>';
            $user_info .= '<tr style="background-color: #ffffff;"><td style="padding: 5px 10px;"><strong>Username:</strong></td><td style="padding: 5px 10px;">' . $current_user->user_login . '</td></tr>';
            $user_info .= '<tr><td style="padding: 5px 10px;"><strong>Display Name:</strong></td><td style="padding: 5px 10px;">' . $current_user->display_name . '</td></tr>';
            $user_info .= '<tr style="background-color: #ffffff;"><td style="padding: 5px 10px;"><strong>Email:</strong></td><td style="padding: 5px 10px;"><a href="mailto:' . $current_user->user_email . '">' . $current_user->user_email . '</a></td></tr>';
            $user_info .= '<tr><td style="padding: 5px 10px;"><strong>User Role(s):</strong></td><td style="padding: 5px 10px;">' . implode(', ', array_map('ucfirst', $current_user->roles)) . '</td></tr>';
            $user_info .= '<tr style="background-color: #ffffff;"><td style="padding: 5px 10px;"><strong>Registered Date:</strong></td><td style="padding: 5px 10px;">' . gmdate('F j, Y, g:i a', strtotime($current_user->user_registered)) . '</td></tr>';

            if ($user_last_login) {
                $user_info .= '<tr><td style="padding: 5px 10px;"><strong>Last Login:</strong></td><td style="padding: 5px 10px;">' . $user_last_login . '</td></tr>';
            }
            if ($user_login_count) {
                $user_info .= '<tr style="background-color: #ffffff;"><td style="padding: 5px 10px;"><strong>Total Logins:</strong></td><td style="padding: 5px 10px;">' . $user_login_count . '</td></tr>';
            }

            $user_info .= '</table>';
            $user_info .= '</div>';
        }

        return $user_info;
    }

    /**
     * Get site information HTML
     *
     * @return string
     */
    private static function get_site_info()
    {
        $site_info = '<div style="background-color: #f8f9fa; padding: 15px; margin: 10px 0; border-left: 4px solid #28a745;">';
        $site_info .= '<h3 style="margin-top: 0; color: #28a745;">🌐 Site Information</h3>';
        $site_info .= '<table style="width: 100%; border-collapse: collapse;">';
        $site_info .= '<tr><td style="padding: 5px 10px; width: 40%;"><strong>Site Name:</strong></td><td style="padding: 5px 10px;">' . get_bloginfo('name') . '</td></tr>';
        $site_info .= '<tr style="background-color: #ffffff;"><td style="padding: 5px 10px;"><strong>Site URL:</strong></td><td style="padding: 5px 10px;"><a href="' . get_site_url() . '">' . get_site_url() . '</a></td></tr>';
        $site_info .= '<tr><td style="padding: 5px 10px;"><strong>Admin Email:</strong></td><td style="padding: 5px 10px;"><a href="mailto:' . get_option('admin_email') . '">' . get_option('admin_email') . '</a></td></tr>';
        $site_info .= '<tr style="background-color: #ffffff;"><td style="padding: 5px 10px;"><strong>Timezone:</strong></td><td style="padding: 5px 10px;">' . wp_timezone_string() . '</td></tr>';
        $site_info .= '<tr><td style="padding: 5px 10px;"><strong>Language:</strong></td><td style="padding: 5px 10px;">' . get_bloginfo('language') . '</td></tr>';
        $site_info .= '</table>';
        $site_info .= '</div>';

        return $site_info;
    }

    /**
     * Get technical information HTML
     *
     * @return string
     */
    private static function get_tech_info()
    {
        global $wp_version;
        $theme = wp_get_theme();
        $active_plugins = get_option('active_plugins', array());
        $plugin_count = count($active_plugins);
        $plugin_version = defined('ULTIMATE_SECURITY_VERSION') ? ULTIMATE_SECURITY_VERSION : 'Unknown';
        $memory_limit = ini_get('memory_limit');
        $max_execution_time = ini_get('max_execution_time');

        $tech_info = '<div style="background-color: #f8f9fa; padding: 15px; margin: 10px 0; border-left: 4px solid #6f42c1;">';
        $tech_info .= '<h3 style="margin-top: 0; color: #6f42c1;">⚙️ Technical Details</h3>';
        $tech_info .= '<table style="width: 100%; border-collapse: collapse;">';
        $tech_info .= '<tr><td style="padding: 5px 10px; width: 40%;"><strong>WordPress Version:</strong></td><td style="padding: 5px 10px;">' . $wp_version . '</td></tr>';
        $tech_info .= '<tr style="background-color: #ffffff;"><td style="padding: 5px 10px;"><strong>Plugin Version:</strong></td><td style="padding: 5px 10px;">' . $plugin_version . '</td></tr>';
        $tech_info .= '<tr><td style="padding: 5px 10px;"><strong>Active Theme:</strong></td><td style="padding: 5px 10px;">' . $theme->get('Name') . ' (v' . $theme->get('Version') . ')</td></tr>';
        $tech_info .= '<tr style="background-color: #ffffff;"><td style="padding: 5px 10px;"><strong>Active Plugins:</strong></td><td style="padding: 5px 10px;">' . $plugin_count . ' plugins</td></tr>';
        $tech_info .= '<tr><td style="padding: 5px 10px;"><strong>PHP Version:</strong></td><td style="padding: 5px 10px;">' . phpversion() . '</td></tr>';
        $tech_info .= '<tr style="background-color: #ffffff;"><td style="padding: 5px 10px;"><strong>MySQL Version:</strong></td><td style="padding: 5px 10px;">' . $GLOBALS['wpdb']->db_version() . '</td></tr>';
        $tech_info .= '<tr><td style="padding: 5px 10px;"><strong>Server Software:</strong></td><td style="padding: 5px 10px;">' . (isset($_SERVER['SERVER_SOFTWARE']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE'])) : 'Unknown') . '</td></tr>';
        $tech_info .= '<tr style="background-color: #ffffff;"><td style="padding: 5px 10px;"><strong>Memory Limit:</strong></td><td style="padding: 5px 10px;">' . $memory_limit . '</td></tr>';
        $tech_info .= '<tr><td style="padding: 5px 10px;"><strong>Max Execution Time:</strong></td><td style="padding: 5px 10px;">' . $max_execution_time . ' seconds</td></tr>';
        $tech_info .= '<tr style="background-color: #ffffff;"><td style="padding: 5px 10px;"><strong>Multisite:</strong></td><td style="padding: 5px 10px;">' . (is_multisite() ? 'Yes' : 'No') . '</td></tr>';
        $tech_info .= '</table>';
        $tech_info .= '</div>';

        return $tech_info;
    }

    /**
     * Get request information HTML
     *
     * @return string
     */
    private static function get_request_info()
    {
        $http_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : 'Unknown';
        $http_referer = isset($_SERVER['HTTP_REFERER']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_REFERER'])) : '';

        $request_info = '<div style="background-color: #f8f9fa; padding: 15px; margin: 10px 0; border-left: 4px solid #fd7e14;">';
        $request_info .= '<h3 style="margin-top: 0; color: #fd7e14;">📍 Request Details</h3>';
        $request_info .= '<table style="width: 100%; border-collapse: collapse;">';
        $request_info .= '<tr><td style="padding: 5px 10px; width: 40%;"><strong>User IP:</strong></td><td style="padding: 5px 10px;">' . IpHelper::getClientIp() . '</td></tr>';
        $request_info .= '<tr style="background-color: #ffffff;"><td style="padding: 5px 10px;"><strong>User Agent:</strong></td><td style="padding: 5px 10px; word-break: break-all;">' . esc_html($http_user_agent) . '</td></tr>';
        $request_info .= '<tr><td style="padding: 5px 10px;"><strong>Referrer:</strong></td><td style="padding: 5px 10px;">' . ($http_referer ? esc_url($http_referer) : 'Direct') . '</td></tr>';
        $request_info .= '<tr style="background-color: #ffffff;"><td style="padding: 5px 10px;"><strong>Timestamp:</strong></td><td style="padding: 5px 10px;">' . current_time('F j, Y, g:i:s a') . '</td></tr>';
        $request_info .= '<tr><td style="padding: 5px 10px;"><strong>GMT Time:</strong></td><td style="padding: 5px 10px;">' . gmdate('F j, Y, g:i:s a') . '</td></tr>';
        $request_info .= '</table>';
        $request_info .= '</div>';

        return $request_info;
    }
}
