<?php
/**
 * Aysa Support Handlers
 * Handles AJAX requests for report issue and contact support features
 */

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

class Aysa_Support_Handlers {
    
    public function __construct() {
        add_action('wp_ajax_aysa_report_issue', array($this, 'handle_report_issue'));
        add_action('wp_ajax_aysa_contact_support', array($this, 'handle_contact_support'));
    }
    
    /**
     * Handle report issue AJAX request
     */
    public function handle_report_issue() {
        check_ajax_referer('aysa_report_issue_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        $issue_type = sanitize_text_field($_POST['issue_type'] ?? '');
        $priority = sanitize_text_field($_POST['priority'] ?? '');
        $title = sanitize_text_field($_POST['title'] ?? '');
        $description = sanitize_textarea_field($_POST['description'] ?? '');
        $site_url = sanitize_url($_POST['site_url'] ?? '');
        $plugin_version = sanitize_text_field($_POST['plugin_version'] ?? '');
        $user_id = intval($_POST['user_id'] ?? 0);
        $user_email = sanitize_email($_POST['user_email'] ?? '');
        $timestamp = sanitize_text_field($_POST['timestamp'] ?? '');
        
        if (empty($issue_type) || empty($priority) || empty($title) || empty($description)) {
            wp_send_json_error('Missing required fields');
            return;
        }
        
        $issue_data = array(
            'issueType' => $issue_type,
            'priority' => $priority,
            'title' => $title,
            'description' => $description,
            'siteUrl' => $site_url,
            'pluginVersion' => $plugin_version,
            'userId' => $user_id,
            'userEmail' => $user_email,
            'timestamp' => $timestamp,
            'source' => 'wordpress_plugin'
        );
        
        $response = $this->call_dotnet_endpoint('api/Support/ReportIssue', $issue_data);
        
        if ($response && !is_wp_error($response)) {
            $body = wp_remote_retrieve_body($response);
            $status_code = wp_remote_retrieve_response_code($response);
            
            if ($status_code === 200) {
                wp_send_json_success(array(
                    'message' => 'Issue reported successfully',
                    'response' => json_decode($body, true)
                ));
            } else {
                wp_send_json_error('Failed to report issue: HTTP ' . $status_code);
            }
        } else {
            wp_send_json_error('Failed to connect to support system');
        }
    }
    
    /**
     * Handle contact support AJAX request
     */
    public function handle_contact_support() {
        check_ajax_referer('aysa_contact_support_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        $category = sanitize_text_field($_POST['category'] ?? '');
        $urgency = sanitize_text_field($_POST['urgency'] ?? '');
        $subject = sanitize_text_field($_POST['subject'] ?? '');
        $message = sanitize_textarea_field($_POST['message'] ?? '');
        $site_url = sanitize_url($_POST['site_url'] ?? '');
        $plugin_version = sanitize_text_field($_POST['plugin_version'] ?? '');
        $user_id = intval($_POST['user_id'] ?? 0);
        $user_email = sanitize_email($_POST['user_email'] ?? '');
        $timestamp = sanitize_text_field($_POST['timestamp'] ?? '');
        
        if (empty($category) || empty($urgency) || empty($subject) || empty($message)) {
            wp_send_json_error('Missing required fields');
            return;
        }
        
        $support_data = array(
            'category' => $category,
            'urgency' => $urgency,
            'subject' => $subject,
            'message' => $message,
            'siteUrl' => $site_url,
            'pluginVersion' => $plugin_version,
            'userId' => $user_id,
            'userEmail' => $user_email,
            'timestamp' => $timestamp,
            'source' => 'wordpress_plugin'
        );
        
        $response = $this->call_dotnet_endpoint('api/Support/ContactSupport', $support_data);
        
        if ($response && !is_wp_error($response)) {
            $body = wp_remote_retrieve_body($response);
            $status_code = wp_remote_retrieve_response_code($response);
            
            if ($status_code === 200) {
                wp_send_json_success(array(
                    'message' => 'Support request sent successfully',
                    'response' => json_decode($body, true)
                ));
            } else {
                wp_send_json_error('Failed to send support request: HTTP ' . $status_code);
            }
        } else {
            wp_send_json_error('Failed to connect to support system');
        }
    }
    
    /**
     * Call .NET Core endpoint
     */
    private function call_dotnet_endpoint($endpoint, $data) {
        // Use the centralized API configuration
        $url = Aysa_API_Config::get_endpoint_url(str_replace('api/', '', $endpoint));
        
        if (!$url) {
            // Fallback to old method if endpoint not found in config
            $api_base_url = defined('AYSA_API_BASE_URL') ? AYSA_API_BASE_URL : 'https://api.aysa.ai/';
            $url = rtrim($api_base_url, '/') . '/' . ltrim($endpoint, '/');
        }
        
        $args = array(
            'method' => 'POST',
            'headers' => array(
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ),
            'body' => json_encode($data),
            'timeout' => 30
        );
        
        aysa_debug_log('[AYSA Support] Calling endpoint: ' . $url);
        aysa_debug_log('[AYSA Support] Request data: ' . json_encode($data));
        
        $response = wp_remote_post($url, $args);
        
        if (is_wp_error($response)) {
            aysa_debug_log('[AYSA Support] Request failed: ' . $response->get_error_message());
        } else {
            aysa_debug_log('[AYSA Support] Response code: ' . wp_remote_retrieve_response_code($response));
            aysa_debug_log('[AYSA Support] Response body: ' . wp_remote_retrieve_body($response));
        }
        
        return $response;
    }
}

new Aysa_Support_Handlers();
