<?php
/**
 * Settings Page Template
 *
 * @package KiviCare_API
 */

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

<div class="wrap">
    <div class="care-api-docs">
        
        <!-- Header -->
        <div class="care-api-header">
            <div class="api-version">v<?php echo esc_html( CARE_API_VERSION ); ?></div>
            <h1><?php esc_html_e( 'Care API Settings', 'care-api' ); ?></h1>
            <p><?php esc_html_e( 'Configure API documentation and testing features', 'care-api' ); ?></p>
        </div>

        <div class="api-docs-content">
            
            <form method="post" class="settings-form">
                <?php wp_nonce_field( 'kivicare_api_settings_nonce' ); ?>
                
                <!-- Documentation Settings -->
                <div class="settings-section">
                    <h3><?php esc_html_e( 'Documentation Settings', 'care-api' ); ?></h3>
                    
                    <div class="checkbox-field">
                        <input type="checkbox" id="enable_docs" name="enable_docs" <?php checked( $settings['enable_docs'], true ); ?>>
                        <label for="enable_docs"><?php esc_html_e( 'Enable API Documentation', 'care-api' ); ?></label>
                    </div>
                    <p class="description"><?php esc_html_e( 'Show the API documentation page in the WordPress admin.', 'care-api' ); ?></p>

                    <div class="checkbox-field">
                        <input type="checkbox" id="show_examples" name="show_examples" <?php checked( $settings['show_examples'], true ); ?>>
                        <label for="show_examples"><?php esc_html_e( 'Show Code Examples', 'care-api' ); ?></label>
                    </div>
                    <p class="description"><?php esc_html_e( 'Display code examples in multiple programming languages.', 'care-api' ); ?></p>

                    <div class="form-group">
                        <label for="docs_access_role"><?php esc_html_e( 'Documentation Access Role', 'care-api' ); ?></label>
                        <select id="docs_access_role" name="docs_access_role">
                            <option value="manage_kivicare_api" <?php selected( $settings['docs_access_role'], 'manage_kivicare_api' ); ?>>
                                <?php esc_html_e( 'Care API Users', 'care-api' ); ?>
                            </option>
                            <option value="manage_options" <?php selected( $settings['docs_access_role'], 'manage_options' ); ?>>
                                <?php esc_html_e( 'Administrators Only', 'care-api' ); ?>
                            </option>
                            <option value="edit_posts" <?php selected( $settings['docs_access_role'], 'edit_posts' ); ?>>
                                <?php esc_html_e( 'Editors and Above', 'care-api' ); ?>
                            </option>
                            <option value="read" <?php selected( $settings['docs_access_role'], 'read' ); ?>>
                                <?php esc_html_e( 'All Users', 'care-api' ); ?>
                            </option>
                        </select>
                        <p class="description"><?php esc_html_e( 'Minimum capability required to view API documentation.', 'care-api' ); ?></p>
                    </div>
                </div>

                <!-- API Tester Settings -->
                <div class="settings-section">
                    <h3><?php esc_html_e( 'API Tester Settings', 'care-api' ); ?></h3>
                    
                    <div class="checkbox-field">
                        <input type="checkbox" id="enable_tester" name="enable_tester" <?php checked( $settings['enable_tester'], true ); ?>>
                        <label for="enable_tester"><?php esc_html_e( 'Enable API Tester', 'care-api' ); ?></label>
                    </div>
                    <p class="description"><?php esc_html_e( 'Show the interactive API testing tool in the WordPress admin.', 'care-api' ); ?></p>

                    <div class="form-group">
                        <label for="tester_access_role"><?php esc_html_e( 'API Tester Access Role', 'care-api' ); ?></label>
                        <select id="tester_access_role" name="tester_access_role">
                            <option value="manage_kivicare_api" <?php selected( $settings['tester_access_role'], 'manage_kivicare_api' ); ?>>
                                <?php esc_html_e( 'Care API Users', 'care-api' ); ?>
                            </option>
                            <option value="manage_options" <?php selected( $settings['tester_access_role'], 'manage_options' ); ?>>
                                <?php esc_html_e( 'Administrators Only', 'care-api' ); ?>
                            </option>
                            <option value="kivicare_api_full_access" <?php selected( $settings['tester_access_role'], 'kivicare_api_full_access' ); ?>>
                                <?php esc_html_e( 'Full API Access Only', 'care-api' ); ?>
                            </option>
                        </select>
                        <p class="description"><?php esc_html_e( 'Minimum capability required to use the API tester. Be careful as this allows testing live data.', 'care-api' ); ?></p>
                    </div>

                    <div class="notice notice-warning">
                        <p><strong><?php esc_html_e( 'Security Warning:', 'care-api' ); ?></strong> <?php esc_html_e( 'The API tester can modify live data. Only give access to trusted users.', 'care-api' ); ?></p>
                    </div>
                </div>

                <!-- Advanced Settings -->
                <div class="settings-section">
                    <h3><?php esc_html_e( 'Advanced Settings', 'care-api' ); ?></h3>
                    
                    <div class="checkbox-field">
                        <input type="checkbox" id="auto_generate_docs" name="auto_generate_docs" <?php checked( $settings['auto_generate_docs'], true ); ?>>
                        <label for="auto_generate_docs"><?php esc_html_e( 'Auto-Generate Documentation', 'care-api' ); ?></label>
                    </div>
                    <p class="description"><?php esc_html_e( 'Automatically generate documentation from endpoint registration. (Experimental feature)', 'care-api' ); ?></p>

                    <div class="notice notice-info">
                        <h4><?php esc_html_e( 'API Information', 'care-api' ); ?></h4>
                        <p><strong><?php esc_html_e( 'Base URL:', 'care-api' ); ?></strong> <code><?php echo esc_url( rest_url( 'care/v1/' ) ); ?></code></p>
                        <p><strong><?php esc_html_e( 'Version:', 'care-api' ); ?></strong> <?php echo esc_html( CARE_API_VERSION ); ?></p>
                        <p><strong><?php esc_html_e( 'WordPress Version:', 'care-api' ); ?></strong> <?php echo esc_html( get_bloginfo( 'version' ) ); ?></p>
                        <p><strong><?php esc_html_e( 'PHP Version:', 'care-api' ); ?></strong> <?php echo esc_html( phpversion() ); ?></p>
                    </div>
                </div>

                <!-- System Status -->
                <div class="settings-section">
                    <h3><?php esc_html_e( 'System Status', 'care-api' ); ?></h3>
                    
                    <?php
                    // Check if KiviCare plugin is active
                    $kivicare_active = is_plugin_active( 'kivicare-clinic-&-patient-management-system/kivicare-clinic-&-patient-management-system.php' );
                    
                    // Check database tables
                    global $wpdb;
                    $tables_exist = array(
                        'clinics' => $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}kc_clinics'" ),
                        'appointments' => $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}kc_appointments'" ),
                        'patients' => $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}kc_patient_encounters'" ),
                    );
                    
                    // Check REST API
                    $rest_url = rest_url( 'care/v1/' );
                    $rest_response = wp_remote_get( $rest_url );
                    $rest_working = ! is_wp_error( $rest_response );
                    ?>
                    
                    <table class="params-table">
                        <thead>
                            <tr>
                                <th><?php esc_html_e( 'Component', 'care-api' ); ?></th>
                                <th><?php esc_html_e( 'Status', 'care-api' ); ?></th>
                                <th><?php esc_html_e( 'Details', 'care-api' ); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><?php esc_html_e( 'KiviCare Plugin', 'care-api' ); ?></td>
                                <td>
                                    <?php if ( $kivicare_active ) : ?>
                                        <span style="color: #28a745; font-weight: bold;">✓ <?php esc_html_e( 'Active', 'care-api' ); ?></span>
                                    <?php else : ?>
                                        <span style="color: #dc3545; font-weight: bold;">✗ <?php esc_html_e( 'Inactive', 'care-api' ); ?></span>
                                    <?php endif; ?>
                                </td>
                                <td><?php esc_html_e( 'Base KiviCare plugin required for API functionality', 'care-api' ); ?></td>
                            </tr>
                            <tr>
                                <td><?php esc_html_e( 'Database Tables', 'care-api' ); ?></td>
                                <td>
                                    <?php if ( $tables_exist['clinics'] && $tables_exist['appointments'] && $tables_exist['patients'] ) : ?>
                                        <span style="color: #28a745; font-weight: bold;">✓ <?php esc_html_e( 'Found', 'care-api' ); ?></span>
                                    <?php else : ?>
                                        <span style="color: #dc3545; font-weight: bold;">✗ <?php esc_html_e( 'Missing', 'care-api' ); ?></span>
                                    <?php endif; ?>
                                </td>
                                <td><?php esc_html_e( 'KiviCare database tables needed for API data', 'care-api' ); ?></td>
                            </tr>
                            <tr>
                                <td><?php esc_html_e( 'REST API', 'care-api' ); ?></td>
                                <td>
                                    <?php if ( $rest_working ) : ?>
                                        <span style="color: #28a745; font-weight: bold;">✓ <?php esc_html_e( 'Working', 'care-api' ); ?></span>
                                    <?php else : ?>
                                        <span style="color: #dc3545; font-weight: bold;">✗ <?php esc_html_e( 'Error', 'care-api' ); ?></span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <code><?php echo esc_url( $rest_url ); ?></code>
                                    <?php if ( ! $rest_working ) : ?>
                                        <br><small style="color: #dc3545;"><?php esc_html_e( 'Check permalink settings and server configuration', 'care-api' ); ?></small>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Current User Permissions -->
                <div class="settings-section">
                    <h3><?php esc_html_e( 'Current User Permissions', 'care-api' ); ?></h3>
                    
                    <?php
                    $current_user = wp_get_current_user();
                    $user_capabilities = array(
                        'manage_kivicare_api' => __( 'Manage Care API', 'care-api' ),
                        'kivicare_api_full_access' => __( 'Full API Access', 'care-api' ),
                        'kivicare_api_medical_access' => __( 'Medical Data Access', 'care-api' ),
                        'kivicare_api_patient_access' => __( 'Patient Access', 'care-api' ),
                        'kivicare_api_reception_access' => __( 'Reception Access', 'care-api' ),
                    );
                    ?>
                    
                    <div class="notice notice-info">
                        <p><strong><?php esc_html_e( 'User:', 'care-api' ); ?></strong> <?php echo esc_html( $current_user->display_name ); ?> (<?php echo esc_html( $current_user->user_login ); ?>)</p>
                        <p><strong><?php esc_html_e( 'Role:', 'care-api' ); ?></strong> <?php echo esc_html( implode( ', ', $current_user->roles ) ); ?></p>
                        
                        <p><strong><?php esc_html_e( 'API Capabilities:', 'care-api' ); ?></strong></p>
                        <ul style="margin-left: 20px;">
                            <?php foreach ( $user_capabilities as $cap => $label ) : ?>
                                <li>
                                    <?php if ( current_user_can( $cap ) ) : ?>
                                        <span style="color: #28a745;">✓</span>
                                    <?php else : ?>
                                        <span style="color: #dc3545;">✗</span>
                                    <?php endif; ?>
                                    <?php echo esc_html( $label ); ?>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>

                <!-- API Documentation Export -->
                <div class="settings-section">
                    <h3><?php esc_html_e( 'Export Documentation', 'care-api' ); ?></h3>
                    
                    <p><?php esc_html_e( 'Export API documentation in different formats for external use:', 'care-api' ); ?></p>
                    
                    <div style="margin: 20px 0;">
                        <button type="button" class="button" onclick="exportDocs('json')">
                            <?php esc_html_e( 'Export as JSON', 'care-api' ); ?>
                        </button>
                        <button type="button" class="button" onclick="exportDocs('markdown')" style="margin-left: 10px;">
                            <?php esc_html_e( 'Export as Markdown', 'care-api' ); ?>
                        </button>
                        <button type="button" class="button" onclick="exportDocs('postman')" style="margin-left: 10px;">
                            <?php esc_html_e( 'Export for Postman', 'care-api' ); ?>
                        </button>
                    </div>
                </div>

                <!-- Save Button -->
                <div class="settings-section">
                    <button type="submit" name="submit" class="button button-primary button-large">
                        <?php esc_html_e( 'Save Settings', 'care-api' ); ?>
                    </button>
                </div>

            </form>

        </div>
    </div>
</div>

<script>
function exportDocs(format) {
    var baseUrl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
    var nonce = '<?php echo wp_create_nonce( 'kivicare_api_export_docs' ); ?>';
    
    var url = baseUrl + '?action=kivicare_api_export_docs&format=' + format + '&nonce=' + nonce;
    
    // Open in new window for download
    window.open(url, '_blank');
}

jQuery(document).ready(function($) {
    // Add some interactivity to the settings page
    $('#enable_docs').on('change', function() {
        if (!$(this).is(':checked')) {
            $('#docs_access_role').prop('disabled', true);
        } else {
            $('#docs_access_role').prop('disabled', false);
        }
    }).trigger('change');

    $('#enable_tester').on('change', function() {
        if (!$(this).is(':checked')) {
            $('#tester_access_role').prop('disabled', true);
        } else {
            $('#tester_access_role').prop('disabled', false);
        }
    }).trigger('change');
});
</script>