<?php
/**
 * VMPFence Diagnostic Controller
 *
 * Handles AJAX requests for diagnostic tests
 *
 * @package VMPFence
 * @subpackage Tools/Controllers
 * @since 2.2.0
 * @since 2.2.1 Updated text-domain to vmpfence-security
 * @since 2.2.6 Added Email alert
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Diagnostic Controller
 *
 * @since 2.2.0
 */
class VMPFence_Tools_Diagnostic_Controller {

    /**
     * Register AJAX actions
     *
     * @since 2.2.0
     */
    public function register_ajax_actions() {
        add_action('wp_ajax_vmpfence_run_diagnostics', array($this, 'ajax_run_diagnostics'));
        add_action('wp_ajax_vmpfence_export_diagnostics', array($this, 'ajax_export_diagnostics'));
        add_action('wp_ajax_vmpfence_email_diagnostics', array($this, 'ajax_email_diagnostics'));
    }

    /**
     * Handle run diagnostics AJAX request
     *
     * @since 2.2.0
     */
    public function ajax_run_diagnostics() {
        
        // Verify nonce
        check_ajax_referer('vmpfence_tools_nonce', 'nonce');

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => __('Permission denied', 'vmpfence-security')
            ));
        }

        // Get tests to run (or run all if not specified)
        $tests_to_run = isset($_POST['tests']) ? (array) $_POST['tests'] : array();

        // Run diagnostics
        $results = VMPFence_Tools_Diagnostic::run_diagnostics($tests_to_run);
        
        // Return results
        wp_send_json_success(array(
            'results' => $results,
            'timestamp' => current_time('mysql')
        ));
    }

    /**
     * Handle export diagnostics AJAX request
     *
     * @since 2.2.0
     */
    public function ajax_export_diagnostics() {        
        // Verify nonce
        check_ajax_referer('vmpfence_tools_nonce', 'nonce');

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => __('Permission denied', 'vmpfence-security')
            ));
        }

        // Get results from POST
        $results = isset($_POST['results']) ? json_decode(stripslashes($_POST['results']), true) : array();
        
        if (empty($results)) {
            wp_send_json_error(array(
                'message' => __('No diagnostic results to export', 'vmpfence-security')
            ));
        }

        // Get export format
        $format = isset($_POST['format']) ? sanitize_text_field($_POST['format']) : 'json';

        // Export
        $export_result = VMPFence_Tools_Diagnostic_Report::export($results, $format);

        if ($export_result['success']) {
            wp_send_json_success(array(
                'message' => __('Diagnostic report exported successfully', 'vmpfence-security'),
                'url' => $export_result['url'],
                'filename' => $export_result['file']
            ));
        } else {
            wp_send_json_error(array(
                'message' => $export_result['message']
            ));
        }
    }

    /**
     * Handle email diagnostics AJAX request
     *
     * @since 2.2.0
     */
    public function ajax_email_diagnostics() {        
        // Verify nonce
        check_ajax_referer('vmpfence_tools_nonce', 'nonce');

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => __('Permission denied', 'vmpfence-security')
            ));
        }

        // Get report text from POST (already formatted)
        $report_text = isset($_POST['report_text']) ? wp_unslash($_POST['report_text']) : '';
        
        if (empty($report_text)) {
            wp_send_json_error(array(
                'message' => __('No diagnostic results to email', 'vmpfence-security')
            ));
        }

        // Get email address and ticket number
        $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : get_option('admin_email');
        $ticket_number = isset($_POST['ticket_number']) ? sanitize_text_field($_POST['ticket_number']) : '';

        // Send via centralized Email Service (API → branded template)
        $context = array(
            'report_text'    => $report_text,
            'ticket_number'  => $ticket_number,
            'requesting_ip'  => class_exists('VMPFence_Utils') ? VMPFence_Utils::get_real_ip() : '',
            'wp_version'     => get_bloginfo('version'),
            'php_version'    => PHP_VERSION,
            'plugin_version' => defined('VMPFENCE_VERSION') ? VMPFENCE_VERSION : '',
            'sent_at'        => current_time('Y-m-d H:i:s'),
        );

        $result = VMPFence_Email_Service::send_alert('diagnostic_report', $context, array($email));

        if ($result['success']) {
            wp_send_json_success(array(
                'message' => sprintf(__('Diagnostic report sent to %s', 'vmpfence-security'), $email)
            ));
        } else {
            wp_send_json_error(array(
                'message' => sprintf(__('Failed to send diagnostic report: %s', 'vmpfence-security'), $result['message'])
            ));
        }
    }
}
