<?php
session_start();
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Check authorization - only Super Admin and Hospital Admin
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_id'], [1, 2])) {
    header('Location: login.php');
    exit();
}

// Fetch current settings grouped by category
function getSettingsByCategory($conn, $category) {
    $sql = "SELECT setting_key, setting_value FROM system_settings WHERE category = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $category);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $settings = [];
    while ($row = $result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    return $settings;
}

$hospital_settings = getSettingsByCategory($conn, 'hospital');
$mpesa_settings = getSettingsByCategory($conn, 'mpesa');
$sms_settings = getSettingsByCategory($conn, 'sms');
$email_settings = getSettingsByCategory($conn, 'email');
$chatbot_settings = getSettingsByCategory($conn, 'chatbot');
$system_settings = getSettingsByCategory($conn, 'system');
$security_settings = getSettingsByCategory($conn, 'security');
$etims_settings = getSettingsByCategory($conn, 'etims');
$video_settings = getSettingsByCategory($conn, 'video_conferencing');
$smart_settings = getSettingsByCategory($conn, 'smart');

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_settings'])) {
    $category = $_POST['category'];
    
    $conn->begin_transaction();
    
    try {
        // Handle logo upload for hospital settings
        if ($category === 'hospital' && isset($_FILES['hospital_logo']) && $_FILES['hospital_logo']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = 'assets/images/';
            $file_extension = strtolower(pathinfo($_FILES['hospital_logo']['name'], PATHINFO_EXTENSION));
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'svg'];
            
            if (in_array($file_extension, $allowed_extensions)) {
                $new_filename = 'hospital-logo-' . time() . '.' . $file_extension;
                $upload_path = $upload_dir . $new_filename;
                
                if (move_uploaded_file($_FILES['hospital_logo']['tmp_name'], $upload_path)) {
                    // Delete old logo if exists
                    if (!empty($hospital_settings['hospital_logo']) && file_exists($hospital_settings['hospital_logo'])) {
                        unlink($hospital_settings['hospital_logo']);
                    }
                    $_POST['hospital_logo'] = $upload_path;
                }
            }
        }
        
        foreach ($_POST as $key => $value) {
            if ($key === 'save_settings' || $key === 'category') continue;
            
            // Handle checkboxes (unchecked = 0)
            if (!isset($_POST[$key]) && strpos($key, 'enabled') !== false) {
                $value = '0';
            }
            
            // Check if setting exists
            $check_sql = "SELECT setting_id FROM system_settings WHERE setting_key = ?";
            $check_stmt = $conn->prepare($check_sql);
            $check_stmt->bind_param("s", $key);
            $check_stmt->execute();
            $exists = $check_stmt->get_result()->fetch_assoc();
            
            if ($exists) {
                $update_sql = "UPDATE system_settings SET setting_value = ?, updated_by = ?, updated_at = NOW() WHERE setting_key = ?";
                $update_stmt = $conn->prepare($update_sql);
                $update_stmt->bind_param("sis", $value, $_SESSION['user_id'], $key);
                $update_stmt->execute();
            } else {
                $insert_sql = "INSERT INTO system_settings (setting_key, setting_value, category, updated_by) VALUES (?, ?, ?, ?)";
                $insert_stmt = $conn->prepare($insert_sql);
                $insert_stmt->bind_param("sssi", $key, $value, $category, $_SESSION['user_id']);
                $insert_stmt->execute();
            }
        }
        
        // Log activity
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_type, ip_address) VALUES (?, 'UPDATE', 'system_settings', ?, ?)";
        $log_stmt = $conn->prepare($log_sql);
        $log_stmt->bind_param("iss", $_SESSION['user_id'], $category, $_SERVER['REMOTE_ADDR']);
        $log_stmt->execute();
        
        $conn->commit();
        $success_message = ucfirst($category) . " settings updated successfully!";
        
        // Refresh settings after save
        ${$category . '_settings'} = getSettingsByCategory($conn, $category);
        
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = "Error updating settings: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'System Settings')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .settings-wrapper { min-height: calc(100vh - 200px); }
        
        .settings-sidebar {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            position: sticky;
            top: 20px;
            height: fit-content;
        }
        
        .settings-nav-link {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.875rem 1rem;
            margin-bottom: 0.5rem;
            border-radius: 8px;
            color: #64748b;
            text-decoration: none;
            transition: all 0.2s;
            border: 1px solid transparent;
        }
        
        .settings-nav-link:hover {
            background: #f8fafc;
            color: #059669;
            border-color: #e2e8f0;
        }
        
        .settings-nav-link.active {
            background: #059669;
            color: white;
            font-weight: 500;
        }
        
        .settings-nav-link i { font-size: 1.25rem; }
        
        .settings-content {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        
        .settings-header {
            padding: 2rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .settings-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .settings-title i { color: #059669; }
        
        .settings-body { padding: 2rem; }
        
        .form-section {
            margin-bottom: 2.5rem;
            padding-bottom: 2rem;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .form-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }
        
        .section-header {
            font-size: 1.125rem;
            font-weight: 600;
            color: #334155;
            margin-bottom: 1.5rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .help-text {
            font-size: 0.875rem;
            color: #64748b;
            margin-top: 0.25rem;
        }
        
        .switch-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem;
            background: #f8fafc;
            border-radius: 8px;
            margin-bottom: 1.5rem;
        }
        
        .switch-label {
            font-weight: 500;
            color: #334155;
        }
        
        .form-switch .form-check-input {
            width: 3rem;
            height: 1.5rem;
            cursor: pointer;
        }
        
        .settings-footer {
            padding: 1.5rem 2rem;
            border-top: 1px solid #e2e8f0;
            background: #f8fafc;
            border-radius: 0 0 12px 12px;
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
        }
        
        .test-status {
            margin-top: 1rem;
            padding: 1rem;
            border-radius: 8px;
            display: none;
        }
        
        .test-status.success {
            background: #dcfce7;
            color: #166534;
            border: 1px solid #86efac;
        }
        
        .test-status.error {
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fca5a5;
        }
        
        .info-alert {
            background: #dbeafe;
            border: 1px solid #93c5fd;
            color: #1e40af;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
        }
        
        .logo-preview {
            max-width: 200px;
            max-height: 100px;
            margin-top: 1rem;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.5rem;
        }
        
        .upload-area {
            border: 2px dashed #cbd5e1;
            border-radius: 8px;
            padding: 2rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .upload-area:hover {
            border-color: #059669;
            background: #f0fdf4;
        }
        
        .upload-area.dragover {
            border-color: #059669;
            background: #d1fae5;
        }
        
        .code-block {
            background: #1e293b;
            color: #e2e8f0;
            padding: 1rem;
            border-radius: 6px;
            font-family: 'Courier New', monospace;
            font-size: 0.875rem;
            overflow-x: auto;
        }
        
        .provider-card {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            cursor: pointer;
            transition: all 0.2s;
            height: 100%;
        }
        
        .provider-card:hover {
            border-color: #059669;
            background: #f0fdf4;
        }
        
        .provider-card.active {
            border-color: #059669;
            background: #dcfce7;
        }
        
        .provider-config {
            animation: fadeIn 0.3s;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-0">System Settings</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item">System Administration</li>
                                        <li class="breadcrumb-item active">Settings</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (isset($success_message)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="ri-check-line me-2"></i><?php echo $success_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if (isset($error_message)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="ri-error-warning-line me-2"></i><?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <div class="row settings-wrapper">
                        <!-- Settings Sidebar -->
                        <div class="col-lg-3">
                            <div class="settings-sidebar">
                                <h5 class="mb-3">Settings Menu</h5>
                                <nav class="nav flex-column">
                                    <a href="#" class="settings-nav-link active" data-section="general">
                                        <i class="ri-settings-3-line"></i>
                                        <span>General Settings</span>
                                    </a>
                                    <a href="#" class="settings-nav-link" data-section="hospital">
                                        <i class="ri-hospital-line"></i>
                                        <span>Hospital Info</span>
                                    </a>
                                    <a href="#" class="settings-nav-link" data-section="mpesa">
                                        <i class="ri-smartphone-line"></i>
                                        <span>M-Pesa</span>
                                    </a>
                                    <a href="#" class="settings-nav-link" data-section="sms">
                                        <i class="ri-message-2-line"></i>
                                        <span>SMS Settings</span>
                                    </a>
                                    <a href="#" class="settings-nav-link" data-section="email">
                                        <i class="ri-mail-line"></i>
                                        <span>Email Settings</span>
                                    </a>
                                    <a href="#" class="settings-nav-link" data-section="video">
                                        <i class="ri-vidicon-line"></i>
                                        <span>Video Conferencing</span>
                                    </a>
                                    <a href="#" class="settings-nav-link" data-section="chatbot">
                                        <i class="ri-robot-line"></i>
                                        <span>AI Chatbot</span>
                                    </a>
                                    <a href="#" class="settings-nav-link" data-section="etims">
                                        <i class="ri-file-list-3-line"></i>
                                        <span>eTIMS Integration</span>
                                    </a>
                                    <a href="#" class="settings-nav-link" data-section="smart">
                                        <i class="ri-shield-star-line"></i>
                                        <span>Smart Integration</span>
                                    </a>
                                    <a href="#" class="settings-nav-link" data-section="security">
                                        <i class="ri-shield-check-line"></i>
                                        <span>Security</span>
                                    </a>
                                </nav>
                            </div>
                        </div>

                        <div class="col-lg-9">
                            <!-- General Settings -->
                            <div id="general" class="settings-content settings-section">
                                <div class="settings-header">
                                    <h2 class="settings-title">
                                        <i class="ri-settings-3-line"></i>
                                        General System Settings
                                    </h2>
                                </div>
                                
                                <form method="POST">
                                    <input type="hidden" name="category" value="system">
                                    
                                    <div class="settings-body">
                                        <div class="form-section">
                                            <h5 class="section-header">Regional Settings</h5>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">System Timezone</label>
                                                    <select class="form-select" name="timezone">
                                                        <option value="Africa/Nairobi" <?php echo ($system_settings['timezone'] ?? 'Africa/Nairobi') == 'Africa/Nairobi' ? 'selected' : ''; ?>>Africa/Nairobi (EAT)</option>
                                                        <option value="Africa/Lagos" <?php echo ($system_settings['timezone'] ?? '') == 'Africa/Lagos' ? 'selected' : ''; ?>>Africa/Lagos (WAT)</option>
                                                        <option value="Africa/Cairo" <?php echo ($system_settings['timezone'] ?? '') == 'Africa/Cairo' ? 'selected' : ''; ?>>Africa/Cairo (EET)</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Date Format</label>
                                                    <select class="form-select" name="date_format">
                                                        <option value="d/m/Y" <?php echo ($system_settings['date_format'] ?? 'd/m/Y') == 'd/m/Y' ? 'selected' : ''; ?>>DD/MM/YYYY</option>
                                                        <option value="m/d/Y" <?php echo ($system_settings['date_format'] ?? '') == 'm/d/Y' ? 'selected' : ''; ?>>MM/DD/YYYY</option>
                                                        <option value="Y-m-d" <?php echo ($system_settings['date_format'] ?? '') == 'Y-m-d' ? 'selected' : ''; ?>>YYYY-MM-DD</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Time Format</label>
                                                    <select class="form-select" name="time_format">
                                                        <option value="12" <?php echo ($system_settings['time_format'] ?? '12') == '12' ? 'selected' : ''; ?>>12-hour (AM/PM)</option>
                                                        <option value="24" <?php echo ($system_settings['time_format'] ?? '') == '24' ? 'selected' : ''; ?>>24-hour</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Currency</label>
                                                    <select class="form-select" name="currency">
                                                        <option value="KES" <?php echo ($system_settings['currency'] ?? 'KES') == 'KES' ? 'selected' : ''; ?>>KES - Kenyan Shilling</option>
                                                        <option value="USD" <?php echo ($system_settings['currency'] ?? '') == 'USD' ? 'selected' : ''; ?>>USD - US Dollar</option>
                                                        <option value="EUR" <?php echo ($system_settings['currency'] ?? '') == 'EUR' ? 'selected' : ''; ?>>EUR - Euro</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">Feature Toggles</h5>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="patient_portal_enabled" value="1"
                                                           <?php echo ($system_settings['patient_portal_enabled'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable Patient Online Portal</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="online_booking_enabled" value="1"
                                                           <?php echo ($system_settings['online_booking_enabled'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable Online Appointment Booking</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="telemedicine_enabled" value="1"
                                                           <?php echo ($system_settings['telemedicine_enabled'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable Telemedicine Consultations</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="maintenance_mode" value="1"
                                                           <?php echo ($system_settings['maintenance_mode'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label text-danger">System Maintenance Mode</label>
                                                </div>
                                                <div class="help-text">Disables patient portal and online features</div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">Medical Settings</h5>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Default Consultation Fee (KES)</label>
                                                    <input type="number" step="0.01" class="form-control" name="consultation_fee_default" 
                                                           value="<?php echo htmlspecialchars($system_settings['consultation_fee_default'] ?? '3000.00'); ?>">
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Default Follow-up Fee (KES)</label>
                                                    <input type="number" step="0.01" class="form-control" name="follow_up_fee_default" 
                                                           value="<?php echo htmlspecialchars($system_settings['follow_up_fee_default'] ?? '2000.00'); ?>">
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Emergency Surcharge (%)</label>
                                                    <input type="number" step="0.01" class="form-control" name="emergency_surcharge" 
                                                           value="<?php echo htmlspecialchars($system_settings['emergency_surcharge'] ?? '20.00'); ?>">
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Appointment Duration (minutes)</label>
                                                    <input type="number" class="form-control" name="default_appointment_duration" 
                                                           value="<?php echo htmlspecialchars($system_settings['default_appointment_duration'] ?? '30'); ?>">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="settings-footer">
                                        <button type="submit" name="save_settings" class="btn btn-primary">
                                            <i class="ri-save-line me-1"></i> Save Settings
                                        </button>
                                    </div>
                                </form>
                            </div>

                            <!-- Hospital Information Settings -->
                            <div id="hospital" class="settings-content settings-section" style="display:none;">
                                <div class="settings-header">
                                    <h2 class="settings-title">
                                        <i class="ri-hospital-line"></i>
                                        Hospital Information
                                    </h2>
                                </div>
                                
                                <form method="POST" enctype="multipart/form-data">
                                    <input type="hidden" name="category" value="hospital">
                                    
                                    <div class="settings-body">
                                        <div class="form-section">
                                            <h5 class="section-header">Basic Information</h5>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Hospital Name</label>
                                                <input type="text" class="form-control" name="hospital_name" 
                                                       value="<?php echo htmlspecialchars($hospital_settings['hospital_name'] ?? ''); ?>" required>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Phone Number</label>
                                                    <input type="text" class="form-control" name="hospital_phone" 
                                                           value="<?php echo htmlspecialchars($hospital_settings['hospital_phone'] ?? ''); ?>">
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Email Address</label>
                                                    <input type="email" class="form-control" name="hospital_email" 
                                                           value="<?php echo htmlspecialchars($hospital_settings['hospital_email'] ?? ''); ?>">
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Address</label>
                                                <textarea class="form-control" name="hospital_address" rows="3"><?php echo htmlspecialchars($hospital_settings['hospital_address'] ?? ''); ?></textarea>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Website</label>
                                                    <input type="url" class="form-control" name="hospital_website" 
                                                           value="<?php echo htmlspecialchars($hospital_settings['hospital_website'] ?? ''); ?>">
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">License Number</label>
                                                    <input type="text" class="form-control" name="hospital_license" 
                                                           value="<?php echo htmlspecialchars($hospital_settings['hospital_license'] ?? ''); ?>">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">Hospital Logo</h5>
                                            
                                            <?php if (!empty($hospital_settings['hospital_logo'])): ?>
                                            <div class="mb-3">
                                                <label class="form-label">Current Logo:</label>
                                                <img src="<?php echo htmlspecialchars($hospital_settings['hospital_logo']); ?>" 
                                                     alt="Hospital Logo" class="logo-preview">
                                            </div>
                                            <?php endif; ?>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Upload New Logo</label>
                                                <input type="file" class="form-control" name="hospital_logo" accept="image/*" id="logoInput">
                                                <div class="help-text">Supported formats: JPG, PNG, GIF, SVG. Max 2MB.</div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="settings-footer">
                                        <button type="submit" name="save_settings" class="btn btn-primary">
                                            <i class="ri-save-line me-1"></i> Save Settings
                                        </button>
                                    </div>
                                </form>
                            </div>

                            <!-- M-Pesa Settings -->
                            <div id="mpesa" class="settings-content settings-section" style="display:none;">
                                <div class="settings-header">
                                    <h2 class="settings-title">
                                        <i class="ri-smartphone-line"></i>
                                        M-Pesa Configuration
                                    </h2>
                                </div>
                                
                                <form method="POST">
                                    <input type="hidden" name="category" value="mpesa">
                                    
                                    <div class="settings-body">
                                        <div class="info-alert">
                                            <i class="ri-information-line me-2"></i>
                                            Configure your Safaricom Daraja API credentials for M-Pesa payments. Get your credentials from <a href="https://developer.safaricom.co.ke" target="_blank">Safaricom Developer Portal</a>.
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">API Credentials</h5>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Environment</label>
                                                    <select class="form-select" name="mpesa_environment">
                                                        <option value="sandbox" <?php echo ($mpesa_settings['mpesa_environment'] ?? 'sandbox') == 'sandbox' ? 'selected' : '';?>>Sandbox (Testing)</option>
                                                        <option value="production" <?php echo ($mpesa_settings['mpesa_environment'] ?? '') == 'production' ? 'selected' : ''; ?>>Production (Live)</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Business Short Code</label>
                                                    <input type="text" class="form-control" name="mpesa_shortcode" 
                                                           value="<?php echo htmlspecialchars($mpesa_settings['mpesa_shortcode'] ?? '174379'); ?>"
                                                           placeholder="e.g., 174379">
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Consumer Key</label>
                                                <input type="text" class="form-control" name="mpesa_consumer_key" 
                                                       value="<?php echo htmlspecialchars($mpesa_settings['mpesa_consumer_key'] ?? ''); ?>"
                                                       placeholder="Your M-Pesa Consumer Key">
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Consumer Secret</label>
                                                <input type="password" class="form-control" name="mpesa_consumer_secret" 
                                                       value="<?php echo htmlspecialchars($mpesa_settings['mpesa_consumer_secret'] ?? ''); ?>"
                                                       placeholder="Your M-Pesa Consumer Secret">
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Passkey</label>
                                                <input type="password" class="form-control" name="mpesa_passkey" 
                                                       value="<?php echo htmlspecialchars($mpesa_settings['mpesa_passkey'] ?? ''); ?>"
                                                       placeholder="Your M-Pesa Passkey">
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">Payment Configuration</h5>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Transaction Type</label>
                                                    <select class="form-select" name="mpesa_transaction_type">
                                                        <option value="CustomerPayBillOnline" <?php echo ($mpesa_settings['mpesa_transaction_type'] ?? 'CustomerPayBillOnline') == 'CustomerPayBillOnline' ? 'selected' : ''; ?>>Pay Bill</option>
                                                        <option value="CustomerBuyGoodsOnline" <?php echo ($mpesa_settings['mpesa_transaction_type'] ?? '') == 'CustomerBuyGoodsOnline' ? 'selected' : ''; ?>>Buy Goods</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Account Reference Prefix</label>
                                                    <input type="text" class="form-control" name="mpesa_account_reference" 
                                                           value="<?php echo htmlspecialchars($mpesa_settings['mpesa_account_reference'] ?? 'ENT-'); ?>"
                                                           placeholder="e.g., ENT-">
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Callback URL</label>
                                                <input type="url" class="form-control" name="mpesa_callback_url" 
                                                       value="<?php echo htmlspecialchars($mpesa_settings['mpesa_callback_url'] ?? ''); ?>"
                                                       placeholder="https://yourdomain.com/mpesa_callback.php">
                                                <div class="help-text">This URL will receive payment confirmations from M-Pesa</div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="mpesa_enabled" value="1"
                                                           <?php echo ($mpesa_settings['mpesa_enabled'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable M-Pesa Payments</label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="settings-footer">
                                        <button type="button" class="btn btn-outline-primary" onclick="testMpesaConnection()">
                                            <i class="ri-refresh-line me-1"></i> Test Connection
                                        </button>
                                        <button type="submit" name="save_settings" class="btn btn-primary">
                                            <i class="ri-save-line me-1"></i> Save Settings
                                        </button>
                                    </div>
                                </form>
                            </div>

                            <!-- SMS Settings -->
                            <div id="sms" class="settings-content settings-section" style="display:none;">
                                <div class="settings-header">
                                    <h2 class="settings-title">
                                        <i class="ri-message-2-line"></i>
                                        SMS Configuration
                                    </h2>
                                </div>
                                
                                <form method="POST">
                                    <input type="hidden" name="category" value="sms">
                                    
                                    <div class="settings-body">
                                        <div class="info-alert">
                                            <i class="ri-information-line me-2"></i>
                                            Configure Africa's Talking API for SMS notifications. Get your API key from <a href="https://africastalking.com" target="_blank">Africa's Talking</a>.
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">API Configuration</h5>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Username</label>
                                                <input type="text" class="form-control" name="sms_username" 
                                                       value="<?php echo htmlspecialchars($sms_settings['sms_username'] ?? ''); ?>"
                                                       placeholder="Your Africa's Talking Username">
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">API Key</label>
                                                <input type="password" class="form-control" name="sms_api_key" 
                                                       value="<?php echo htmlspecialchars($sms_settings['sms_api_key'] ?? ''); ?>"
                                                       placeholder="Your Africa's Talking API Key">
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Sender ID</label>
                                                <input type="text" class="form-control" name="sms_sender_id" 
                                                       value="<?php echo htmlspecialchars($sms_settings['sms_sender_id'] ?? 'ENT HOSP'); ?>"
                                                       placeholder="e.g., ENT HOSP" maxlength="11">
                                                <div class="help-text">Max 11 alphanumeric characters (requires approval)</div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Environment</label>
                                                    <select class="form-select" name="sms_environment">
                                                        <option value="sandbox" <?php echo ($sms_settings['sms_environment'] ?? 'sandbox') == 'sandbox' ? 'selected' : ''; ?>>Sandbox (Testing)</option>
                                                        <option value="production" <?php echo ($sms_settings['sms_environment'] ?? '') == 'production' ? 'selected' : ''; ?>>Production (Live)</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Default Country Code</label>
                                                    <input type="text" class="form-control" name="sms_country_code" 
                                                           value="<?php echo htmlspecialchars($sms_settings['sms_country_code'] ?? '+254'); ?>"
                                                           placeholder="+254">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">Notification Settings</h5>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="sms_enabled" value="1"
                                                           <?php echo ($sms_settings['sms_enabled'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable SMS Notifications</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="sms_appointment_reminders" value="1"
                                                           <?php echo ($sms_settings['sms_appointment_reminders'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Send Appointment Reminders</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="sms_payment_confirmations" value="1"
                                                           <?php echo ($sms_settings['sms_payment_confirmations'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Send Payment Confirmations</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="sms_test_results" value="1"
                                                           <?php echo ($sms_settings['sms_test_results'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Send Test Results Available Notifications</label>
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Reminder Hours Before Appointment</label>
                                                    <input type="number" class="form-control" name="sms_reminder_hours" 
                                                           value="<?php echo htmlspecialchars($sms_settings['sms_reminder_hours'] ?? '24'); ?>">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="settings-footer">
                                        <button type="button" class="btn btn-outline-primary" onclick="testSmsConnection()">
                                            <i class="ri-send-plane-line me-1"></i> Send Test SMS
                                        </button>
                                        <button type="submit" name="save_settings" class="btn btn-primary">
                                            <i class="ri-save-line me-1"></i> Save Settings
                                        </button>
                                    </div>
                                </form>
                            </div>

                            <!-- Email Settings -->
                            <div id="email" class="settings-content settings-section" style="display:none;">
                                <div class="settings-header">
                                    <h2 class="settings-title">
                                        <i class="ri-mail-line"></i>
                                        Email Configuration
                                    </h2>
                                </div>
                                
                                <form method="POST">
                                    <input type="hidden" name="category" value="email">
                                    
                                    <div class="settings-body">
                                        <div class="form-section">
                                            <h5 class="section-header">SMTP Configuration</h5>
                                            
                                            <div class="row">
                                                <div class="col-md-8 mb-3">
                                                    <label class="form-label">SMTP Host</label>
                                                    <input type="text" class="form-control" name="smtp_host" 
                                                           value="<?php echo htmlspecialchars($email_settings['smtp_host'] ?? ''); ?>"
                                                           placeholder="smtp.gmail.com">
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">SMTP Port</label>
                                                    <input type="number" class="form-control" name="smtp_port" 
                                                           value="<?php echo htmlspecialchars($email_settings['smtp_port'] ?? '587'); ?>"
                                                           placeholder="587">
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">SMTP Username</label>
                                                <input type="text" class="form-control" name="smtp_username" 
                                                       value="<?php echo htmlspecialchars($email_settings['smtp_username'] ?? ''); ?>"
                                                       placeholder="your-email@gmail.com">
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">SMTP Password</label>
                                                <input type="password" class="form-control" name="smtp_password" 
                                                       value="<?php echo htmlspecialchars($email_settings['smtp_password'] ?? ''); ?>"
                                                       placeholder="Your SMTP password or App Password">
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Encryption</label>
                                                    <select class="form-select" name="smtp_encryption">
                                                        <option value="tls" <?php echo ($email_settings['smtp_encryption'] ?? 'tls') == 'tls' ? 'selected' : ''; ?>>TLS</option>
                                                        <option value="ssl" <?php echo ($email_settings['smtp_encryption'] ?? '') == 'ssl' ? 'selected' : ''; ?>>SSL</option>
                                                        <option value="none" <?php echo ($email_settings['smtp_encryption'] ?? '') == 'none' ? 'selected' : ''; ?>>None</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">From Email</label>
                                                    <input type="email" class="form-control" name="email_from" 
                                                           value="<?php echo htmlspecialchars($email_settings['email_from'] ?? ''); ?>"
                                                           placeholder="noreply@hospital.com">
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">From Name</label>
                                                <input type="text" class="form-control" name="email_from_name" 
                                                       value="<?php echo htmlspecialchars($email_settings['email_from_name'] ?? ''); ?>"
                                                       placeholder="ENT Hospital">
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">Email Notifications</h5>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="email_enabled" value="1"
                                                           <?php echo ($email_settings['email_enabled'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable Email Notifications</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="email_appointment_confirmations" value="1"
                                                           <?php echo ($email_settings['email_appointment_confirmations'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Send Appointment Confirmations</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="email_medical_reports" value="1"
                                                           <?php echo ($email_settings['email_medical_reports'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Send Medical Reports</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="email_invoices" value="1"
                                                           <?php echo ($email_settings['email_invoices'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Send Invoices & Receipts</label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="settings-footer">
                                        <button type="button" class="btn btn-outline-primary" onclick="testEmailConnection()">
                                            <i class="ri-mail-send-line me-1"></i> Send Test Email
                                        </button>
                                        <button type="submit" name="save_settings" class="btn btn-primary">
                                            <i class="ri-save-line me-1"></i> Save Settings
                                        </button>
                                    </div>
                                </form>
                            </div>

                            <!-- Video Conferencing Settings -->
                            <div id="video" class="settings-content settings-section" style="display:none;">
                                <div class="settings-header">
                                    <h2 class="settings-title">
                                        <i class="ri-vidicon-line"></i>
                                        Video Conferencing Configuration
                                    </h2>
                                </div>
                                
                                <form method="POST">
                                    <input type="hidden" name="category" value="video_conferencing">
                                    
                                    <div class="settings-body">
                                        <div class="info-alert">
                                            <i class="ri-information-line me-2"></i>
                                            Configure video conferencing for telemedicine consultations. Choose from multiple providers based on your needs.
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">General Settings</h5>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="video_enabled" value="1"
                                                           <?php echo ($video_settings['video_enabled'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable Video Conferencing</label>
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Default Video Quality</label>
                                                    <select class="form-select" name="video_quality">
                                                        <option value="360p" <?php echo ($video_settings['video_quality'] ?? '') == '360p' ? 'selected' : ''; ?>>360p (Low bandwidth)</option>
                                                        <option value="480p" <?php echo ($video_settings['video_quality'] ?? '') == '480p' ? 'selected' : ''; ?>>480p (Standard)</option>
                                                        <option value="720p" <?php echo ($video_settings['video_quality'] ?? '720p') == '720p' ? 'selected' : ''; ?>>720p (HD)</option>
                                                        <option value="1080p" <?php echo ($video_settings['video_quality'] ?? '') == '1080p' ? 'selected' : ''; ?>>1080p (Full HD)</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Auto-start Video</label>
                                                    <select class="form-select" name="video_autostart">
                                                        <option value="both" <?php echo ($video_settings['video_autostart'] ?? 'both') == 'both' ? 'selected' : ''; ?>>Doctor & Patient</option>
                                                        <option value="host" <?php echo ($video_settings['video_autostart'] ?? '') == 'host' ? 'selected' : ''; ?>>Doctor Only</option>
                                                        <option value="none" <?php echo ($video_settings['video_autostart'] ?? '') == 'none' ? 'selected' : ''; ?>>None</option>
                                                    </select>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="video_enable_chat" value="1"
                                                           <?php echo ($video_settings['video_enable_chat'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable In-Meeting Chat</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="video_require_authentication" value="1"
                                                           <?php echo ($video_settings['video_require_authentication'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Require Authentication Before Joining</label>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">Select Video Provider</h5>
                                            
                                            <div class="row">
                                                <!-- Jitsi Meet -->
                                                <div class="col-md-6 mb-3">
                                                    <div class="provider-card <?php echo ($video_settings['video_provider'] ?? 'jitsi') == 'jitsi' ? 'active' : ''; ?>" 
                                                         onclick="selectProvider('jitsi')">
                                                        <div class="d-flex align-items-center mb-2">
                                                            <input type="radio" name="video_provider" value="jitsi" 
                                                                   <?php echo ($video_settings['video_provider'] ?? 'jitsi') == 'jitsi' ? 'checked' : ''; ?>>
                                                            <strong class="ms-2">Jitsi Meet</strong>
                                                        </div>
                                                        <p class="text-muted mb-0" style="font-size: 0.875rem;">
                                                            Free & open-source. Self-hosted or use meet.jit.si.
                                                        </p>
                                                    </div>
                                                </div>
                                                
                                                <!-- Daily.co -->
                                                <div class="col-md-6 mb-3">
                                                    <div class="provider-card <?php echo ($video_settings['video_provider'] ?? '') == 'daily' ? 'active' : ''; ?>" 
                                                         onclick="selectProvider('daily')">
                                                        <div class="d-flex align-items-center mb-2">
                                                            <input type="radio" name="video_provider" value="daily" 
                                                                   <?php echo ($video_settings['video_provider'] ?? '') == 'daily' ? 'checked' : ''; ?>>
                                                            <strong class="ms-2">Daily.co</strong>
                                                        </div>
                                                        <p class="text-muted mb-0" style="font-size: 0.875rem;">
                                                            Modern API. Scalable. Requires API key.
                                                        </p>
                                                    </div>
                                                </div>
                                                
                                                <!-- Zoom -->
                                                <div class="col-md-6 mb-3">
                                                    <div class="provider-card <?php echo ($video_settings['video_provider'] ?? '') == 'zoom' ? 'active' : ''; ?>" 
                                                         onclick="selectProvider('zoom')">
                                                        <div class="d-flex align-items-center mb-2">
                                                            <input type="radio" name="video_provider" value="zoom" 
                                                                   <?php echo ($video_settings['video_provider'] ?? '') == 'zoom' ? 'checked' : ''; ?>>
                                                            <strong class="ms-2">Zoom</strong>
                                                        </div>
                                                        <p class="text-muted mb-0" style="font-size: 0.875rem;">
                                                            Enterprise-grade. Requires Zoom SDK or JWT credentials.
                                                        </p>
                                                    </div>
                                                </div>
                                                
                                                <!-- Whereby -->
                                                <div class="col-md-6 mb-3">
                                                    <div class="provider-card <?php echo ($video_settings['video_provider'] ?? '') == 'whereby' ? 'active' : ''; ?>" 
                                                         onclick="selectProvider('whereby')">
                                                        <div class="d-flex align-items-center mb-2">
                                                            <input type="radio" name="video_provider" value="whereby" 
                                                                   <?php echo ($video_settings['video_provider'] ?? '') == 'whereby' ? 'checked' : ''; ?>>
                                                            <strong class="ms-2">Whereby</strong>
                                                        </div>
                                                        <p class="text-muted mb-0" style="font-size: 0.875rem;">
                                                            Embedded video rooms. Simple integration, no downloads.
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Jitsi Meet Configuration -->
                                        <div id="jitsi-config" class="form-section provider-config" style="display: <?php echo ($video_settings['video_provider'] ?? 'jitsi') == 'jitsi' ? 'block' : 'none'; ?>;">
                                            <h5 class="section-header">Jitsi Meet Configuration</h5>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Jitsi Server URL</label>
                                                <input type="url" class="form-control" name="jitsi_server_url" 
                                                       value="<?php echo htmlspecialchars($video_settings['jitsi_server_url'] ?? 'https://meet.jit.si'); ?>"
                                                       placeholder="https://meet.jit.si">
                                                <div class="help-text">Use meet.jit.si for free or your self-hosted instance</div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">App ID (Optional - for JWT)</label>
                                                <input type="text" class="form-control" name="jitsi_app_id" 
                                                       value="<?php echo htmlspecialchars($video_settings['jitsi_app_id'] ?? ''); ?>"
                                                       placeholder="Your Jitsi App ID">
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Secret Key (Optional - for JWT)</label>
                                                <input type="password" class="form-control" name="jitsi_secret_key" 
                                                       value="<?php echo htmlspecialchars($video_settings['jitsi_secret_key'] ?? ''); ?>"
                                                       placeholder="Your Jitsi Secret Key">
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="jitsi_enable_recording" value="1"
                                                               <?php echo ($video_settings['jitsi_enable_recording'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                        <label class="form-check-label">Enable Recording</label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="jitsi_enable_lobby" value="1"
                                                               <?php echo ($video_settings['jitsi_enable_lobby'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                        <label class="form-check-label">Enable Waiting Room</label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Daily.co Configuration -->
                                        <div id="daily-config" class="form-section provider-config" style="display: <?php echo ($video_settings['video_provider'] ?? '') == 'daily' ? 'block' : 'none'; ?>;">
                                            <h5 class="section-header">Daily.co Configuration</h5>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">API Key</label>
                                                <input type="password" class="form-control" name="daily_api_key" 
                                                       value="<?php echo htmlspecialchars($video_settings['daily_api_key'] ?? ''); ?>"
                                                       placeholder="Your Daily.co API Key">
                                                <div class="help-text">Get your API key from <a href="https://dashboard.daily.co" target="_blank">Daily.co Dashboard</a></div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Domain</label>
                                                <input type="text" class="form-control" name="daily_domain" 
                                                       value="<?php echo htmlspecialchars($video_settings['daily_domain'] ?? ''); ?>"
                                                       placeholder="your-subdomain.daily.co">
                                                <div class="help-text">Your Daily.co domain (e.g., mycompany.daily.co)</div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Max Participants</label>
                                                    <input type="number" class="form-control" name="daily_max_participants" 
                                                           value="<?php echo htmlspecialchars($video_settings['daily_max_participants'] ?? '2'); ?>"
                                                           min="2" max="100">
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Meeting Duration (minutes)</label>
                                                    <input type="number" class="form-control" name="daily_meeting_duration" 
                                                           value="<?php echo htmlspecialchars($video_settings['daily_meeting_duration'] ?? '60'); ?>"
                                                           min="15">
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="daily_enable_recording" value="1"
                                                               <?php echo ($video_settings['daily_enable_recording'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                        <label class="form-check-label">Enable Cloud Recording</label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="daily_enable_screenshare" value="1"
                                                               <?php echo ($video_settings['daily_enable_screenshare'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                        <label class="form-check-label">Enable Screen Sharing</label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Zoom Configuration -->
                                        <div id="zoom-config" class="form-section provider-config" style="display: <?php echo ($video_settings['video_provider'] ?? '') == 'zoom' ? 'block' : 'none'; ?>;">
                                            <h5 class="section-header">Zoom Configuration</h5>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Account ID</label>
                                                <input type="text" class="form-control" name="zoom_account_id" 
                                                       value="<?php echo htmlspecialchars($video_settings['zoom_account_id'] ?? ''); ?>"
                                                       placeholder="Your Zoom Account ID">
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Client ID</label>
                                                <input type="text" class="form-control" name="zoom_client_id" 
                                                       value="<?php echo htmlspecialchars($video_settings['zoom_client_id'] ?? ''); ?>"
                                                       placeholder="Your Zoom Client ID">
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Client Secret</label>
                                                <input type="password" class="form-control" name="zoom_client_secret" 
                                                       value="<?php echo htmlspecialchars($video_settings['zoom_client_secret'] ?? ''); ?>"
                                                       placeholder="Your Zoom Client Secret">
                                                <div class="help-text">Create a Server-to-Server OAuth app at <a href="https://marketplace.zoom.us" target="_blank">Zoom Marketplace</a></div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Meeting Type</label>
                                                    <select class="form-select" name="zoom_meeting_type">
                                                        <option value="1" <?php echo ($video_settings['zoom_meeting_type'] ?? '1') == '1' ? 'selected' : ''; ?>>Instant Meeting</option>
                                                        <option value="2" <?php echo ($video_settings['zoom_meeting_type'] ?? '') == '2' ? 'selected' : ''; ?>>Scheduled Meeting</option>
                                                        <option value="3" <?php echo ($video_settings['zoom_meeting_type'] ?? '') == '3' ? 'selected' : ''; ?>>Recurring (No Fixed Time)</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Default Duration (minutes)</label>
                                                    <input type="number" class="form-control" name="zoom_default_duration" 
                                                           value="<?php echo htmlspecialchars($video_settings['zoom_default_duration'] ?? '60'); ?>"
                                                           min="15">
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="zoom_enable_waiting_room" value="1"
                                                               <?php echo ($video_settings['zoom_enable_waiting_room'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                        <label class="form-check-label">Enable Waiting Room</label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="zoom_enable_recording" value="1"
                                                               <?php echo ($video_settings['zoom_enable_recording'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                        <label class="form-check-label">Enable Cloud Recording</label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="zoom_mute_on_entry" value="1"
                                                               <?php echo ($video_settings['zoom_mute_on_entry'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                        <label class="form-check-label">Mute Participants on Entry</label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Whereby Configuration -->
                                        <div id="whereby-config" class="form-section provider-config" style="display: <?php echo ($video_settings['video_provider'] ?? '') == 'whereby' ? 'block' : 'none'; ?>;">
                                            <h5 class="section-header">Whereby Configuration</h5>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">API Key</label>
                                                <input type="password" class="form-control" name="whereby_api_key" 
                                                       value="<?php echo htmlspecialchars($video_settings['whereby_api_key'] ?? ''); ?>"
                                                       placeholder="Your Whereby API Key">
                                                <div class="help-text">Get your API key from <a href="https://whereby.com/information/embedded" target="_blank">Whereby Embedded</a></div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Subdomain</label>
                                                <input type="text" class="form-control" name="whereby_subdomain" 
                                                       value="<?php echo htmlspecialchars($video_settings['whereby_subdomain'] ?? ''); ?>"
                                                       placeholder="your-company">
                                                <div class="help-text">Your Whereby subdomain (e.g., your-company.whereby.com)</div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Room Name Prefix</label>
                                                <input type="text" class="form-control" name="whereby_room_prefix" 
                                                       value="<?php echo htmlspecialchars($video_settings['whereby_room_prefix'] ?? 'ent-consult'); ?>"
                                                       placeholder="ent-consult">
                                                <div class="help-text">Prefix for room names (e.g., ent-consult-12345)</div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="whereby_enable_recording" value="1"
                                                               <?php echo ($video_settings['whereby_enable_recording'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                        <label class="form-check-label">Enable Recording</label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="whereby_lock_room" value="1"
                                                               <?php echo ($video_settings['whereby_lock_room'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                        <label class="form-check-label">Lock Room When Meeting Starts</label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">Additional Settings</h5>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="video_send_reminder_sms" value="1"
                                                               <?php echo ($video_settings['video_send_reminder_sms'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                        <label class="form-check-label">Send SMS Reminder with Meeting Link</label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="video_send_email" value="1"
                                                               <?php echo ($video_settings['video_send_email'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                        <label class="form-check-label">Send Email with Meeting Details</label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="video_log_sessions" value="1"
                                                               <?php echo ($video_settings['video_log_sessions'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                        <label class="form-check-label">Log All Video Sessions</label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="video_end_to_end_encryption" value="1"
                                                               <?php echo ($video_settings['video_end_to_end_encryption'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                        <label class="form-check-label">Enable End-to-End Encryption</label>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Recording Retention (days)</label>
                                                    <input type="number" class="form-control" name="video_recording_retention" 
                                                           value="<?php echo htmlspecialchars($video_settings['video_recording_retention'] ?? '90'); ?>"
                                                           min="30">
                                                    <div class="help-text">How long to keep recordings before auto-deletion</div>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Recording Storage Path</label>
                                                    <input type="text" class="form-control" name="video_recording_path" 
                                                           value="<?php echo htmlspecialchars($video_settings['video_recording_path'] ?? 'recordings/video/'); ?>"
                                                           placeholder="recordings/video/">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="settings-footer">
                                        <button type="button" class="btn btn-outline-primary" onclick="testVideoConnection()">
                                            <i class="ri-vidicon-line me-1"></i> Test Connection
                                        </button>
                                        <button type="submit" name="save_settings" class="btn btn-primary">
                                            <i class="ri-save-line me-1"></i> Save Settings
                                        </button>
                                    </div>
                                </form>
                            </div>

                            <!-- AI Chatbot Settings -->
                            <div id="chatbot" class="settings-content settings-section" style="display:none;">
                                <div class="settings-header">
                                    <h2 class="settings-title">
                                        <i class="ri-robot-line"></i>
                                        AI Chatbot Configuration
                                    </h2>
                                </div>
                                
                                <form method="POST">
                                    <input type="hidden" name="category" value="chatbot">
                                    
                                    <div class="settings-body">
                                        <div class="info-alert">
                                            <i class="ri-information-line me-2"></i>
                                            Configure Claude AI for patient triage and automated assistance.
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">API Configuration</h5>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Anthropic API Key</label>
                                                <input type="password" class="form-control" name="chatbot_api_key" 
                                                       value="<?php echo htmlspecialchars($chatbot_settings['chatbot_api_key'] ?? ''); ?>"
                                                       placeholder="sk-ant-...">
                                                <div class="help-text">Get your API key from <a href="https://console.anthropic.com" target="_blank">Anthropic Console</a></div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Model</label>
                                                    <select class="form-select" name="chatbot_model">
                                                        <option value="claude-sonnet-4-20250514" <?php echo ($chatbot_settings['chatbot_model'] ?? 'claude-sonnet-4-20250514') == 'claude-sonnet-4-20250514' ? 'selected' : ''; ?>>Claude Sonnet 4</option>
                                                        <option value="claude-3-5-sonnet-20241022" <?php echo ($chatbot_settings['chatbot_model'] ?? '') == 'claude-3-5-sonnet-20241022' ? 'selected' : ''; ?>>Claude 3.5 Sonnet</option>
                                                        <option value="claude-3-opus-20240229" <?php echo ($chatbot_settings['chatbot_model'] ?? '') == 'claude-3-opus-20240229' ? 'selected' : ''; ?>>Claude 3 Opus</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Max Tokens</label>
                                                    <input type="number" class="form-control" name="chatbot_max_tokens" 
                                                           value="<?php echo htmlspecialchars($chatbot_settings['chatbot_max_tokens'] ?? '1024'); ?>"
                                                           min="256" max="4096">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">Chatbot Features</h5>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="chatbot_enabled" value="1"
                                                           <?php echo ($chatbot_settings['chatbot_enabled'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable AI Chatbot</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="chatbot_patient_triage" value="1"
                                                           <?php echo ($chatbot_settings['chatbot_patient_triage'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable Patient Triage</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="chatbot_appointment_booking" value="1"
                                                           <?php echo ($chatbot_settings['chatbot_appointment_booking'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Allow Appointment Booking via Chatbot</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="chatbot_symptom_checker" value="1"
                                                           <?php echo ($chatbot_settings['chatbot_symptom_checker'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable Symptom Checker</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Welcome Message</label>
                                                <textarea class="form-control" name="chatbot_welcome_message" rows="3"><?php echo htmlspecialchars($chatbot_settings['chatbot_welcome_message'] ?? 'Hello! I\'m here to help you with your ENT health concerns. How can I assist you today?'); ?></textarea>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="settings-footer">
                                        <button type="submit" name="save_settings" class="btn btn-primary">
                                            <i class="ri-save-line me-1"></i> Save Settings
                                        </button>
                                    </div>
                                </form>
                            </div>

                            <!-- eTIMS Settings with Mock Mode -->
                            <div id="etims" class="settings-content settings-section" style="display:none;">
                                <div class="settings-header">
                                    <h2 class="settings-title">
                                        <i class="ri-file-list-3-line"></i>
                                        eTIMS Integration
                                    </h2>
                                </div>
                                
                                <form method="POST" id="etimsForm">
                                    <input type="hidden" name="category" value="etims">
                                    
                                    <div class="settings-body">
                                        <div class="info-alert">
                                            <i class="ri-information-line me-2"></i>
                                            Configure Kenya Revenue Authority (KRA) eTIMS for tax compliance and electronic invoicing.
                                            <br><br>
                                            <strong>Sandbox Status:</strong> If the sandbox server is unavailable, enable Mock Mode below to continue development.
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">eTIMS Credentials</h5>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Environment</label>
                                                    <select class="form-select" name="etims_environment" id="etimsEnvironment">
                                                        <option value="sandbox" <?php echo ($etims_settings['etims_environment'] ?? 'sandbox') == 'sandbox' ? 'selected' : ''; ?>>Sandbox (Testing)</option>
                                                        <option value="production" <?php echo ($etims_settings['etims_environment'] ?? '') == 'production' ? 'selected' : ''; ?>>Production (Live)</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">TIN Number</label>
                                                    <input type="text" class="form-control" name="etims_tin" 
                                                           value="<?php echo htmlspecialchars($etims_settings['etims_tin'] ?? 'P052077586R'); ?>"
                                                           placeholder="Your KRA TIN Number">
                                                    <div class="help-text">Default sandbox TIN: P052077586R</div>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Device Serial Number</label>
                                                <input type="text" class="form-control" name="etims_device_serial" 
                                                       value="<?php echo htmlspecialchars($etims_settings['etims_device_serial'] ?? ''); ?>"
                                                       placeholder="eTIMS Device Serial Number (Optional)">
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">API Key</label>
                                                <input type="password" class="form-control" name="etims_api_key" 
                                                       value="<?php echo htmlspecialchars($etims_settings['etims_api_key'] ?? 'etims-fc-2025-secure-api-key-9ffhksorghjlys'); ?>"
                                                       placeholder="Your eTIMS API Key">
                                                <div class="help-text">Default sandbox key: etims-fc-2025-secure-api-key-9ffhksorghjlys</div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Branch Code</label>
                                                <input type="text" class="form-control" name="etims_branch_code" 
                                                       value="<?php echo htmlspecialchars($etims_settings['etims_branch_code'] ?? '00'); ?>"
                                                       placeholder="Branch Code (e.g., 00 for main)">
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">Development Settings</h5>
                                            
                                            <div class="mb-3">
                                                <div class="switch-container">
                                                    <div>
                                                        <strong class="switch-label">Mock Mode (Development Only)</strong>
                                                        <p class="mb-0 text-muted" style="font-size: 0.875rem;">
                                                            Use simulated eTIMS responses when sandbox is unavailable
                                                        </p>
                                                    </div>
                                                    <div class="form-switch">
                                                        <input class="form-check-input" type="checkbox" name="etims_mock_mode" value="1"
                                                               id="etimsMockMode"
                                                               <?php echo ($etims_settings['etims_mock_mode'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div id="mockModeWarning" style="display: <?php echo ($etims_settings['etims_mock_mode'] ?? '0') == '1' ? 'block' : 'none'; ?>;">
                                                <div class="alert alert-warning">
                                                    <i class="ri-alert-line me-2"></i>
                                                    <strong>Warning:</strong> Mock Mode is enabled. The system will use simulated eTIMS responses. 
                                                    <strong>Disable this before going to production!</strong>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">eTIMS Features</h5>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="etims_enabled" value="1"
                                                           <?php echo ($etims_settings['etims_enabled'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable eTIMS Integration</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="etims_auto_submit" value="1"
                                                           <?php echo ($etims_settings['etims_auto_submit'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Auto-Submit Invoices to eTIMS</label>
                                                </div>
                                                <div class="help-text">Automatically submit invoices when they are generated</div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="etims_send_customer_copy" value="1"
                                                           <?php echo ($etims_settings['etims_send_customer_copy'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Send Customer Copy via Email/SMS</label>
                                                </div>
                                                <div class="help-text">Send eTIMS receipt to customers automatically</div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="etims_auto_register_services" value="1"
                                                           <?php echo ($etims_settings['etims_auto_register_services'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Auto-Register Services with eTIMS</label>
                                                </div>
                                                <div class="help-text">Automatically register new services/products with KRA</div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">Tax Configuration</h5>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Default Tax Type for Medical Services</label>
                                                    <select class="form-select" name="etims_default_tax_type">
                                                        <option value="B" <?php echo ($etims_settings['etims_default_tax_type'] ?? 'B') == 'B' ? 'selected' : ''; ?>>B - VAT 8% (Reduced)</option>
                                                        <option value="A" <?php echo ($etims_settings['etims_default_tax_type'] ?? '') == 'A' ? 'selected' : ''; ?>>A - VAT 16% (Standard)</option>
                                                        <option value="C" <?php echo ($etims_settings['etims_default_tax_type'] ?? '') == 'C' ? 'selected' : ''; ?>>C - Exempt</option>
                                                        <option value="D" <?php echo ($etims_settings['etims_default_tax_type'] ?? '') == 'D' ? 'selected' : ''; ?>>D - Zero-rated</option>
                                                    </select>
                                                    <div class="help-text">Medical services typically use VAT 8%</div>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Default Item Class for ENT Services</label>
                                                    <input type="text" class="form-control" name="etims_default_item_class" 
                                                           value="<?php echo htmlspecialchars($etims_settings['etims_default_item_class'] ?? '50101502'); ?>"
                                                           placeholder="50101502">
                                                    <div class="help-text">50101502 = ENT Medical Services</div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Connection Test Status -->
                                        <div id="etimsStatus" class="test-status" style="display: none;"></div>
                                    </div>
                                    
                                    <div class="settings-footer">
                                        <button type="button" class="btn btn-outline-secondary" onclick="viewEtimsGuide()">
                                            <i class="ri-book-open-line me-1"></i> Integration Guide
                                        </button>
                                        <button type="button" class="btn btn-outline-primary" onclick="testEtimsConnection()">
                                            <i class="ri-refresh-line me-1"></i> Test Connection
                                        </button>
                                        <button type="submit" name="save_settings" class="btn btn-primary">
                                            <i class="ri-save-line me-1"></i> Save Settings
                                        </button>
                                    </div>
                                </form>
                            </div>
                            
                            <!-- Smart Integration Settings -->
                            <!-- Smart Integration Settings -->
<div id="smart" class="settings-content settings-section" style="display:none;">
    <div class="settings-header">
        <h2 class="settings-title">
            <i class="ri-shield-star-line"></i>
            SMART Integration
        </h2>
    </div>
    
    <form method="POST" id="smartForm">
        <input type="hidden" name="category" value="smart">
        
        <div class="settings-body">
            <div class="info-alert">
                <i class="ri-information-line me-2"></i>
                Configure SMART Application Systems integration for real-time insurance verification and claims processing. 
                <strong>Sandbox credentials are pre-filled for testing.</strong>
            </div>
            
            <div class="form-section">
                <h5 class="section-header">Environment & API Configuration</h5>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Environment</label>
                        <select class="form-select" name="smart_environment" id="smartEnvironment">
                            <option value="development" <?php echo ($smart_settings['smart_environment'] ?? 'development') == 'development' ? 'selected' : ''; ?>>
                                Development (Sandbox)
                            </option>
                            <option value="production" <?php echo ($smart_settings['smart_environment'] ?? '') == 'production' ? 'selected' : ''; ?>>
                                Production (Live)
                            </option>
                        </select>
                        <div class="help-text">Use development for testing with sandbox credentials</div>
                    </div>
                    
                    <div class="col-md-6 mb-3">
                        <label class="form-label">API Base URL</label>
                        <input type="url" class="form-control" name="smart_api_url" 
                               value="<?php echo htmlspecialchars($smart_settings['smart_api_url'] ?? 'https://data.smartapplicationsgroup.com/providerapi-dev'); ?>"
                               placeholder="https://data.smartapplicationsgroup.com/providerapi-dev">
                        <div class="help-text">Sandbox: /providerapi-dev | Production: /providerapi</div>
                    </div>
                </div>
                
                <div class="alert alert-warning mb-3">
                    <strong><i class="ri-information-line me-1"></i> Sandbox Test Credentials</strong>
                    <p class="mb-0 mt-2">The following are test credentials for the SMART sandbox environment. Use these for development and testing.</p>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Provider Key</label>
                    <input type="text" class="form-control" name="smart_provider_key" 
                           value="<?php echo htmlspecialchars($smart_settings['smart_provider_key'] ?? 'SKSP_3194'); ?>"
                           placeholder="SKSP_3194">
                    <div class="help-text">
                        <span class="badge bg-info">Sandbox Default:</span> SKSP_3194
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Username</label>
                        <input type="text" class="form-control" name="smart_username" 
                               value="<?php echo htmlspecialchars($smart_settings['smart_username'] ?? 'ecare'); ?>"
                               placeholder="ecare">
                        <div class="help-text">
                            <span class="badge bg-info">Sandbox Default:</span> ecare
                        </div>
                    </div>
                    
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Password</label>
                        <input type="password" class="form-control" name="smart_password" 
                               value="<?php echo htmlspecialchars($smart_settings['smart_password'] ?? 'P@S5W00rd'); ?>"
                               placeholder="P@S5W00rd">
                        <div class="help-text">
                            <span class="badge bg-info">Sandbox Default:</span> P@S5W00rd
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Client ID (OAuth - Optional)</label>
                        <input type="text" class="form-control" name="smart_client_id" 
                               value="<?php echo htmlspecialchars($smart_settings['smart_client_id'] ?? ''); ?>"
                               placeholder="Leave empty if not using OAuth">
                        <div class="help-text">Only required if using OAuth2 authentication</div>
                    </div>
                    
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Client Secret (OAuth - Optional)</label>
                        <input type="password" class="form-control" name="smart_client_secret" 
                               value="<?php echo htmlspecialchars($smart_settings['smart_client_secret'] ?? ''); ?>"
                               placeholder="Leave empty if not using OAuth">
                        <div class="help-text">Only required if using OAuth2 authentication</div>
                    </div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Accept Language Header</label>
                    <select class="form-select" name="smart_accept_language">
                        <option value="en" <?php echo ($smart_settings['smart_accept_language'] ?? 'en') == 'en' ? 'selected' : ''; ?>>
                            English (en)
                        </option>
                        <option value="ar" <?php echo ($smart_settings['smart_accept_language'] ?? '') == 'ar' ? 'selected' : ''; ?>>
                            Arabic (ar)
                        </option>
                        <option value="fr" <?php echo ($smart_settings['smart_accept_language'] ?? '') == 'fr' ? 'selected' : ''; ?>>
                            French (fr)
                        </option>
                    </select>
                    <div class="help-text">Language for API responses</div>
                </div>
            </div>
            
            <div class="form-section">
                <h5 class="section-header">Test Patient Numbers (Sandbox)</h5>
                <div class="alert alert-info">
                    <strong>Available Test Patient Numbers in Sandbox:</strong>
                    <ul class="mb-0 mt-2">
                        <li><code>70008</code> - Test patient with pending sessions</li>
                        <li><code>ABCH-49085</code> - Test patient for member details</li>
                        <li><code>EQA-00100-21432</code> - Test patient for claims</li>
                    </ul>
                    <p class="mb-0 mt-2"><small>Use these patient numbers when testing SMART integration in sandbox mode.</small></p>
                </div>
            </div>
            
            <div class="form-section">
                <h5 class="section-header">Integration Features</h5>
                
                <div class="mb-3">
                    <div class="switch-container">
                        <div>
                            <strong class="switch-label">Enable SMART Integration</strong>
                            <p class="mb-0 text-muted" style="font-size: 0.875rem;">
                                Master switch for all SMART card functionality
                            </p>
                        </div>
                        <div class="form-switch">
                            <input class="form-check-input" type="checkbox" name="smart_enabled" value="1"
                                   <?php echo ($smart_settings['smart_enabled'] ?? '0') == '1' ? 'checked' : ''; ?>>
                        </div>
                    </div>
                </div>
                
                <div class="mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="smart_auto_verify_cards" value="1"
                               <?php echo ($smart_settings['smart_auto_verify_cards'] ?? '1') == '1' ? 'checked' : ''; ?>>
                        <label class="form-check-label">Auto-Verify Cards on Patient Registration</label>
                    </div>
                    <div class="help-text">Automatically fetch and verify SMART card data during patient registration</div>
                </div>
                
                <div class="mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="smart_auto_activate_sessions" value="1"
                               <?php echo ($smart_settings['smart_auto_activate_sessions'] ?? '1') == '1' ? 'checked' : ''; ?>>
                        <label class="form-check-label">Auto-Activate Sessions with Visit Number</label>
                    </div>
                    <div class="help-text">Automatically activate SMART sessions when patient visits are created</div>
                </div>
                
                <div class="mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="smart_real_time_benefits" value="1"
                               <?php echo ($smart_settings['smart_real_time_benefits'] ?? '1') == '1' ? 'checked' : ''; ?>>
                        <label class="form-check-label">Real-time Benefits Check</label>
                    </div>
                    <div class="help-text">Check available benefits before each service (SBB Rules)</div>
                </div>
                
                <div class="mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="smart_auto_preauth" value="1"
                               <?php echo ($smart_settings['smart_auto_preauth'] ?? '0') == '1' ? 'checked' : ''; ?>>
                        <label class="form-check-label">Automatic Pre-authorization Requests</label>
                    </div>
                    <div class="help-text">Automatically request pre-auth for services that require it</div>
                </div>
                
                <div class="mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="smart_auto_submit_claims" value="1"
                               <?php echo ($smart_settings['smart_auto_submit_claims'] ?? '0') == '1' ? 'checked' : ''; ?>>
                        <label class="form-check-label">Auto-Submit Claims to SMART</label>
                    </div>
                    <div class="help-text">Automatically submit invoices to SMART when generated</div>
                </div>
                
                <div class="mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="smart_block_without_session" value="1"
                               <?php echo ($smart_settings['smart_block_without_session'] ?? '1') == '1' ? 'checked' : ''; ?>>
                        <label class="form-check-label text-warning">
                            <strong>Block Registration Without Valid SMART Session</strong>
                        </label>
                    </div>
                    <div class="help-text">Prevent insurance patient registration if SMART card hasn't been forwarded</div>
                </div>
            </div>
            
            <div class="form-section">
                <h5 class="section-header">Session Management</h5>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Session Timeout (hours)</label>
                        <input type="number" class="form-control" name="smart_session_timeout" 
                               value="<?php echo htmlspecialchars($smart_settings['smart_session_timeout'] ?? '24'); ?>"
                               min="1" max="72">
                        <div class="help-text">Auto-expire inactive SMART sessions after this period</div>
                    </div>
                    
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Max Retries for Failed API Calls</label>
                        <input type="number" class="form-control" name="smart_max_retries" 
                               value="<?php echo htmlspecialchars($smart_settings['smart_max_retries'] ?? '3'); ?>"
                               min="1" max="10">
                        <div class="help-text">Number of retry attempts for failed SMART API calls</div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">API Timeout (seconds)</label>
                        <input type="number" class="form-control" name="smart_api_timeout" 
                               value="<?php echo htmlspecialchars($smart_settings['smart_api_timeout'] ?? '30'); ?>"
                               min="5" max="120">
                        <div class="help-text">Timeout for SMART API requests</div>
                    </div>
                    
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Default Session Type</label>
                        <select class="form-select" name="smart_default_session_type">
                            <option value="Outpatient" <?php echo ($smart_settings['smart_default_session_type'] ?? 'Outpatient') == 'Outpatient' ? 'selected' : ''; ?>>
                                Outpatient
                            </option>
                            <option value="Inpatient" <?php echo ($smart_settings['smart_default_session_type'] ?? '') == 'Inpatient' ? 'selected' : ''; ?>>
                                Inpatient
                            </option>
                        </select>
                        <div class="help-text">Default session type for new visits</div>
                    </div>
                </div>
            </div>
            
            <div class="form-section">
                <h5 class="section-header">API Endpoints Reference</h5>
                <div class="table-responsive">
                    <table class="table table-sm table-bordered">
                        <thead class="table-light">
                            <tr>
                                <th>Endpoint</th>
                                <th>Method</th>
                                <th>Purpose</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><code>/oauth/token</code></td>
                                <td><span class="badge bg-success">POST</span></td>
                                <td>Generate OAuth2 access token</td>
                            </tr>
                            <tr>
                                <td><code>/api/member</code></td>
                                <td><span class="badge bg-info">GET</span></td>
                                <td>Fetch member details and benefits</td>
                            </tr>
                            <tr>
                                <td><code>/api/visit</code></td>
                                <td><span class="badge bg-info">GET</span></td>
                                <td>Fetch visits/sessions</td>
                            </tr>
                            <tr>
                                <td><code>/api/visit/{id}/visit-number/{visitNo}</code></td>
                                <td><span class="badge bg-warning">PUT</span></td>
                                <td>Merge visit with visit number</td>
                            </tr>
                            <tr>
                                <td><code>/api/sbb-rules</code></td>
                                <td><span class="badge bg-success">POST</span></td>
                                <td>Check benefits and pre-auth rules</td>
                            </tr>
                            <tr>
                                <td><code>/api/preauth-request</code></td>
                                <td><span class="badge bg-success">POST</span></td>
                                <td>Submit pre-authorization request</td>
                            </tr>
                            <tr>
                                <td><code>/api/claims</code></td>
                                <td><span class="badge bg-success">POST</span></td>
                                <td>Upload claims/invoices</td>
                            </tr>
                            <tr>
                                <td><code>/api/claim-status</code></td>
                                <td><span class="badge bg-info">GET</span></td>
                                <td>Check claim status</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Connection Test Status -->
            <div id="smartStatus" class="test-status" style="display: none;"></div>
        </div>
        
        <div class="settings-footer">
            <a href="test_smart_connection.php" class="btn btn-outline-secondary" target="_blank">
                <i class="ri-flask-line me-1"></i> Open Test Page
            </a>
            <button type="button" class="btn btn-outline-primary" onclick="testSmartConnection()">
                <i class="ri-refresh-line me-1"></i> Quick Test
            </button>
            <button type="button" class="btn btn-outline-info" onclick="viewSmartDocs()">
                <i class="ri-book-open-line me-1"></i> API Documentation
            </button>
            <button type="submit" name="save_settings" class="btn btn-primary">
                <i class="ri-save-line me-1"></i> Save Settings
            </button>
        </div>
    </form>
</div>

                            <!-- Security Settings -->
                            <div id="security" class="settings-content settings-section" style="display:none;">
                                <div class="settings-header">
                                    <h2 class="settings-title">
                                        <i class="ri-shield-check-line"></i>
                                        Security Configuration
                                    </h2>
                                </div>
                                
                                <form method="POST">
                                    <input type="hidden" name="category" value="security">
                                    
                                    <div class="settings-body">
                                        <div class="form-section">
                                            <h5 class="section-header">Password Policy</h5>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Minimum Password Length</label>
                                                    <input type="number" class="form-control" name="password_min_length" 
                                                           value="<?php echo htmlspecialchars($security_settings['password_min_length'] ?? '8'); ?>"
                                                           min="6" max="20">
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Password Expiry (days)</label>
                                                    <input type="number" class="form-control" name="password_expiry_days" 
                                                           value="<?php echo htmlspecialchars($security_settings['password_expiry_days'] ?? '90'); ?>"
                                                           min="0">
                                                    <div class="help-text">0 = never expires</div>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="password_require_uppercase" value="1"
                                                           <?php echo ($security_settings['password_require_uppercase'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Require Uppercase Letters</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="password_require_numbers" value="1"
                                                           <?php echo ($security_settings['password_require_numbers'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Require Numbers</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="password_require_special" value="1"
                                                           <?php echo ($security_settings['password_require_special'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Require Special Characters</label>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">Session & Login Security</h5>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Session Timeout (minutes)</label>
                                                    <input type="number" class="form-control" name="session_timeout" 
                                                           value="<?php echo htmlspecialchars($security_settings['session_timeout'] ?? '30'); ?>"
                                                           min="5" max="1440">
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Max Login Attempts</label>
                                                    <input type="number" class="form-control" name="max_login_attempts" 
                                                           value="<?php echo htmlspecialchars($security_settings['max_login_attempts'] ?? '5'); ?>"
                                                           min="3" max="10">
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Account Lockout Duration (minutes)</label>
                                                    <input type="number" class="form-control" name="lockout_duration" 
                                                           value="<?php echo htmlspecialchars($security_settings['lockout_duration'] ?? '30'); ?>"
                                                           min="5">
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="two_factor_enabled" value="1"
                                                           <?php echo ($security_settings['two_factor_enabled'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable Two-Factor Authentication</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="force_https" value="1"
                                                           <?php echo ($security_settings['force_https'] ?? '1') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Force HTTPS Connection</label>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-section">
                                            <h5 class="section-header">IP Whitelist</h5>
                                            
                                            <div class="mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" name="ip_whitelist_enabled" value="1"
                                                           <?php echo ($security_settings['ip_whitelist_enabled'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                                    <label class="form-check-label">Enable IP Whitelist</label>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Allowed IP Addresses</label>
                                                <textarea class="form-control" name="allowed_ips" rows="4" placeholder="One IP per line&#10;e.g., 192.168.1.1&#10;or 192.168.1.0/24"><?php echo htmlspecialchars($security_settings['allowed_ips'] ?? ''); ?></textarea>
                                                <div class="help-text">One IP address or CIDR range per line</div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="settings-footer">
                                        <button type="submit" name="save_settings" class="btn btn-primary">
                                            <i class="ri-save-line me-1"></i> Save Settings
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
<script>
    // Navigation between settings sections
    document.querySelectorAll('.settings-nav-link').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // Update active link
            document.querySelectorAll('.settings-nav-link').forEach(l => l.classList.remove('active'));
            this.classList.add('active');
            
            // Show corresponding section
            const sectionId = this.dataset.section;
            document.querySelectorAll('.settings-section').forEach(section => {
                section.style.display = 'none';
            });
            document.getElementById(sectionId).style.display = 'block';
        });
    });
    
    // Logo upload functionality
    const uploadArea = document.getElementById('uploadArea');
    const logoInput = document.getElementById('logoInput');
    
    if (uploadArea && logoInput) {
        uploadArea.addEventListener('click', () => logoInput.click());
        
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                logoInput.files = files;
                previewLogo(files[0]);
            }
        });
        
        logoInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                previewLogo(this.files[0]);
            }
        });
    }
    
    function previewLogo(file) {
        // Validate file size (max 5MB)
        if (file.size > 5 * 1024 * 1024) {
            Swal.fire({
                icon: 'error',
                title: 'File Too Large',
                text: 'Logo file must be less than 5MB'
            });
            return;
        }
        
        // Validate file type
        const validTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/svg+xml'];
        if (!validTypes.includes(file.type)) {
            Swal.fire({
                icon: 'error',
                title: 'Invalid File Type',
                text: 'Please upload PNG, JPG, GIF, or SVG files only'
            });
            return;
        }
        
        const reader = new FileReader();
        reader.onload = function(e) {
            const currentLogo = document.getElementById('currentLogo');
            if (currentLogo) {
                currentLogo.src = e.target.result;
            } else {
                const preview = document.createElement('img');
                preview.src = e.target.result;
                preview.className = 'logo-preview';
                preview.id = 'currentLogo';
                uploadArea.parentNode.insertBefore(preview, uploadArea);
            }
        };
        reader.readAsDataURL(file);
    }
    
    // Video provider selection
    function selectProvider(provider) {
        // Update radio button
        document.querySelectorAll('input[name="video_provider"]').forEach(radio => {
            radio.checked = (radio.value === provider);
        });
        
        // Update card styling
        document.querySelectorAll('.provider-card').forEach(card => {
            card.classList.remove('active');
        });
        event.currentTarget.classList.add('active');
        
        // Show corresponding configuration
        document.querySelectorAll('.provider-config').forEach(config => {
            config.style.display = 'none';
        });
        
        const configElement = document.getElementById(provider + '-config');
        if (configElement) {
            configElement.style.display = 'block';
        }
    }
    
    // Initialize provider display on page load
    document.addEventListener('DOMContentLoaded', function() {
        // Show the active provider config
        const activeProvider = document.querySelector('input[name="video_provider"]:checked');
        if (activeProvider) {
            const provider = activeProvider.value;
            document.querySelectorAll('.provider-config').forEach(config => {
                config.style.display = 'none';
            });
            const configElement = document.getElementById(provider + '-config');
            if (configElement) {
                configElement.style.display = 'block';
            }
        }
    });
    
    // Test Video Connection
    function testVideoConnection() {
        const btn = event.target;
        const originalText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Testing...';
        
        const formData = new FormData(document.getElementById('videoForm'));
        
        fetch('api/test_video_connection.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            const statusDiv = document.getElementById('videoStatus');
            if (statusDiv) {
                statusDiv.style.display = 'block';
                
                if (data.success) {
                    statusDiv.className = 'test-status success';
                    statusDiv.innerHTML = '<i class="ri-check-line me-2"></i>' + data.message;
                    
                    let detailsHtml = '<strong>Provider:</strong> ' + data.provider + '<br>';
                    if (data.room_url) {
                        detailsHtml += '<strong>Test Room URL:</strong><br><a href="' + data.room_url + '" target="_blank">' + data.room_url + '</a>';
                    }
                    
                    Swal.fire({
                        icon: 'success',
                        title: 'Video Connection Successful!',
                        html: detailsHtml,
                        width: 600,
                        confirmButtonColor: '#059669'
                    });
                } else {
                    statusDiv.className = 'test-status error';
                    statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>' + data.message;
                    
                    Swal.fire({
                        icon: 'error',
                        title: 'Video Connection Failed',
                        text: data.message
                    });
                }
            }
            
            btn.disabled = false;
            btn.innerHTML = originalText;
        })
        .catch(error => {
            const statusDiv = document.getElementById('videoStatus');
            if (statusDiv) {
                statusDiv.style.display = 'block';
                statusDiv.className = 'test-status error';
                statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>Connection test failed: ' + error.message;
            }
            
            Swal.fire({
                icon: 'error',
                title: 'Connection Error',
                text: 'Failed to test video connection: ' + error.message
            });
            
            btn.disabled = false;
            btn.innerHTML = originalText;
        });
    }
    
    // Test eTIMS Connection
    function testEtimsConnection() {
        const btn = event.target;
        const originalText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Testing...';
        
        const formData = new FormData(document.getElementById('etimsForm'));
        
        fetch('api/test_etims_connection.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            const statusDiv = document.getElementById('etimsStatus');
            statusDiv.style.display = 'block';
            
            if (data.success) {
                statusDiv.className = 'test-status success';
                statusDiv.innerHTML = '<i class="ri-check-line me-2"></i>' + data.message;
                
                if (data.details) {
                    statusDiv.innerHTML += '<br><small>Device: ' + data.details.sdcId + ' | MRC: ' + data.details.mrcNo + '</small>';
                }
                
                Swal.fire({
                    icon: 'success',
                    title: 'eTIMS Connection Successful!',
                    text: data.message,
                    confirmButtonColor: '#059669'
                });
            } else {
                statusDiv.className = 'test-status error';
                statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>' + data.message;
                
                Swal.fire({
                    icon: 'error',
                    title: 'eTIMS Connection Failed',
                    text: data.message
                });
            }
            
            btn.disabled = false;
            btn.innerHTML = originalText;
        })
        .catch(error => {
            const statusDiv = document.getElementById('etimsStatus');
            statusDiv.style.display = 'block';
            statusDiv.className = 'test-status error';
            statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>Connection test failed: ' + error.message;
            
            Swal.fire({
                icon: 'error',
                title: 'Connection Error',
                text: 'Failed to connect to eTIMS API: ' + error.message
            });
            
            btn.disabled = false;
            btn.innerHTML = originalText;
        });
    }
    
    // Test Smart Connection
    function testSmartConnection() {
        const btn = event.target;
        const originalText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Testing...';
        
        const formData = new FormData(document.getElementById('smartForm'));
        
        fetch('api/test_smart_connection.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            const statusDiv = document.getElementById('smartStatus');
            statusDiv.style.display = 'block';
            
            if (data.success) {
                statusDiv.className = 'test-status success';
                statusDiv.innerHTML = '<i class="ri-check-line me-2"></i>' + data.message;
                
                let detailsHtml = '<strong>Connection Successful!</strong><br><br>';
                if (data.details) {
                    detailsHtml += '<strong>Environment:</strong> ' + data.details.environment + '<br>';
                    detailsHtml += '<strong>Practice Number:</strong> ' + data.details.practice_number + '<br>';
                    detailsHtml += '<strong>API Version:</strong> ' + (data.details.api_version || 'v1') + '<br>';
                    detailsHtml += '<strong>Status:</strong> <span class="badge bg-success">Connected</span>';
                }
                
                Swal.fire({
                    icon: 'success',
                    title: 'Smart Connection Successful!',
                    html: detailsHtml,
                    width: 600,
                    confirmButtonColor: '#059669'
                });
            } else {
                statusDiv.className = 'test-status error';
                statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>' + data.message;
                
                Swal.fire({
                    icon: 'error',
                    title: 'Smart Connection Failed',
                    html: '<strong>Error:</strong> ' + data.message + '<br><br>' +
                          '<small>Please verify your API credentials and try again.</small>',
                    confirmButtonColor: '#dc3545'
                });
            }
            
            btn.disabled = false;
            btn.innerHTML = originalText;
        })
        .catch(error => {
            const statusDiv = document.getElementById('smartStatus');
            statusDiv.style.display = 'block';
            statusDiv.className = 'test-status error';
            statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>Connection test failed: ' + error.message;
            
            Swal.fire({
                icon: 'error',
                title: 'Connection Error',
                text: 'Failed to connect to Smart API: ' + error.message
            });
            
            btn.disabled = false;
            btn.innerHTML = originalText;
        });
    }
    
    // View Smart Documentation
// View Smart Documentation
function viewSmartDocs() {
    Swal.fire({
        title: 'SMART Integration Documentation',
        html: `
            <div class="text-start">
                <h6>Sandbox Test Credentials:</h6>
                <ul>
                    <li><strong>API URL:</strong> https://data.smartapplicationsgroup.com/providerapi-dev</li>
                    <li><strong>Provider Key:</strong> SKSP_3194</li>
                    <li><strong>Username:</strong> ecare</li>
                    <li><strong>Password:</strong> P@S5W00rd</li>
                    <li><strong>Accept-Language:</strong> en, ar, or fr</li>
                </ul>
                
                <h6 class="mt-3">Test Patient Numbers:</h6>
                <ul>
                    <li><code>70008</code> - For testing visit/session endpoints</li>
                    <li><code>ABCH-49085</code> - For member details (Session ID: 153520)</li>
                    <li><code>EQA-00100-21432</code> - For claims testing (Session ID: 137266)</li>
                </ul>
                
                <h6 class="mt-3">Integration Workflow:</h6>
                <ol>
                    <li><strong>Token Generation:</strong> POST to /oauth/token with credentials</li>
                    <li><strong>Member Lookup:</strong> GET /api/member?PatientNumber=X&sessionId=Y</li>
                    <li><strong>Fetch Visits:</strong> GET /api/visit?patientNumber=X&sessionStatus=PENDING</li>
                    <li><strong>Merge Visit:</strong> PUT /api/visit/{sessionId}/visit-number/{yourVisitNo}</li>
                    <li><strong>Check Benefits:</strong> POST /api/sbb-rules with service items</li>
                    <li><strong>Pre-Auth (if needed):</strong> POST /api/preauth-request</li>
                    <li><strong>Submit Claim:</strong> POST /api/claims with invoice data</li>
                    <li><strong>Check Status:</strong> GET /api/claim-status</li>
                    <li><strong>Close Session:</strong> PUT /api/visit/{sessionId}/close-session</li>
                </ol>
                
                <h6 class="mt-3">Sample Medical Aid Codes (Sandbox):</h6>
                <ul>
                    <li><strong>SAMPLEX2</strong> - Test scheme</li>
                    <li><strong>Member Number:</strong> CAS018, CAS050, QASAMPLE1-00</li>
                    <li><strong>Policy ID:</strong> 1001065</li>
                    <li><strong>Medical Aid Plan:</strong> 1001065.SAMPLE2</li>
                </ul>
                
                <h6 class="mt-3">Important Headers:</h6>
                <ul>
                    <li><code>provider-key</code>: Your provider key (SKSP_3194)</li>
                    <li><code>Authorization</code>: Bearer {access_token}</li>
                    <li><code>accept-language</code>: en, ar, or fr</li>
                    <li><code>Content-Type</code>: application/json (for POST/PUT)</li>
                </ul>
                
                <h6 class="mt-3">Response Codes:</h6>
                <ul>
                    <li><strong>200</strong> - Success</li>
                    <li><strong>400</strong> - Bad request / Invalid data</li>
                    <li><strong>401</strong> - Unauthorized (check token)</li>
                    <li><strong>404</strong> - Not found</li>
                </ul>
                
                <div class="alert alert-info mt-3">
                    <strong>Production Environment:</strong><br>
                    When moving to production, change the API URL to:<br>
                    <code>https://data.smartapplicationsgroup.com/providerapi</code><br>
                    and use your live credentials from SMART.
                </div>
                
                <div class="alert alert-warning mt-2">
                    <strong>Note:</strong> Token expires after a set period. Always check for 401 errors 
                    and regenerate token when needed.
                </div>
            </div>
        `,
        width: 900,
        confirmButtonText: 'Close',
        confirmButtonColor: '#2d7a2d',
        customClass: {
            htmlContainer: 'text-small'
        }
    });
}
    
    // Test M-Pesa Connection
    function testMpesaConnection() {
        const btn = event.target;
        const originalText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Testing...';
        
        const formData = new FormData(document.getElementById('mpesaForm'));
        
        fetch('api/test_mpesa_connection.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            const statusDiv = document.getElementById('mpesaStatus');
            statusDiv.style.display = 'block';
            
            if (data.success) {
                statusDiv.className = 'test-status success';
                statusDiv.innerHTML = '<i class="ri-check-line me-2"></i>' + data.message;
            } else {
                statusDiv.className = 'test-status error';
                statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>' + data.message;
            }
            
            btn.disabled = false;
            btn.innerHTML = originalText;
        })
        .catch(error => {
            const statusDiv = document.getElementById('mpesaStatus');
            statusDiv.style.display = 'block';
            statusDiv.className = 'test-status error';
            statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>Connection test failed: ' + error.message;
            
            btn.disabled = false;
            btn.innerHTML = originalText;
        });
    }
    
    // Test SMS Connection
    function testSMSConnection() {
        const btn = event.target;
        const originalText = btn.innerHTML;
        
        Swal.fire({
            title: 'Send Test SMS',
            input: 'text',
            inputLabel: 'Enter phone number',
            inputPlaceholder: '+254700000000',
            showCancelButton: true,
            confirmButtonText: 'Send Test SMS',
            confirmButtonColor: '#059669',
            inputValidator: (value) => {
                if (!value) {
                    return 'Please enter a phone number';
                }
            }
        }).then((result) => {
            if (result.isConfirmed) {
                btn.disabled = true;
                btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Sending...';
                
                const formData = new FormData(document.getElementById('smsForm'));
                formData.append('test_phone', result.value);
                
                fetch('api/test_sms_connection.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    const statusDiv = document.getElementById('smsStatus');
                    statusDiv.style.display = 'block';
                    
                    if (data.success) {
                        statusDiv.className = 'test-status success';
                        statusDiv.innerHTML = '<i class="ri-check-line me-2"></i>' + data.message;
                        
                        Swal.fire({
                            icon: 'success',
                            title: 'SMS Sent!',
                            text: data.message,
                            confirmButtonColor: '#059669'
                        });
                    } else {
                        statusDiv.className = 'test-status error';
                        statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>' + data.message;
                        
                        Swal.fire({
                            icon: 'error',
                            title: 'SMS Failed',
                            text: data.message
                        });
                    }
                    
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                })
                .catch(error => {
                    const statusDiv = document.getElementById('smsStatus');
                    statusDiv.style.display = 'block';
                    statusDiv.className = 'test-status error';
                    statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>SMS test failed: ' + error.message;
                    
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
            }
        });
    }
    
    // Test Email Connection
    function testEmailConnection() {
        const btn = event.target;
        const originalText = btn.innerHTML;
        
        Swal.fire({
            title: 'Send Test Email',
            input: 'email',
            inputLabel: 'Enter email address',
            inputPlaceholder: 'test@example.com',
            showCancelButton: true,
            confirmButtonText: 'Send Test Email',
            confirmButtonColor: '#059669',
            inputValidator: (value) => {
                if (!value) {
                    return 'Please enter an email address';
                }
            }
        }).then((result) => {
            if (result.isConfirmed) {
                btn.disabled = true;
                btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Sending...';
                
                const formData = new FormData(document.getElementById('emailForm'));
                formData.append('test_email', result.value);
                
                fetch('api/test_email_connection.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    const statusDiv = document.getElementById('emailStatus');
                    statusDiv.style.display = 'block';
                    
                    if (data.success) {
                        statusDiv.className = 'test-status success';
                        statusDiv.innerHTML = '<i class="ri-check-line me-2"></i>' + data.message;
                        
                        Swal.fire({
                            icon: 'success',
                            title: 'Email Sent!',
                            text: data.message,
                            confirmButtonColor: '#059669'
                        });
                    } else {
                        statusDiv.className = 'test-status error';
                        statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>' + data.message;
                        
                        Swal.fire({
                            icon: 'error',
                            title: 'Email Failed',
                            text: data.message
                        });
                    }
                    
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                })
                .catch(error => {
                    const statusDiv = document.getElementById('emailStatus');
                    statusDiv.style.display = 'block';
                    statusDiv.className = 'test-status error';
                    statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>Email test failed: ' + error.message;
                    
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
            }
        });
    }
    
    // Test Chatbot
    function testChatbot() {
        const btn = event.target;
        const originalText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Testing...';
        
        const formData = new FormData(document.getElementById('chatbotForm'));
        formData.append('test_message', 'Hello, I need help booking an appointment');
        
        fetch('api/test_chatbot.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            const statusDiv = document.getElementById('chatbotStatus');
            statusDiv.style.display = 'block';
            
            if (data.success) {
                statusDiv.className = 'test-status success';
                statusDiv.innerHTML = '<i class="ri-check-line me-2"></i><strong>Bot Response:</strong><br>' + data.message;
                
                Swal.fire({
                    icon: 'success',
                    title: 'Chatbot Working!',
                    html: '<strong>Test Message:</strong> Hello, I need help booking an appointment<br><br><strong>Bot Response:</strong><br>' + data.message,
                    width: 600,
                    confirmButtonColor: '#059669'
                });
            } else {
                statusDiv.className = 'test-status error';
                statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>' + data.message;
                
                Swal.fire({
                    icon: 'error',
                    title: 'Chatbot Test Failed',
                    text: data.message
                });
            }
            
            btn.disabled = false;
            btn.innerHTML = originalText;
        })
        .catch(error => {
            const statusDiv = document.getElementById('chatbotStatus');
            statusDiv.style.display = 'block';
            statusDiv.className = 'test-status error';
            statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>Chatbot test failed: ' + error.message;
            
            btn.disabled = false;
            btn.innerHTML = originalText;
        });
    }
</script>
<script>
// Show/hide mock mode warning
document.addEventListener('DOMContentLoaded', function() {
    const mockModeCheckbox = document.getElementById('etimsMockMode');
    const mockModeWarning = document.getElementById('mockModeWarning');
    
    if (mockModeCheckbox && mockModeWarning) {
        mockModeCheckbox.addEventListener('change', function() {
            mockModeWarning.style.display = this.checked ? 'block' : 'none';
        });
    }
});

// View eTIMS integration guide
function viewEtimsGuide() {
    Swal.fire({
        title: 'eTIMS Integration Guide',
        html: `
            <div class="text-start">
                <h6>Sandbox Setup:</h6>
                <ul>
                    <li><strong>TIN:</strong> P052077586R</li>
                    <li><strong>API Key:</strong> etims-fc-2025-secure-api-key-9ffhksorghjlys</li>
                    <li><strong>Branch ID:</strong> 00</li>
                    <li><strong>Swagger Docs:</strong> <a href="http://62.169.23.132:4122/api-docs/" target="_blank">View API Docs</a></li>
                </ul>
                
                <h6 class="mt-3">If Sandbox is Down:</h6>
                <ol>
                    <li>Enable <strong>Mock Mode</strong> in the settings above</li>
                    <li>Continue development with simulated responses</li>
                    <li>All invoice submissions will generate mock receipts</li>
                    <li><strong>Remember to disable Mock Mode before production!</strong></li>
                </ol>
                
                <h6 class="mt-3">Tax Types:</h6>
                <ul>
                    <li><strong>A</strong> - VAT 16% (Standard rate)</li>
                    <li><strong>B</strong> - VAT 8% (Medical services - recommended)</li>
                    <li><strong>C</strong> - Exempt from VAT</li>
                    <li><strong>D</strong> - Zero-rated (0% VAT)</li>
                </ul>
                
                <h6 class="mt-3">Item Classes:</h6>
                <ul>
                    <li><strong>50101502</strong> - ENT Medical Services (your main code)</li>
                    <li><strong>51101500</strong> - Medical Laboratory Services</li>
                </ul>
                
                <h6 class="mt-3">Next Steps:</h6>
                <ol>
                    <li>Test the connection above</li>
                    <li>If it fails, enable Mock Mode temporarily</li>
                    <li>Register your services with eTIMS</li>
                    <li>Configure auto-submission settings</li>
                    <li>Test with a sample invoice</li>
                </ol>
                
                <div class="alert alert-info mt-3">
                    <strong>Note:</strong> The sandbox environment may be temporarily unavailable. 
                    Use Mock Mode to continue development without interruption.
                </div>
            </div>
        `,
        width: 800,
        confirmButtonText: 'Got it!',
        confirmButtonColor: '#059669'
    });
}
</script>
</body>
</html>