<?php
/**
 * Care API Documentation Admin
 *
 * @package Care_API
 */

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

/**
 * Class Care_API_Docs_Admin
 * 
 * Handles the WordPress admin interface for API documentation
 * 
 * SECURITY NOTES:
 * - All JWT token examples use safe placeholder tokens
 * - Password examples use generic placeholders 
 * - No real credentials or secrets are exposed in documentation
 * - Token generation respects current user permissions
 */
class Care_API_Docs_Admin {

    /**
     * Constructor
     */
    public function __construct() {
        add_action( 'admin_menu', array( $this, 'add_admin_menus' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
        add_action( 'wp_ajax_care_api_test_endpoint', array( $this, 'test_endpoint_ajax' ) );
        add_action( 'wp_ajax_care_api_generate_token', array( $this, 'generate_test_token_ajax' ) );
    }

    /**
     * Add admin menus
     */
    public function add_admin_menus() {
        // Main menu page
        add_menu_page(
            __( 'Care API', 'care-api' ),
            __( 'Care API', 'care-api' ),
            'manage_kivicare_api',
            'care-api-docs',
            array( $this, 'render_main_docs_page' ),
            'dashicons-rest-api',
            30
        );

        // Documentation submenu
        add_submenu_page(
            'care-api-docs',
            __( 'API Documentation', 'care-api' ),
            __( 'Documentation', 'care-api' ),
            'manage_kivicare_api',
            'care-api-docs',
            array( $this, 'render_main_docs_page' )
        );

        // API Tester submenu
        add_submenu_page(
            'care-api-docs',
            __( 'API Tester', 'care-api' ),
            __( 'API Tester', 'care-api' ),
            'manage_kivicare_api',
            'care-api-tester',
            array( $this, 'render_api_tester_page' )
        );

        // Settings submenu
        add_submenu_page(
            'care-api-docs',
            __( 'API Settings', 'care-api' ),
            __( 'Settings', 'care-api' ),
            'manage_options',
            'care-api-settings',
            array( $this, 'render_settings_page' )
        );
    }

    /**
     * Enqueue admin scripts and styles
     *
     * @param string $hook_suffix The current admin page.
     */
    public function enqueue_admin_scripts( $hook_suffix ) {
        // Only load on Care API pages
        if ( strpos( $hook_suffix, 'care-api' ) === false ) {
            return;
        }

        // Enqueue styles
        wp_enqueue_style(
            'care-api-docs-admin',
            CARE_API_URL . 'assets/css/admin-docs.css',
            array(),
            CARE_API_VERSION
        );

        // Enqueue scripts
        wp_enqueue_script(
            'care-api-docs-admin',
            CARE_API_URL . 'assets/js/admin-docs.js',
            array( 'jquery', 'wp-util' ),
            CARE_API_VERSION,
            true
        );

        // Localize script
        wp_localize_script(
            'care-api-docs-admin',
            'care_api_docs',
            array(
                'nonce'        => wp_create_nonce( 'care_api_docs_nonce' ),
                'ajax_url'     => admin_url( 'admin-ajax.php' ),
                'rest_url'     => rest_url( 'care/v1/' ),
                'current_user' => wp_get_current_user(),
                'strings'      => array(
                    'testing'      => __( 'Testing endpoint...', 'care-api' ),
                    'success'      => __( 'Success!', 'care-api' ),
                    'error'        => __( 'Error occurred', 'care-api' ),
                    'copy_success' => __( 'Copied to clipboard!', 'care-api' ),
                )
            )
        );

        // Enqueue code editor for JSON display
        wp_enqueue_code_editor( array( 'type' => 'application/json' ) );
    }

    /**
     * Render main documentation page
     */
    public function render_main_docs_page() {
        $endpoints = $this->get_api_endpoints();
        include CARE_API_PATH . 'templates/docs/main-docs.php';
    }

    /**
     * Render API tester page
     */
    public function render_api_tester_page() {
        $endpoints = $this->get_api_endpoints();
        include CARE_API_PATH . 'templates/docs/api-tester.php';
    }

    /**
     * Render settings page
     */
    public function render_settings_page() {
        if ( isset( $_POST['submit'] ) ) {
            $this->save_settings();
        }

        $settings = $this->get_settings();
        include CARE_API_PATH . 'templates/docs/settings.php';
    }

    /**
     * Get API endpoints with documentation
     *
     * @return array
     */
    private function get_api_endpoints() {
        return array(
            'authentication' => array(
                'title'       => __( 'Authentication', 'care-api' ),
                'description' => __( 'Endpoints for user authentication and token management', 'care-api' ),
                'endpoints'   => array(
                    array(
                        'method'      => 'POST',
                        'endpoint'    => '/auth/login',
                        'title'       => __( 'User Login', 'care-api' ),
                        'description' => __( 'Authenticate user and get JWT token', 'care-api' ),
                        'security_note' => __( 'SECURITY WARNING: Never expose real JWT tokens in documentation or logs. Always use placeholder tokens for examples.', 'care-api' ),
                        'parameters'  => array(
                            'username' => array( 'type' => 'string', 'required' => true, 'description' => 'WordPress username' ),
                            'password' => array( 'type' => 'string', 'required' => true, 'description' => 'WordPress password' ),
                        ),
                        'example_request'  => array(
                            'username' => 'your_username',
                            'password' => 'your-secure-password'
                        ),
                        'example_response' => array(
                            'success' => true,
                            'token'   => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.example_payload.example_signature',
                            'user'    => array(
                                'id'          => 123,
                                'username'    => 'your_username',
                                'email'       => 'user@example.com',
                                'role'        => 'doctor',
                                'clinic_id'   => 1,
                            )
                        )
                    ),
                    array(
                        'method'      => 'POST',
                        'endpoint'    => '/auth/refresh',
                        'title'       => __( 'Refresh Token', 'care-api' ),
                        'description' => __( 'Refresh JWT token', 'care-api' ),
                        'parameters'  => array(),
                        'auth_required' => true,
                        'example_response' => array(
                            'success' => true,
                            'token'   => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.example_payload.example_signature'
                        )
                    ),
                    array(
                        'method'      => 'POST',
                        'endpoint'    => '/auth/logout',
                        'title'       => __( 'User Logout', 'care-api' ),
                        'description' => __( 'Invalidate JWT token', 'care-api' ),
                        'parameters'  => array(),
                        'auth_required' => true,
                        'example_response' => array(
                            'success' => true,
                            'message' => 'Logged out successfully'
                        )
                    )
                )
            ),
            'clinics' => array(
                'title'       => __( 'Clinics', 'care-api' ),
                'description' => __( 'Manage clinic information', 'care-api' ),
                'endpoints'   => array(
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/clinics',
                        'title'       => __( 'Get Clinics', 'care-api' ),
                        'description' => __( 'Retrieve list of clinics', 'care-api' ),
                        'parameters'  => array(
                            'page'     => array( 'type' => 'integer', 'default' => 1, 'description' => 'Page number' ),
                            'per_page' => array( 'type' => 'integer', 'default' => 10, 'description' => 'Items per page' ),
                            'search'   => array( 'type' => 'string', 'description' => 'Search term' ),
                            'status'   => array( 'type' => 'integer', 'description' => 'Filter by status (1=active, 0=inactive)' ),
                        ),
                        'auth_required' => true,
                        'example_response' => array(
                            'success' => true,
                            'data'    => array(
                                array(
                                    'id'               => 1,
                                    'name'             => 'Central Clinic',
                                    'email'            => 'info@central-clinic.com',
                                    'telephone_no'     => '+351 213 456 789',
                                    'address'          => 'Rua da Saúde, 123',
                                    'city'             => 'Lisboa',
                                    'state'            => 'Lisboa',
                                    'country'          => 'Portugal',
                                    'postal_code'      => '1000-001',
                                    'status'           => 1,
                                    'specialties'      => array( 'General Practice', 'Cardiology' ),
                                    'doctors_count'    => 5,
                                    'patients_count'   => 150,
                                )
                            ),
                            'pagination' => array(
                                'total'        => 1,
                                'total_pages'  => 1,
                                'current_page' => 1,
                                'per_page'     => 10,
                            )
                        )
                    ),
                    array(
                        'method'      => 'POST',
                        'endpoint'    => '/clinics',
                        'title'       => __( 'Create Clinic', 'care-api' ),
                        'description' => __( 'Create a new clinic', 'care-api' ),
                        'parameters'  => array(
                            'name'         => array( 'type' => 'string', 'required' => true, 'description' => 'Clinic name' ),
                            'email'        => array( 'type' => 'string', 'required' => true, 'description' => 'Clinic email' ),
                            'telephone_no' => array( 'type' => 'string', 'required' => true, 'description' => 'Phone number' ),
                            'address'      => array( 'type' => 'string', 'description' => 'Street address' ),
                            'city'         => array( 'type' => 'string', 'description' => 'City' ),
                            'state'        => array( 'type' => 'string', 'description' => 'State/Province' ),
                            'country'      => array( 'type' => 'string', 'description' => 'Country' ),
                            'postal_code'  => array( 'type' => 'string', 'description' => 'Postal code' ),
                            'specialties'  => array( 'type' => 'array', 'description' => 'Array of specialties' ),
                        ),
                        'auth_required' => true,
                        'required_role' => 'administrator',
                        'example_request' => array(
                            'name'         => 'New Medical Center',
                            'email'        => 'info@newmedical.com',
                            'telephone_no' => '+351 213 999 888',
                            'address'      => 'Avenida da República, 456',
                            'city'         => 'Porto',
                            'state'        => 'Porto',
                            'country'      => 'Portugal',
                            'postal_code'  => '4000-001',
                            'specialties'  => array( 'Pediatrics', 'Dermatology' )
                        )
                    ),
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/clinics/{id}',
                        'title'       => __( 'Get Clinic', 'care-api' ),
                        'description' => __( 'Get specific clinic details', 'care-api' ),
                        'parameters'  => array(
                            'id' => array( 'type' => 'integer', 'required' => true, 'description' => 'Clinic ID' ),
                        ),
                        'auth_required' => true,
                    ),
                    array(
                        'method'      => 'PUT',
                        'endpoint'    => '/clinics/{id}',
                        'title'       => __( 'Update Clinic', 'care-api' ),
                        'description' => __( 'Update clinic information', 'care-api' ),
                        'parameters'  => array(
                            'id' => array( 'type' => 'integer', 'required' => true, 'description' => 'Clinic ID' ),
                        ),
                        'auth_required' => true,
                        'required_role' => 'administrator',
                    ),
                    array(
                        'method'      => 'DELETE',
                        'endpoint'    => '/clinics/{id}',
                        'title'       => __( 'Delete Clinic', 'care-api' ),
                        'description' => __( 'Delete a clinic', 'care-api' ),
                        'parameters'  => array(
                            'id' => array( 'type' => 'integer', 'required' => true, 'description' => 'Clinic ID' ),
                        ),
                        'auth_required' => true,
                        'required_role' => 'administrator',
                    )
                )
            ),
            'patients' => array(
                'title'       => __( 'Patients', 'care-api' ),
                'description' => __( 'Patient management endpoints', 'care-api' ),
                'endpoints'   => array(
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/patients',
                        'title'       => __( 'Get Patients', 'care-api' ),
                        'description' => __( 'Retrieve list of patients', 'care-api' ),
                        'parameters'  => array(
                            'clinic_id' => array( 'type' => 'integer', 'description' => 'Filter by clinic ID' ),
                            'search'    => array( 'type' => 'string', 'description' => 'Search by name or email' ),
                            'page'      => array( 'type' => 'integer', 'default' => 1 ),
                            'per_page'  => array( 'type' => 'integer', 'default' => 10 ),
                        ),
                        'auth_required' => true,
                    ),
                    array(
                        'method'      => 'POST',
                        'endpoint'    => '/patients',
                        'title'       => __( 'Create Patient', 'care-api' ),
                        'description' => __( 'Register a new patient', 'care-api' ),
                        'parameters'  => array(
                            'first_name' => array( 'type' => 'string', 'required' => true ),
                            'last_name'  => array( 'type' => 'string', 'required' => true ),
                            'email'      => array( 'type' => 'string', 'required' => true ),
                            'phone'      => array( 'type' => 'string', 'required' => true ),
                            'birth_date' => array( 'type' => 'string', 'format' => 'Y-m-d' ),
                            'gender'     => array( 'type' => 'string', 'enum' => array( 'M', 'F', 'Other' ) ),
                            'address'    => array( 'type' => 'object' ),
                            'clinic_id'  => array( 'type' => 'integer', 'required' => true ),
                        ),
                        'auth_required' => true,
                    ),
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/patients/{id}',
                        'title'       => __( 'Get Patient', 'care-api' ),
                        'description' => __( 'Get specific patient details', 'care-api' ),
                        'auth_required' => true,
                    ),
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/patients/{id}/history',
                        'title'       => __( 'Get Patient Medical History', 'care-api' ),
                        'description' => __( 'Retrieve patient medical history', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'doctor',
                    ),
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/patients/{id}/encounters',
                        'title'       => __( 'Get Patient Encounters', 'care-api' ),
                        'description' => __( 'Get all medical encounters for a patient', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'doctor',
                    ),
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/patients/{id}/prescriptions',
                        'title'       => __( 'Get Patient Prescriptions', 'care-api' ),
                        'description' => __( 'Get all prescriptions for a patient', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'doctor',
                    )
                )
            ),
            'doctors' => array(
                'title'       => __( 'Doctors', 'care-api' ),
                'description' => __( 'Doctor management and scheduling', 'care-api' ),
                'endpoints'   => array(
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/doctors',
                        'title'       => __( 'Get Doctors', 'care-api' ),
                        'description' => __( 'Retrieve list of doctors', 'care-api' ),
                        'auth_required' => true,
                    ),
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/doctors/{id}/schedule',
                        'title'       => __( 'Get Doctor Schedule', 'care-api' ),
                        'description' => __( 'Get doctor\'s schedule and availability', 'care-api' ),
                        'auth_required' => true,
                    ),
                    array(
                        'method'      => 'PUT',
                        'endpoint'    => '/doctors/{id}/schedule',
                        'title'       => __( 'Update Doctor Schedule', 'care-api' ),
                        'description' => __( 'Update doctor\'s availability schedule', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'doctor',
                    )
                )
            ),
            'appointments' => array(
                'title'       => __( 'Appointments', 'care-api' ),
                'description' => __( 'Appointment booking and management', 'care-api' ),
                'endpoints'   => array(
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/appointments',
                        'title'       => __( 'Get Appointments', 'care-api' ),
                        'description' => __( 'Retrieve appointments list', 'care-api' ),
                        'parameters'  => array(
                            'patient_id' => array( 'type' => 'integer', 'description' => 'Filter by patient' ),
                            'doctor_id'  => array( 'type' => 'integer', 'description' => 'Filter by doctor' ),
                            'clinic_id'  => array( 'type' => 'integer', 'description' => 'Filter by clinic' ),
                            'status'     => array( 'type' => 'string', 'description' => 'Filter by status' ),
                            'date_from'  => array( 'type' => 'string', 'format' => 'Y-m-d', 'description' => 'Start date' ),
                            'date_to'    => array( 'type' => 'string', 'format' => 'Y-m-d', 'description' => 'End date' ),
                        ),
                        'auth_required' => true,
                    ),
                    array(
                        'method'      => 'POST',
                        'endpoint'    => '/appointments',
                        'title'       => __( 'Create Appointment', 'care-api' ),
                        'description' => __( 'Book a new appointment', 'care-api' ),
                        'parameters'  => array(
                            'patient_id'               => array( 'type' => 'integer', 'required' => true ),
                            'doctor_id'                => array( 'type' => 'integer', 'required' => true ),
                            'clinic_id'                => array( 'type' => 'integer', 'required' => true ),
                            'appointment_start_date'   => array( 'type' => 'string', 'required' => true, 'format' => 'Y-m-d' ),
                            'appointment_start_time'   => array( 'type' => 'string', 'required' => true, 'format' => 'H:i:s' ),
                            'appointment_end_date'     => array( 'type' => 'string', 'required' => true, 'format' => 'Y-m-d' ),
                            'appointment_end_time'     => array( 'type' => 'string', 'required' => true, 'format' => 'H:i:s' ),
                            'visit_type'               => array( 'type' => 'string', 'description' => 'Type of visit' ),
                            'description'              => array( 'type' => 'string', 'description' => 'Appointment notes' ),
                            'services'                 => array( 'type' => 'array', 'description' => 'Array of service IDs' ),
                        ),
                        'auth_required' => true,
                        'example_request' => array(
                            'patient_id'               => 123,
                            'doctor_id'                => 456,
                            'clinic_id'                => 1,
                            'appointment_start_date'   => '2024-12-20',
                            'appointment_start_time'   => '14:30:00',
                            'appointment_end_date'     => '2024-12-20',
                            'appointment_end_time'     => '15:00:00',
                            'visit_type'               => 'consultation',
                            'description'              => 'Regular checkup',
                            'services'                 => array( 1, 2 )
                        )
                    ),
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/appointments/available-slots',
                        'title'       => __( 'Get Available Slots', 'care-api' ),
                        'description' => __( 'Get available appointment slots for a doctor', 'care-api' ),
                        'parameters'  => array(
                            'doctor_id' => array( 'type' => 'integer', 'required' => true ),
                            'date'      => array( 'type' => 'string', 'required' => true, 'format' => 'Y-m-d' ),
                            'duration'  => array( 'type' => 'integer', 'default' => 30, 'description' => 'Appointment duration in minutes' ),
                        ),
                        'auth_required' => true,
                    ),
                    array(
                        'method'      => 'PUT',
                        'endpoint'    => '/appointments/{id}',
                        'title'       => __( 'Update Appointment', 'care-api' ),
                        'description' => __( 'Update appointment details', 'care-api' ),
                        'auth_required' => true,
                    ),
                    array(
                        'method'      => 'DELETE',
                        'endpoint'    => '/appointments/{id}',
                        'title'       => __( 'Cancel Appointment', 'care-api' ),
                        'description' => __( 'Cancel an appointment', 'care-api' ),
                        'auth_required' => true,
                    )
                )
            ),
            'encounters' => array(
                'title'       => __( 'Medical Encounters', 'care-api' ),
                'description' => __( 'Medical consultation records', 'care-api' ),
                'endpoints'   => array(
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/encounters',
                        'title'       => __( 'Get Encounters', 'care-api' ),
                        'description' => __( 'Retrieve medical encounters', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'doctor',
                    ),
                    array(
                        'method'      => 'POST',
                        'endpoint'    => '/encounters',
                        'title'       => __( 'Create Encounter', 'care-api' ),
                        'description' => __( 'Record a new medical encounter', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'doctor',
                    ),
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/encounters/{id}/prescriptions',
                        'title'       => __( 'Get Encounter Prescriptions', 'care-api' ),
                        'description' => __( 'Get prescriptions for a specific encounter', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'doctor',
                    ),
                    array(
                        'method'      => 'POST',
                        'endpoint'    => '/encounters/{id}/prescriptions',
                        'title'       => __( 'Add Prescription', 'care-api' ),
                        'description' => __( 'Add prescription to an encounter', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'doctor',
                    )
                )
            ),
            'bills' => array(
                'title'       => __( 'Billing', 'care-api' ),
                'description' => __( 'Invoice and payment management', 'care-api' ),
                'endpoints'   => array(
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/bills',
                        'title'       => __( 'Get Bills', 'care-api' ),
                        'description' => __( 'Retrieve billing records', 'care-api' ),
                        'auth_required' => true,
                    ),
                    array(
                        'method'      => 'POST',
                        'endpoint'    => '/bills',
                        'title'       => __( 'Create Bill', 'care-api' ),
                        'description' => __( 'Create a new bill/invoice', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'administrator',
                    ),
                    array(
                        'method'      => 'POST',
                        'endpoint'    => '/bills/{id}/payment',
                        'title'       => __( 'Process Payment', 'care-api' ),
                        'description' => __( 'Process payment for a bill', 'care-api' ),
                        'auth_required' => true,
                    )
                )
            ),
            'services' => array(
                'title'       => __( 'Services', 'care-api' ),
                'description' => __( 'Medical services management', 'care-api' ),
                'endpoints'   => array(
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/services',
                        'title'       => __( 'Get Services', 'care-api' ),
                        'description' => __( 'Get available medical services', 'care-api' ),
                        'auth_required' => true,
                    ),
                    array(
                        'method'      => 'POST',
                        'endpoint'    => '/services',
                        'title'       => __( 'Create Service', 'care-api' ),
                        'description' => __( 'Create a new medical service', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'administrator',
                    )
                )
            ),
            'reports' => array(
                'title'       => __( 'Reports', 'care-api' ),
                'description' => __( 'Analytics and reporting endpoints', 'care-api' ),
                'endpoints'   => array(
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/reports/appointments',
                        'title'       => __( 'Appointments Report', 'care-api' ),
                        'description' => __( 'Get appointment statistics and reports', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'administrator',
                    ),
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/reports/revenue',
                        'title'       => __( 'Revenue Report', 'care-api' ),
                        'description' => __( 'Get financial reports and revenue analytics', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'administrator',
                    ),
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/reports/patients',
                        'title'       => __( 'Patient Report', 'care-api' ),
                        'description' => __( 'Get patient statistics and demographics', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'administrator',
                    ),
                    array(
                        'method'      => 'GET',
                        'endpoint'    => '/reports/doctors',
                        'title'       => __( 'Doctor Performance Report', 'care-api' ),
                        'description' => __( 'Get doctor performance and workload statistics', 'care-api' ),
                        'auth_required' => true,
                        'required_role' => 'administrator',
                    )
                )
            )
        );
    }

    /**
     * AJAX handler for testing endpoints
     */
    public function test_endpoint_ajax() {
        // Verify nonce
        if ( ! wp_verify_nonce( $_POST['nonce'], 'care_api_docs_nonce' ) ) {
            wp_die( 'Security check failed' );
        }

        $method = sanitize_text_field( $_POST['method'] );
        $endpoint = sanitize_text_field( $_POST['endpoint'] );
        $token = sanitize_text_field( $_POST['token'] );
        $body = wp_unslash( $_POST['body'] );

        // Prepare request
        $url = rest_url( 'care/v1' . $endpoint );
        $args = array(
            'method'  => $method,
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'timeout' => 30,
        );

        // Add authorization header if token provided
        if ( ! empty( $token ) ) {
            $args['headers']['Authorization'] = 'Bearer ' . $token;
        }

        // Add body for POST/PUT requests
        if ( in_array( $method, array( 'POST', 'PUT' ) ) && ! empty( $body ) ) {
            $args['body'] = $body;
        }

        // Make request
        $response = wp_remote_request( $url, $args );

        if ( is_wp_error( $response ) ) {
            wp_send_json_error( array(
                'message' => $response->get_error_message()
            ) );
        }

        $status_code = wp_remote_retrieve_response_code( $response );
        $response_body = wp_remote_retrieve_body( $response );
        $headers = wp_remote_retrieve_headers( $response );

        wp_send_json_success( array(
            'status_code' => $status_code,
            'headers'     => $headers->getAll(),
            'body'        => $response_body,
            'formatted_body' => json_decode( $response_body, true ),
        ) );
    }

    /**
     * AJAX handler for generating test tokens
     */
    public function generate_test_token_ajax() {
        // Verify nonce
        if ( ! wp_verify_nonce( $_POST['nonce'], 'care_api_docs_nonce' ) ) {
            wp_die( 'Security check failed' );
        }

        $current_user = wp_get_current_user();
        
        if ( ! $current_user->exists() ) {
            wp_send_json_error( array(
                'message' => 'No user logged in'
            ) );
        }

        // Generate JWT token for current user
        $jwt_service = new Care_API_JWT_Service();
        $token = $jwt_service->generate_token( $current_user->ID );

        if ( is_wp_error( $token ) ) {
            wp_send_json_error( array(
                'message' => $token->get_error_message()
            ) );
        }

        wp_send_json_success( array(
            'token' => $token,
            'user'  => array(
                'id'       => $current_user->ID,
                'username' => $current_user->user_login,
                'email'    => $current_user->user_email,
                'role'     => $current_user->roles[0] ?? 'subscriber',
            )
        ) );
    }

    /**
     * Get documentation settings
     *
     * @return array
     */
    private function get_settings() {
        return array(
            'enable_docs'        => get_option( 'care_api_enable_docs', true ),
            'enable_tester'      => get_option( 'care_api_enable_tester', true ),
            'docs_access_role'   => get_option( 'care_api_docs_access_role', 'manage_kivicare_api' ),
            'tester_access_role' => get_option( 'care_api_tester_access_role', 'manage_kivicare_api' ),
            'show_examples'      => get_option( 'care_api_show_examples', true ),
            'auto_generate_docs' => get_option( 'care_api_auto_generate_docs', false ),
        );
    }

    /**
     * Save settings
     */
    private function save_settings() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( 'You do not have permission to access this page.' );
        }

        // Verify nonce
        if ( ! wp_verify_nonce( $_POST['_wpnonce'], 'care_api_settings_nonce' ) ) {
            wp_die( 'Security check failed' );
        }

        update_option( 'care_api_enable_docs', isset( $_POST['enable_docs'] ) );
        update_option( 'care_api_enable_tester', isset( $_POST['enable_tester'] ) );
        update_option( 'care_api_docs_access_role', sanitize_text_field( $_POST['docs_access_role'] ) );
        update_option( 'care_api_tester_access_role', sanitize_text_field( $_POST['tester_access_role'] ) );
        update_option( 'care_api_show_examples', isset( $_POST['show_examples'] ) );
        update_option( 'care_api_auto_generate_docs', isset( $_POST['auto_generate_docs'] ) );

        add_action( 'admin_notices', function() {
            echo '<div class="notice notice-success is-dismissible"><p>' . __( 'Settings saved successfully!', 'care-api' ) . '</p></div>';
        } );
    }
}

// Initialize if we're in admin
if ( is_admin() ) {
    new Care_API_Docs_Admin();
}