<?php
/**
 * Main Documentation 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 Documentation', 'care-api' ); ?></h1>
            <p><?php esc_html_e( 'Complete REST API documentation for KiviCare healthcare management system', 'care-api' ); ?></p>
        </div>

        <!-- Navigation Tabs -->
        <nav class="nav-tab-wrapper">
            <a href="#overview" class="nav-tab nav-tab-active" data-tab="overview">
                <?php esc_html_e( 'Overview', 'care-api' ); ?>
            </a>
            <a href="#endpoints" class="nav-tab" data-tab="endpoints">
                <?php esc_html_e( 'API Endpoints', 'care-api' ); ?>
            </a>
            <a href="#authentication" class="nav-tab" data-tab="authentication">
                <?php esc_html_e( 'Authentication', 'care-api' ); ?>
            </a>
            <a href="#examples" class="nav-tab" data-tab="examples">
                <?php esc_html_e( 'Code Examples', 'care-api' ); ?>
            </a>
        </nav>

        <div class="api-docs-content">
            
            <!-- Overview Tab -->
            <div id="overview" class="tab-content">
                <div class="endpoint-section">
                    <h2><?php esc_html_e( 'Overview', 'care-api' ); ?></h2>
                    <p><?php esc_html_e( 'The Care API is a comprehensive REST API for managing healthcare clinics, patients, appointments, medical encounters, and billing. Built on WordPress REST API infrastructure with JWT authentication.', 'care-api' ); ?></p>
                    
                    <div class="notice notice-info">
                        <p><strong><?php esc_html_e( 'Base URL:', 'care-api' ); ?></strong> <code><?php echo esc_url( rest_url( 'care/v1/' ) ); ?></code></p>
                    </div>

                    <h3><?php esc_html_e( 'Key Features', 'care-api' ); ?></h3>
                    <ul>
                        <li><?php esc_html_e( 'JWT Authentication with role-based access control', 'care-api' ); ?></li>
                        <li><?php esc_html_e( 'Complete CRUD operations for all healthcare entities', 'care-api' ); ?></li>
                        <li><?php esc_html_e( 'Comprehensive patient medical history management', 'care-api' ); ?></li>
                        <li><?php esc_html_e( 'Advanced appointment scheduling with availability checking', 'care-api' ); ?></li>
                        <li><?php esc_html_e( 'Medical encounter recording with prescriptions', 'care-api' ); ?></li>
                        <li><?php esc_html_e( 'Billing and payment processing', 'care-api' ); ?></li>
                        <li><?php esc_html_e( 'Analytics and reporting capabilities', 'care-api' ); ?></li>
                    </ul>

                    <h3><?php esc_html_e( 'Response Format', 'care-api' ); ?></h3>
                    <p><?php esc_html_e( 'All API responses follow a consistent JSON format:', 'care-api' ); ?></p>
                    
                    <div class="code-example">
                        <div class="code-example-header">
                            <span class="code-language">JSON</span>
                            <button class="copy-button" title="<?php esc_attr_e( 'Copy to clipboard', 'care-api' ); ?>">
                                <i class="dashicons dashicons-clipboard"></i>
                            </button>
                        </div>
                        <div class="code-content">{
  "success": true,
  "data": {
    // Response data here
  },
  "message": "Success message",
  "pagination": {
    "total": 100,
    "total_pages": 10,
    "current_page": 1,
    "per_page": 10
  }
}</div>
                    </div>

                    <h3><?php esc_html_e( 'Error Handling', 'care-api' ); ?></h3>
                    <p><?php esc_html_e( 'Error responses include detailed information:', 'care-api' ); ?></p>
                    
                    <div class="code-example">
                        <div class="code-example-header">
                            <span class="code-language">JSON</span>
                            <button class="copy-button" title="<?php esc_attr_e( 'Copy to clipboard', 'care-api' ); ?>">
                                <i class="dashicons dashicons-clipboard"></i>
                            </button>
                        </div>
                        <div class="code-content">{
  "success": false,
  "error": {
    "code": "invalid_request",
    "message": "Required parameter missing: patient_id",
    "details": {
      "field": "patient_id",
      "expected": "integer"
    }
  }
}</div>
                    </div>

                    <h3><?php esc_html_e( 'Rate Limiting', 'care-api' ); ?></h3>
                    <p><?php esc_html_e( 'API requests are rate limited to prevent abuse:', 'care-api' ); ?></p>
                    <ul>
                        <li><?php esc_html_e( 'Authenticated users: 1000 requests per hour', 'care-api' ); ?></li>
                        <li><?php esc_html_e( 'Unauthenticated users: 100 requests per hour', 'care-api' ); ?></li>
                    </ul>
                </div>
            </div>

            <!-- Endpoints Tab -->
            <div id="endpoints" class="tab-content" style="display: none;">
                <?php if ( ! empty( $endpoints ) ) : ?>
                    <?php foreach ( $endpoints as $group_key => $group ) : ?>
                        <div class="endpoint-group" id="group-<?php echo esc_attr( $group_key ); ?>">
                            <div class="endpoint-group-header">
                                <div class="endpoint-group-title">
                                    <?php echo esc_html( $group['title'] ); ?>
                                    <div>
                                        <span class="endpoint-count"><?php echo count( $group['endpoints'] ); ?></span>
                                        <span class="toggle-icon">▼</span>
                                    </div>
                                </div>
                                <div class="endpoint-group-description">
                                    <?php echo esc_html( $group['description'] ); ?>
                                </div>
                            </div>
                            
                            <ul class="endpoint-list">
                                <?php foreach ( $group['endpoints'] as $endpoint ) : ?>
                                    <li class="endpoint-item">
                                        <div class="endpoint-header">
                                            <span class="method-badge method-<?php echo esc_attr( strtolower( $endpoint['method'] ) ); ?>">
                                                <?php echo esc_html( $endpoint['method'] ); ?>
                                            </span>
                                            <span class="endpoint-path">
                                                <?php echo esc_html( $endpoint['endpoint'] ); ?>
                                            </span>
                                            <div class="endpoint-info">
                                                <div class="endpoint-title"><?php echo esc_html( $endpoint['title'] ); ?></div>
                                                <div class="endpoint-description"><?php echo esc_html( $endpoint['description'] ); ?></div>
                                            </div>
                                            <?php if ( ! empty( $endpoint['auth_required'] ) ) : ?>
                                                <span class="auth-required"><?php esc_html_e( 'Auth Required', 'care-api' ); ?></span>
                                            <?php endif; ?>
                                            <?php if ( ! empty( $endpoint['required_role'] ) ) : ?>
                                                <span class="role-required"><?php echo esc_html( $endpoint['required_role'] ); ?></span>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="endpoint-details">
                                            
                                            <?php if ( ! empty( $endpoint['parameters'] ) ) : ?>
                                                <div class="endpoint-section">
                                                    <h4><?php esc_html_e( 'Parameters', 'care-api' ); ?></h4>
                                                    <table class="params-table">
                                                        <thead>
                                                            <tr>
                                                                <th><?php esc_html_e( 'Parameter', 'care-api' ); ?></th>
                                                                <th><?php esc_html_e( 'Type', 'care-api' ); ?></th>
                                                                <th><?php esc_html_e( 'Required', 'care-api' ); ?></th>
                                                                <th><?php esc_html_e( 'Description', 'care-api' ); ?></th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ( $endpoint['parameters'] as $param_name => $param ) : ?>
                                                                <tr>
                                                                    <td class="param-name"><?php echo esc_html( $param_name ); ?></td>
                                                                    <td><span class="param-type"><?php echo esc_html( $param['type'] ); ?></span></td>
                                                                    <td>
                                                                        <?php if ( ! empty( $param['required'] ) ) : ?>
                                                                            <span class="param-required"><?php esc_html_e( 'Yes', 'care-api' ); ?></span>
                                                                        <?php else : ?>
                                                                            <?php esc_html_e( 'No', 'care-api' ); ?>
                                                                        <?php endif; ?>
                                                                    </td>
                                                                    <td><?php echo esc_html( $param['description'] ?? '' ); ?></td>
                                                                </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            <?php endif; ?>

                                            <?php if ( ! empty( $endpoint['example_request'] ) ) : ?>
                                                <div class="endpoint-section">
                                                    <h4><?php esc_html_e( 'Example Request', 'care-api' ); ?></h4>
                                                    <div class="code-example">
                                                        <div class="code-example-header">
                                                            <span class="code-language">JSON</span>
                                                            <button class="copy-button" title="<?php esc_attr_e( 'Copy to clipboard', 'care-api' ); ?>">
                                                                <i class="dashicons dashicons-clipboard"></i>
                                                            </button>
                                                        </div>
                                                        <div class="code-content"><?php echo esc_html( wp_json_encode( $endpoint['example_request'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ); ?></div>
                                                    </div>
                                                </div>
                                            <?php endif; ?>

                                            <?php if ( ! empty( $endpoint['example_response'] ) ) : ?>
                                                <div class="endpoint-section">
                                                    <h4><?php esc_html_e( 'Example Response', 'care-api' ); ?></h4>
                                                    <div class="code-example">
                                                        <div class="code-example-header">
                                                            <span class="code-language">JSON</span>
                                                            <button class="copy-button" title="<?php esc_attr_e( 'Copy to clipboard', 'care-api' ); ?>">
                                                                <i class="dashicons dashicons-clipboard"></i>
                                                            </button>
                                                        </div>
                                                        <div class="code-content"><?php echo esc_html( wp_json_encode( $endpoint['example_response'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ); ?></div>
                                                    </div>
                                                </div>
                                            <?php endif; ?>

                                        </div>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <!-- Authentication Tab -->
            <div id="authentication" class="tab-content" style="display: none;">
                <div class="endpoint-section">
                    <h2><?php esc_html_e( 'Authentication', 'care-api' ); ?></h2>
                    <p><?php esc_html_e( 'The Care API uses JSON Web Tokens (JWT) for authentication. All authenticated requests must include the JWT token in the Authorization header.', 'care-api' ); ?></p>
                    
                    <div class="notice notice-warning">
                        <p><strong><?php esc_html_e( 'SECURITY WARNING:', 'care-api' ); ?></strong> <?php esc_html_e( 'Never expose real JWT tokens in documentation, logs, or client-side code. Always use placeholder tokens for examples and secure token storage in production.', 'care-api' ); ?></p>
                    </div>

                    <h3><?php esc_html_e( 'Getting a Token', 'care-api' ); ?></h3>
                    <p><?php esc_html_e( 'Use the login endpoint to obtain a JWT token:', 'care-api' ); ?></p>
                    
                    <div class="code-example">
                        <div class="code-example-header">
                            <span class="code-language">cURL</span>
                            <button class="copy-button" title="<?php esc_attr_e( 'Copy to clipboard', 'care-api' ); ?>">
                                <i class="dashicons dashicons-clipboard"></i>
                            </button>
                        </div>
                        <div class="code-content">curl -X POST <?php echo esc_url( rest_url( 'care/v1/auth/login' ) ); ?> \
  -H "Content-Type: application/json" \
  -d '{
    "username": "your_username",
    "password": "your_password"
  }'</div>
                    </div>

                    <h3><?php esc_html_e( 'Using the Token', 'care-api' ); ?></h3>
                    <p><?php esc_html_e( 'Include the JWT token in the Authorization header of your requests:', 'care-api' ); ?></p>
                    
                    <div class="code-example">
                        <div class="code-example-header">
                            <span class="code-language">cURL</span>
                            <button class="copy-button" title="<?php esc_attr_e( 'Copy to clipboard', 'care-api' ); ?>">
                                <i class="dashicons dashicons-clipboard"></i>
                            </button>
                        </div>
                        <div class="code-content">curl -X GET <?php echo esc_url( rest_url( 'care/v1/patients' ) ); ?> \
  -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE"</div>
                    </div>

                    <h3><?php esc_html_e( 'User Roles and Permissions', 'care-api' ); ?></h3>
                    <p><?php esc_html_e( 'Different user roles have access to different API endpoints:', 'care-api' ); ?></p>
                    
                    <table class="params-table">
                        <thead>
                            <tr>
                                <th><?php esc_html_e( 'Role', 'care-api' ); ?></th>
                                <th><?php esc_html_e( 'Permissions', 'care-api' ); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><strong>Administrator</strong></td>
                                <td><?php esc_html_e( 'Full access to all endpoints and data', 'care-api' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Doctor</strong></td>
                                <td><?php esc_html_e( 'Access to patients, appointments, encounters, prescriptions for their clinic(s)', 'care-api' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Patient</strong></td>
                                <td><?php esc_html_e( 'Read-only access to their own data, book appointments', 'care-api' ); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Receptionist</strong></td>
                                <td><?php esc_html_e( 'Manage appointments, basic patient data for their clinic', 'care-api' ); ?></td>
                            </tr>
                        </tbody>
                    </table>

                    <h3><?php esc_html_e( 'Token Refresh', 'care-api' ); ?></h3>
                    <p><?php esc_html_e( 'JWT tokens expire after 24 hours. Use the refresh endpoint to get a new token:', 'care-api' ); ?></p>
                    
                    <div class="code-example">
                        <div class="code-example-header">
                            <span class="code-language">cURL</span>
                            <button class="copy-button" title="<?php esc_attr_e( 'Copy to clipboard', 'care-api' ); ?>">
                                <i class="dashicons dashicons-clipboard"></i>
                            </button>
                        </div>
                        <div class="code-content">curl -X POST <?php echo esc_url( rest_url( 'care/v1/auth/refresh' ) ); ?> \
  -H "Authorization: Bearer YOUR_CURRENT_TOKEN"</div>
                    </div>
                </div>
            </div>

            <!-- Code Examples Tab -->
            <div id="examples" class="tab-content" style="display: none;">
                <div class="endpoint-section">
                    <h2><?php esc_html_e( 'Code Examples', 'care-api' ); ?></h2>
                    <p><?php esc_html_e( 'Here are practical examples of using the Care API in different programming languages:', 'care-api' ); ?></p>

                    <h3><?php esc_html_e( 'JavaScript (Fetch API)', 'care-api' ); ?></h3>
                    <div class="code-example">
                        <div class="code-example-header">
                            <span class="code-language">JavaScript</span>
                            <button class="copy-button" title="<?php esc_attr_e( 'Copy to clipboard', 'care-api' ); ?>">
                                <i class="dashicons dashicons-clipboard"></i>
                            </button>
                        </div>
                        <div class="code-content">// Login and get token
const loginResponse = await fetch('<?php echo esc_url( rest_url( 'care/v1/auth/login' ) ); ?>', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    username: 'your_username',
    password: 'your-secure-password'
  })
});

const loginData = await loginResponse.json();
const token = loginData.data.token;

// Use token to make authenticated requests
const patientsResponse = await fetch('<?php echo esc_url( rest_url( 'care/v1/patients' ) ); ?>', {
  headers: {
    'Authorization': `Bearer ${token}`
  }
});

const patients = await patientsResponse.json();
console.log(patients.data);</div>
                    </div>

                    <h3><?php esc_html_e( 'PHP (WordPress)', 'care-api' ); ?></h3>
                    <div class="code-example">
                        <div class="code-example-header">
                            <span class="code-language">PHP</span>
                            <button class="copy-button" title="<?php esc_attr_e( 'Copy to clipboard', 'care-api' ); ?>">
                                <i class="dashicons dashicons-clipboard"></i>
                            </button>
                        </div>
                        <div class="code-content">&lt;?php
// Login and get token
$login_response = wp_remote_post('<?php echo esc_url( rest_url( 'care/v1/auth/login' ) ); ?>', [
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode([
        'username' => 'your_username',
        'password' => 'your-secure-password'
    ])
]);

$login_data = json_decode(wp_remote_retrieve_body($login_response), true);
$token = $login_data['data']['token'];

// Use token to make authenticated requests
$patients_response = wp_remote_get('<?php echo esc_url( rest_url( 'care/v1/patients' ) ); ?>', [
    'headers' => [
        'Authorization' => 'Bearer ' . $token
    ]
]);

$patients = json_decode(wp_remote_retrieve_body($patients_response), true);
var_dump($patients['data']);
?&gt;</div>
                    </div>

                    <h3><?php esc_html_e( 'Python (Requests)', 'care-api' ); ?></h3>
                    <div class="code-example">
                        <div class="code-example-header">
                            <span class="code-language">Python</span>
                            <button class="copy-button" title="<?php esc_attr_e( 'Copy to clipboard', 'care-api' ); ?>">
                                <i class="dashicons dashicons-clipboard"></i>
                            </button>
                        </div>
                        <div class="code-content">import requests
import json

# Login and get token
login_data = {
    'username': 'your_username',
    'password': 'your-secure-password'
}

login_response = requests.post(
    '<?php echo esc_url( rest_url( 'care/v1/auth/login' ) ); ?>',
    json=login_data
)

token = login_response.json()['data']['token']

# Use token to make authenticated requests
headers = {'Authorization': f'Bearer {token}'}

patients_response = requests.get(
    '<?php echo esc_url( rest_url( 'care/v1/patients' ) ); ?>',
    headers=headers
)

patients = patients_response.json()
print(patients['data'])</div>
                    </div>

                    <h3><?php esc_html_e( 'Common Use Cases', 'care-api' ); ?></h3>
                    
                    <h4><?php esc_html_e( 'Book an Appointment', 'care-api' ); ?></h4>
                    <div class="code-example">
                        <div class="code-example-header">
                            <span class="code-language">JavaScript</span>
                            <button class="copy-button" title="<?php esc_attr_e( 'Copy to clipboard', 'care-api' ); ?>">
                                <i class="dashicons dashicons-clipboard"></i>
                            </button>
                        </div>
                        <div class="code-content">// Book an appointment
const appointmentData = {
  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'
};

const response = await fetch('<?php echo esc_url( rest_url( 'care/v1/appointments' ) ); ?>', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify(appointmentData)
});

const appointment = await response.json();
console.log('Appointment created:', appointment.data);</div>
                    </div>

                    <h4><?php esc_html_e( 'Get Patient Medical History', 'care-api' ); ?></h4>
                    <div class="code-example">
                        <div class="code-example-header">
                            <span class="code-language">JavaScript</span>
                            <button class="copy-button" title="<?php esc_attr_e( 'Copy to clipboard', 'care-api' ); ?>">
                                <i class="dashicons dashicons-clipboard"></i>
                            </button>
                        </div>
                        <div class="code-content">// Get patient medical history
const patientId = 123;
const historyResponse = await fetch(`<?php echo esc_url( rest_url( 'care/v1/patients/' ) ); ?>${patientId}/history`, {
  headers: {
    'Authorization': `Bearer ${token}`
  }
});

const history = await historyResponse.json();
console.log('Medical history:', history.data);</div>
                    </div>
                </div>
            </div>

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