<?php
/**
 * Support Controller Class
 *
 * @package VMPFence
 * @since 1.0.0
 * @since 2.2.5 - Added enhanced observer-based audit logging
 * @since 2.2.6 - Email alert
 */

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

/**
 * VMPFence Support Controller Class
 *
 * @since 1.0.0
 */
class VMPFence_Support_Controller {

    /**
     * Submit support ticket
     *
     * @since 1.0.0
     * @param array $ticket_data Ticket data
     * @return array
     */
    public static function submit_ticket($ticket_data) {
        $required_fields = array('name', 'email', 'subject', 'message', 'priority');
        
        // Validate required fields
        foreach ($required_fields as $field) {
            if (empty($ticket_data[$field])) {
                return array(
                    'success' => false,
                    /* translators: %s: field name */
                    'message' => sprintf(__('Field %s is required', 'vmpfence-security'), $field)
                );
            }
        }

        // Validate email
        if (!is_email($ticket_data['email'])) {
            return array(
                'success' => false,
                'message' => __('Invalid email address', 'vmpfence-security')
            );
        }

        // Generate ticket ID
        $ticket_id = 'VMS-' . gmdate('Ymd') . '-' . strtoupper(wp_generate_password(6, false));

        // Prepare ticket data
        $ticket = array(
            'ticket_id' => $ticket_id,
            'name' => sanitize_text_field($ticket_data['name']),
            'email' => sanitize_email($ticket_data['email']),
            'subject' => sanitize_text_field($ticket_data['subject']),
            'message' => sanitize_textarea_field($ticket_data['message']),
            'priority' => sanitize_text_field($ticket_data['priority']),
            'category' => sanitize_text_field($ticket_data['category'] ?? 'general'),
            'site_url' => get_site_url(),
            'wp_version' => get_bloginfo('version'),
            'vmpfence_version' => VMPFence_Constants::PLUGIN_VERSION,
            'php_version' => PHP_VERSION,
            'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '',
            'license_key' => VMPFence_Config::get('license_key', ''),
            'license_type' => VMPFence_License::get_license_type(),
            'created_at' => current_time('timestamp'),
            'status' => 'open',
            'attachments' => array()
        );

        // Handle file attachments
        if (!empty($ticket_data['attachments'])) {
            $attachment_result = self::handle_attachments($ticket_data['attachments']);
            if ($attachment_result['success']) {
                $ticket['attachments'] = $attachment_result['files'];
            }
        }

        // Include system information if requested
        if (!empty($ticket_data['include_system_info'])) {
            $ticket['system_info'] = self::collect_system_information();
        }

        // Include diagnostic information if requested
        if (!empty($ticket_data['include_diagnostics'])) {
            $ticket['diagnostics'] = VMPFence_Diagnostic::run_diagnostics();
        }

        // Store ticket locally
        $stored = self::store_ticket_locally($ticket);
        
        if (!$stored) {
            return array(
                'success' => false,
                'message' => __('Failed to store ticket locally', 'vmpfence-security')
            );
        }

        // Submit to support API
        $api_result = self::submit_to_support_api($ticket);
        
        if ($api_result['success']) {
            // Update local ticket with API response
            self::update_local_ticket($ticket_id, array(
                'api_ticket_id' => $api_result['api_ticket_id'],
                'status' => 'submitted'
            ));

            // Send confirmation email
            self::send_confirmation_email($ticket);

            // Fire hook for observer-based audit logging
            do_action('vmpfence_support_ticket_submitted', $ticket_id, $ticket['subject'], $ticket['priority']);

            return array(
                'success' => true,
                'message' => __('Support ticket submitted successfully', 'vmpfence-security'),
                'ticket_id' => $ticket_id
            );
        } else {
            // Update status to failed
            self::update_local_ticket($ticket_id, array('status' => 'failed'));
            
            return array(
                'success' => false,
                /* translators: %s: error message */
                'message' => sprintf(__('Failed to submit ticket: %s', 'vmpfence-security'), $api_result['message']),
                'ticket_id' => $ticket_id
            );
        }
    }

    /**
     * Get support tickets
     *
     * @since 1.0.0
     * @param array $args Query arguments
     * @return array
     */
    public static function get_tickets($args = array()) {
        global $wpdb;

        $defaults = array(
            'limit' => 20,
            'offset' => 0,
            'status' => '',
            'priority' => '',
            'order_by' => 'created_at',
            'order' => 'DESC'
        );

        $args = wp_parse_args($args, $defaults);
        
        $table_name = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_SUPPORT_TICKETS);

        // Build WHERE clause
        $where_conditions = array('1=1');
        $where_values = array();

        if (!empty($args['status'])) {
            $where_conditions[] = 'status = %s';
            $where_values[] = $args['status'];
        }

        if (!empty($args['priority'])) {
            $where_conditions[] = 'priority = %s';
            $where_values[] = $args['priority'];
        }

        $where_clause = implode(' AND ', $where_conditions);

        // Validate order by
        $allowed_order_by = array('created_at', 'status', 'priority', 'subject');
        if (!in_array($args['order_by'], $allowed_order_by)) {
            $args['order_by'] = 'created_at';
        }

        // Validate order
        $args['order'] = strtoupper($args['order']) === 'ASC' ? 'ASC' : 'DESC';

        // Build query
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- Table name from VMPFence_Constants, order_by validated against whitelist, where_clause built from prepared statements
        $query = "SELECT * FROM $table_name WHERE $where_clause ORDER BY {$args['order_by']} {$args['order']} LIMIT %d OFFSET %d";
        $where_values[] = $args['limit'];
        $where_values[] = $args['offset'];

        if (!empty($where_values)) {
            $query = $wpdb->prepare($query, $where_values);
        }

        $tickets = $wpdb->get_results($query, ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared

        // Process results
        foreach ($tickets as &$ticket) {
            $ticket['created_at_formatted'] = date_i18n(
                get_option('date_format') . ' ' . get_option('time_format'),
                $ticket['created_at']
            );
            $ticket['attachments'] = maybe_unserialize($ticket['attachments']);
            $ticket['system_info'] = maybe_unserialize($ticket['system_info']);
        }

        return $tickets;
    }

    /**
     * Get support ticket by ID
     *
     * @since 1.0.0
     * @param string $ticket_id Ticket ID
     * @return array|null
     */
    public static function get_ticket($ticket_id) {
        global $wpdb;

        $table_name = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_SUPPORT_TICKETS);
        
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name properly escaped via VMPFence_Constants
        $ticket = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table_name WHERE ticket_id = %s",
            $ticket_id
        ), ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        if ($ticket) {
            $ticket['created_at_formatted'] = date_i18n(
                get_option('date_format') . ' ' . get_option('time_format'),
                $ticket['created_at']
            );
            $ticket['attachments'] = maybe_unserialize($ticket['attachments']);
            $ticket['system_info'] = maybe_unserialize($ticket['system_info']);
            $ticket['diagnostics'] = maybe_unserialize($ticket['diagnostics']);
        }

        return $ticket;
    }

    /**
     * Update ticket status
     *
     * @since 1.0.0
     * @param string $ticket_id Ticket ID
     * @param string $status New status
     * @return bool
     */
    public static function update_ticket_status($ticket_id, $status) {
        return self::update_local_ticket($ticket_id, array('status' => $status));
    }

    /**
     * Generate system information report
     *
     * @since 1.0.0
     * @return array
     */
    public static function collect_system_information() {
        global $wpdb;

        $system_info = array(
            'wordpress' => array(
                'version' => get_bloginfo('version'),
                'multisite' => is_multisite(),
                'language' => get_locale(),
                'timezone' => get_option('timezone_string'),
                'date_format' => get_option('date_format'),
                'time_format' => get_option('time_format'),
                'home_url' => home_url(),
                'site_url' => site_url(),
                'admin_email' => get_option('admin_email')
            ),
            'server' => array(
                'php_version' => PHP_VERSION,
                'mysql_version' => $wpdb->get_var('SELECT VERSION()'),
                'server_software' => isset($_SERVER['SERVER_SOFTWARE']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE'])) : 'Unknown',
                'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : 'Unknown',
                'max_execution_time' => ini_get('max_execution_time'),
                'memory_limit' => ini_get('memory_limit'),
                'post_max_size' => ini_get('post_max_size'),
                'upload_max_filesize' => ini_get('upload_max_filesize'),
                'max_input_vars' => ini_get('max_input_vars')
            ),
            'vmpfence' => array(
                'version' => VMPFence_Constants::PLUGIN_VERSION,
                'license_type' => VMPFence_License::get_license_type(),
                'license_status' => VMPFence_License::validate_license() ? 'valid' : 'invalid',
                'waf_enabled' => VMPFence_Config::get('waf_enabled', false),
                'scan_schedule' => VMPFence_Config::get('scan_schedule', 'never'),
                'login_protection' => VMPFence_Config::get('login_protection_enabled', false),
                'audit_logging' => VMPFence_Config::get('enable_audit_log', false)
            ),
            'theme' => array(
                'name' => wp_get_theme()->get('Name'),
                'version' => wp_get_theme()->get('Version'),
                'author' => wp_get_theme()->get('Author')
            ),
            'plugins' => array(),
            'constants' => array(
                'WP_DEBUG' => defined('WP_DEBUG') ? WP_DEBUG : false,
                'WP_DEBUG_LOG' => defined('WP_DEBUG_LOG') ? WP_DEBUG_LOG : false,
                'WP_DEBUG_DISPLAY' => defined('WP_DEBUG_DISPLAY') ? WP_DEBUG_DISPLAY : false,
                'SCRIPT_DEBUG' => defined('SCRIPT_DEBUG') ? SCRIPT_DEBUG : false,
                'WP_CACHE' => defined('WP_CACHE') ? WP_CACHE : false,
                'DISALLOW_FILE_EDIT' => defined('DISALLOW_FILE_EDIT') ? DISALLOW_FILE_EDIT : false,
                'AUTOMATIC_UPDATER_DISABLED' => defined('AUTOMATIC_UPDATER_DISABLED') ? AUTOMATIC_UPDATER_DISABLED : false
            )
        );

        // Get active plugins
        $active_plugins = get_option('active_plugins');
        foreach ($active_plugins as $plugin) {
            $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin);
            $system_info['plugins'][] = array(
                'name' => $plugin_data['Name'],
                'version' => $plugin_data['Version'],
                'author' => $plugin_data['Author'],
                'file' => $plugin
            );
        }

        return $system_info;
    }

    /**
     * Export system information
     *
     * @since 1.0.0
     * @param string $format Export format (json, txt)
     * @return string
     */
    public static function export_system_info($format = 'txt') {
        $system_info = self::collect_system_information();

        if ($format === 'json') {
            return wp_json_encode($system_info, JSON_PRETTY_PRINT);
        }

        // Text format
        $output = array();
        $output[] = "=== VMP Fence System Information ===";
        $output[] = "Generated: " . current_time('mysql');
        $output[] = "";

        foreach ($system_info as $section => $data) {
            $output[] = "=== " . strtoupper($section) . " ===";
            
            if (is_array($data)) {
                foreach ($data as $key => $value) {
                    if (is_array($value)) {
                        $output[] = "$key:";
                        foreach ($value as $subkey => $subvalue) {
                            $output[] = "  $subkey: " . (is_bool($subvalue) ? ($subvalue ? 'Yes' : 'No') : $subvalue);
                        }
                    } else {
                        $output[] = "$key: " . (is_bool($value) ? ($value ? 'Yes' : 'No') : $value);
                    }
                }
            }
            $output[] = "";
        }

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

    /**
     * Get knowledge base articles
     *
     * @since 1.0.0
     * @param array $args Search arguments
     * @return array
     */
    public static function get_knowledge_base($args = array()) {
        $defaults = array(
            'search' => '',
            'category' => '',
            'limit' => 10
        );

        $args = wp_parse_args($args, $defaults);

        // This would typically fetch from an API or local cache
        // For now, return some sample articles
        $articles = array(
            array(
                'id' => 1,
                'title' => __('Getting Started with VMPFence', 'vmpfence-security'),
                'excerpt' => __('Learn how to configure VMPFence for optimal security protection.', 'vmpfence-security'),
                'category' => 'setup',
                'url' => 'https://docs.vmpfence.com/getting-started',
                'helpful_count' => 245
            ),
            array(
                'id' => 2,
                'title' => __('Configuring the Web Application Firewall', 'vmpfence-security'),
                'excerpt' => __('Step-by-step guide to setting up WAF protection.', 'vmpfence-security'),
                'category' => 'waf',
                'url' => 'https://docs.vmpfence.com/waf-configuration',
                'helpful_count' => 189
            ),
            array(
                'id' => 3,
                'title' => __('Understanding Security Scan Results', 'vmpfence-security'),
                'excerpt' => __('How to interpret and act on security scan findings.', 'vmpfence-security'),
                'category' => 'scanning',
                'url' => 'https://docs.vmpfence.com/scan-results',
                'helpful_count' => 156
            ),
            array(
                'id' => 4,
                'title' => __('Login Protection Best Practices', 'vmpfence-security'),
                'excerpt' => __('Secure your WordPress login with VMPFence protection.', 'vmpfence-security'),
                'category' => 'login',
                'url' => 'https://docs.vmpfence.com/login-protection',
                'helpful_count' => 134
            ),
            array(
                'id' => 5,
                'title' => __('Troubleshooting Common Issues', 'vmpfence-security'),
                'excerpt' => __('Solutions to frequently encountered problems.', 'vmpfence-security'),
                'category' => 'troubleshooting',
                'url' => 'https://docs.vmpfence.com/troubleshooting',
                'helpful_count' => 98
            )
        );

        // Filter by search term
        if (!empty($args['search'])) {
            $search_term = strtolower($args['search']);
            $articles = array_filter($articles, function($article) use ($search_term) {
                return strpos(strtolower($article['title']), $search_term) !== false ||
                       strpos(strtolower($article['excerpt']), $search_term) !== false;
            });
        }

        // Filter by category
        if (!empty($args['category'])) {
            $articles = array_filter($articles, function($article) use ($args) {
                return $article['category'] === $args['category'];
            });
        }

        // Limit results
        $articles = array_slice($articles, 0, $args['limit']);

        return $articles;
    }

    /**
     * Send feedback
     *
     * @since 1.0.0
     * @param array $feedback_data Feedback data
     * @return array
     */
    public static function send_feedback($feedback_data) {
        $required_fields = array('type', 'message');
        
        // Validate required fields
        foreach ($required_fields as $field) {
            if (empty($feedback_data[$field])) {
                return array(
                    'success' => false,
                    /* translators: %s: field name */
                    'message' => sprintf(__('Field %s is required', 'vmpfence-security'), $field)
                );
            }
        }

        $feedback = array(
            'type' => sanitize_text_field($feedback_data['type']),
            'message' => sanitize_textarea_field($feedback_data['message']),
            'rating' => isset($feedback_data['rating']) ? (int)$feedback_data['rating'] : 0,
            'email' => sanitize_email($feedback_data['email'] ?? ''),
            'site_url' => get_site_url(),
            'vmpfence_version' => VMPFence_Constants::PLUGIN_VERSION,
            'wp_version' => get_bloginfo('version'),
            'created_at' => current_time('timestamp')
        );

        // Store feedback locally
        global $wpdb;
        $feedback_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_FEEDBACK);
        
        $stored = $wpdb->insert(
            $feedback_table,
            $feedback,
            array('%s', '%s', '%d', '%s', '%s', '%s', '%s', '%d')
        );

        if (!$stored) {
            return array(
                'success' => false,
                'message' => __('Failed to store feedback', 'vmpfence-security')
            );
        }

        // Send to feedback API
        $api_result = self::submit_feedback_to_api($feedback);

        // Fire hook for observer-based audit logging
        do_action('vmpfence_feedback_submitted', $feedback['type'], $feedback['rating']);

        return array(
            'success' => true,
            'message' => __('Thank you for your feedback!', 'vmpfence-security')
        );
    }

    /**
     * Get support statistics
     *
     * @since 1.0.0
     * @return array
     */
    public static function get_support_stats() {
        global $wpdb;

        $tickets_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_SUPPORT_TICKETS);
        
        $stats = array(
            'total_tickets' => 0,
            'open_tickets' => 0,
            'closed_tickets' => 0,
            'avg_response_time' => 0,
            'satisfaction_rating' => 0
        );

        // Get ticket counts
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name properly escaped via VMPFence_Constants
        $ticket_stats = $wpdb->get_row("
            SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status IN ('open', 'pending') THEN 1 ELSE 0 END) as open_count,
                SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed_count
            FROM $tickets_table
        ", ARRAY_A);
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        if ($ticket_stats) {
            $stats['total_tickets'] = (int)$ticket_stats['total'];
            $stats['open_tickets'] = (int)$ticket_stats['open_count'];
            $stats['closed_tickets'] = (int)$ticket_stats['closed_count'];
        }

        // Get feedback statistics
        $feedback_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_FEEDBACK);
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name properly escaped via VMPFence_Constants
        $avg_rating = $wpdb->get_var("SELECT AVG(rating) FROM $feedback_table WHERE rating > 0");
        $stats['satisfaction_rating'] = $avg_rating ? round($avg_rating, 1) : 0;

        return $stats;
    }

    /**
     * Private helper methods
     */

    private static function handle_attachments($attachments) {
        $uploaded_files = array();
        $upload_dir = wp_upload_dir();
        $vmpfence_dir = $upload_dir['basedir'] . '/vmpfence/support/';

        if (!file_exists($vmpfence_dir)) {
            wp_mkdir_p($vmpfence_dir);
        }

        foreach ($attachments as $attachment) {
            // Validate file type and size
            $allowed_types = array('txt', 'log', 'jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx');
            $file_ext = strtolower(pathinfo($attachment['name'], PATHINFO_EXTENSION));
            
            if (!in_array($file_ext, $allowed_types)) {
                continue;
            }

            if ($attachment['size'] > 10485760) { // 10MB limit
                continue;
            }

            // Generate unique filename
            $filename = time() . '_' . wp_generate_password(8, false) . '.' . $file_ext;
            $filepath = $vmpfence_dir . $filename;

            // Move uploaded file
            // phpcs:ignore Generic.PHP.ForbiddenFunctions.Found -- move_uploaded_file is the correct function for handling file uploads, properly validated above
            if (move_uploaded_file($attachment['tmp_name'], $filepath)) {
                $uploaded_files[] = array(
                    'original_name' => $attachment['name'],
                    'filename' => $filename,
                    'filepath' => $filepath,
                    'size' => $attachment['size'],
                    'type' => $attachment['type']
                );
            }
        }

        return array(
            'success' => !empty($uploaded_files),
            'files' => $uploaded_files
        );
    }

    private static function store_ticket_locally($ticket) {
        global $wpdb;

        $table_name = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_SUPPORT_TICKETS);
        
        return $wpdb->insert(
            $table_name,
            array(
                'ticket_id' => $ticket['ticket_id'],
                'name' => $ticket['name'],
                'email' => $ticket['email'],
                'subject' => $ticket['subject'],
                'message' => $ticket['message'],
                'priority' => $ticket['priority'],
                'category' => $ticket['category'],
                'status' => $ticket['status'],
                'site_url' => $ticket['site_url'],
                'wp_version' => $ticket['wp_version'],
                'vmpfence_version' => $ticket['vmpfence_version'],
                'php_version' => $ticket['php_version'],
                'license_key' => $ticket['license_key'],
                'license_type' => $ticket['license_type'],
                'attachments' => maybe_serialize($ticket['attachments']),
                'system_info' => maybe_serialize($ticket['system_info'] ?? null),
                'diagnostics' => maybe_serialize($ticket['diagnostics'] ?? null),
                'created_at' => $ticket['created_at']
            ),
            array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d')
        );
    }

    private static function update_local_ticket($ticket_id, $data) {
        global $wpdb;

        $table_name = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_SUPPORT_TICKETS);
        
        return $wpdb->update(
            $table_name,
            $data,
            array('ticket_id' => $ticket_id),
            null,
            array('%s')
        );
    }

    private static function submit_to_support_api($ticket) {
        $api_url = VMPFence_Constants::API_BASE_URL . '/support/tickets';
        $api_key = VMPFence_Config::get('api_key');

        if (empty($api_key)) {
            return array(
                'success' => false,
                'message' => __('API key not configured', 'vmpfence-security')
            );
        }

        $response = wp_remote_post($api_url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json'
            ),
            'body' => wp_json_encode($ticket),
            'timeout' => 30
        ));

        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => $response->get_error_message()
            );
        }

        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);

        if ($response_code === 201) {
            $data = json_decode($response_body, true);
            return array(
                'success' => true,
                'api_ticket_id' => $data['ticket_id'] ?? '',
                'message' => __('Ticket submitted successfully', 'vmpfence-security')
            );
        } else {
            return array(
                'success' => false,
                /* translators: %d: HTTP response code */
                'message' => sprintf(__('API Error: %d', 'vmpfence-security'), $response_code)
            );
        }
    }

    private static function submit_feedback_to_api($feedback) {
        $api_url = VMPFence_Constants::API_BASE_URL . '/feedback';
        $api_key = VMPFence_Config::get('api_key');

        if (empty($api_key)) {
            return false;
        }

        $response = wp_remote_post($api_url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json'
            ),
            'body' => wp_json_encode($feedback),
            'timeout' => 15
        ));

        return !is_wp_error($response) && wp_remote_retrieve_response_code($response) === 201;
    }

    private static function send_confirmation_email($ticket) {
        // Send via centralized Email Service (API → branded template)
        $context = array(
            'customer_name'  => $ticket['name'],
            'ticket_id'      => $ticket['ticket_id'],
            'ticket_subject' => $ticket['subject'],
            'priority'       => ucfirst($ticket['priority']),
        );

        $result = VMPFence_Email_Service::send_alert('support_ticket_confirmation', $context, array($ticket['email']));

        return $result['success'];
    }
}
