<?php
/**
 * System Settings Page
 */

$title = 'System Settings';
$active = 'settings';

// Define BASE_URL if not already defined
if (!defined('BASE_URL')) {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
    $host = $_SERVER['HTTP_HOST'];
    $scriptPath = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
    $basePath = preg_replace('/\/views\/settings$/', '', $scriptPath);
    define('BASE_URL', $protocol . $host . $basePath);
}

// If accessed directly without router, redirect to router URL
if (!isset($settings)) {
    header('Location: ' . BASE_URL . '/settings');
    exit;
}

require_once __DIR__ . '/../layouts/header.php';
require_once __DIR__ . '/../layouts/sidebar.php';

// Generate CSRF token
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_token'];
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1>
                <i class="fas fa-cogs" style="color: #27ae60;"></i>
                System Settings
            </h1>
            <p>Configure and manage system parameters</p>
        </div>
        <div class="header-actions">
            <button class="btn btn-outline" onclick="exportSettings()" style="background: transparent; border: 1px solid #27ae60; color: #27ae60; padding: 10px 20px; border-radius: 6px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; font-weight: 600;">
                <i class="fas fa-download"></i> Export
            </button>
            <button class="btn btn-outline" onclick="showImportModal()" style="background: transparent; border: 1px solid #27ae60; color: #27ae60; padding: 10px 20px; border-radius: 6px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; font-weight: 600;">
                <i class="fas fa-upload"></i> Import
            </button>
            <button class="btn btn-success" onclick="showAddModal()" style="background: #27ae60; color: white; padding: 10px 20px; border-radius: 6px; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; font-weight: 600; border: none; cursor: pointer;">
                <i class="fas fa-plus-circle"></i> Add Setting
            </button>
        </div>
    </div>

    <!-- Settings Tabs - Like Filter Section -->
    <div class="filter-section" style="background: white; border-radius: 8px; margin-bottom: 20px; border: 1px solid #ddd; overflow: hidden;">
        <div class="filter-header" onclick="toggleTabs()" style="padding: 12px 15px; background: #f8f9fa; cursor: pointer; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #ddd;">
            <h3 style="margin: 0; font-size: 1rem; display: flex; align-items: center; gap: 8px;"><i class="fas fa-tags" style="color: #27ae60;"></i> Setting Groups</h3>
            <i class="fas fa-chevron-down" id="tabChevron" style="transition: transform 0.3s;"></i>
        </div>
        <div class="filter-body" id="tabBody" style="padding: 15px; display: block;">
            <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                <?php 
                $first = true;
                foreach ($groups as $groupKey => $groupName): 
                ?>
                <button class="tab-btn" onclick="showGroup('<?php echo $groupKey; ?>', this)" style="padding: 8px 16px; border: 1px solid #ddd; background: <?php echo $first ? '#27ae60' : 'white'; ?>; color: <?php echo $first ? 'white' : '#666'; ?>; border-radius: 20px; cursor: pointer; font-size: 0.85rem; display: inline-flex; align-items: center; gap: 5px; transition: all 0.3s;">
                    <i class="fas fa-<?php echo getGroupIcon($groupKey); ?>"></i>
                    <?php echo htmlspecialchars($groupName); ?>
                </button>
                <?php 
                $first = false;
                endforeach; 
                ?>
            </div>
        </div>
    </div>

    <!-- Settings Forms -->
    <form id="settingsForm" method="POST" action="<?php echo BASE_URL; ?>/settings/update">
        <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
        
        <?php foreach ($settings as $groupKey => $groupSettings): ?>
        <div id="group-<?php echo $groupKey; ?>" class="settings-group" style="display: <?php echo $groupKey === 'general' ? 'block' : 'none'; ?>;">
            <!-- Settings Card -->
            <div class="content-card">
                <div class="section-title">
                    <h2><i class="fas fa-<?php echo getGroupIcon($groupKey); ?>" style="color: #27ae60;"></i> <?php echo htmlspecialchars($groups[$groupKey] ?? ucfirst($groupKey)); ?> Settings</h2>
                    <div style="display: flex; align-items: center; gap: 15px;">
                        <span style="color: #666; font-size: 0.9rem;"><?php echo count($groupSettings); ?> items</span>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="asset-table" style="width: 100%; border-collapse: collapse;">
                        <thead>
                            <tr style="background: #f4f6f9; border-bottom: 2px solid #27ae60;">
                                <th style="padding: 12px; text-align: left;">Setting Key</th>
                                <th style="padding: 12px; text-align: left;">Value</th>
                                <th style="padding: 12px; text-align: left;">Type</th>
                                <th style="padding: 12px; text-align: left;">Description</th>
                                <th style="padding: 12px; text-align: left;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($groupSettings as $setting): ?>
                            <tr style="border-bottom: 1px solid #eee;" id="setting-<?php echo $setting['id']; ?>">
                                <td style="padding: 12px;">
                                    <code style="background: #f4f6f9; padding: 4px 8px; border-radius: 4px; color: #27ae60;"><?php echo htmlspecialchars($setting['setting_key']); ?></code>
                                    <?php if ($setting['is_encrypted']): ?>
                                        <span class="badge" style="background: #fff3cd; color: #856404; padding: 2px 6px; border-radius: 10px; font-size: 0.7rem; margin-left: 5px;">🔒 Encrypted</span>
                                    <?php endif; ?>
                                </td>
                                <td style="padding: 12px;">
                                    <?php echo renderSettingInput($setting); ?>
                                    <input type="hidden" name="types[<?php echo $setting['setting_key']; ?>]" value="<?php echo $setting['data_type']; ?>">
                                    <input type="hidden" name="groups[<?php echo $setting['setting_key']; ?>]" value="<?php echo $groupKey; ?>">
                                    <input type="hidden" name="descriptions[<?php echo $setting['setting_key']; ?>]" value="<?php echo htmlspecialchars($setting['description'] ?? ''); ?>">
                                    <input type="hidden" name="encrypted[<?php echo $setting['setting_key']; ?>]" value="<?php echo $setting['is_encrypted'] ? '1' : '0'; ?>">
                                </td>
                                <td style="padding: 12px;">
                                    <span class="badge" style="background: #e3f2fd; color: #1565c0; padding: 4px 8px; border-radius: 12px; font-size: 0.75rem;">
                                        <?php echo $setting['data_type']; ?>
                                    </span>
                                </td>
                                <td style="padding: 12px; color: #666; font-size: 0.85rem;">
                                    <?php echo htmlspecialchars($setting['description'] ?? ''); ?>
                                </td>
                                <td style="padding: 12px;">
                                    <div class="action-buttons" style="display: flex; gap: 5px;">
                                        <button type="button" class="btn-icon" onclick="editSetting('<?php echo $setting['id']; ?>')" title="Edit" style="display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; border-radius: 4px; color: #666; text-decoration: none; transition: all 0.3s; background: transparent; border: none; cursor: pointer;">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button type="button" class="btn-icon delete" onclick="deleteSetting('<?php echo $setting['setting_key']; ?>')" title="Delete" style="display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; border-radius: 4px; color: #666; text-decoration: none; transition: all 0.3s; background: transparent; border: none; cursor: pointer;">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
        
        <!-- Save Button -->
        <div style="position: sticky; bottom: 20px; background: white; padding: 15px 20px; border-radius: 8px; box-shadow: 0 -4px 10px rgba(0,0,0,0.05); margin-top: 30px; display: flex; gap: 10px; justify-content: flex-end;">
            <button type="submit" class="btn btn-success" id="saveSettings" style="background: #27ae60; color: white; padding: 12px 30px; border-radius: 6px; border: none; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 8px;">
                <i class="fas fa-save"></i> Save All Changes
            </button>
            <button type="button" class="btn btn-outline" onclick="resetForm()" style="background: transparent; border: 1px solid #ddd; color: #666; padding: 12px 30px; border-radius: 6px; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 8px;">
                <i class="fas fa-undo"></i> Reset
            </button>
        </div>
    </form>
</div>

<!-- Add Setting Modal -->
<div class="modal" id="addModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; align-items: center; justify-content: center;">
    <div class="modal-content" style="background: white; border-radius: 8px; width: 90%; max-width: 600px; max-height: 90vh; overflow-y: auto;">
        <div class="modal-header" style="padding: 15px 20px; border-bottom: 1px solid #ddd; display: flex; justify-content: space-between; align-items: center;">
            <h3 style="margin: 0; font-size: 1.2rem; color: #2c3e50;"><i class="fas fa-plus-circle" style="color: #27ae60;"></i> Add New Setting</h3>
            <button class="modal-close" onclick="closeModal('addModal')" style="background: transparent; border: none; font-size: 1.5rem; cursor: pointer; color: #666;">&times;</button>
        </div>
        <form id="addSettingForm" onsubmit="addSetting(event)">
            <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
            
            <div class="modal-body" style="padding: 20px;">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                    <div>
                        <label style="display: block; font-size: 0.85rem; color: #666; margin-bottom: 5px; font-weight: 600;">Setting Key <span style="color: #e53e3e;">*</span></label>
                        <input type="text" name="key" id="settingKey" class="form-control" required 
                               placeholder="e.g., app_name" pattern="[a-zA-Z0-9_\.]+"
                               style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.9rem;">
                        <small style="display: block; margin-top: 3px; font-size: 0.7rem; color: #999;">Only letters, numbers, dots and underscores</small>
                    </div>
                    
                    <div>
                        <label style="display: block; font-size: 0.85rem; color: #666; margin-bottom: 5px; font-weight: 600;">Data Type <span style="color: #e53e3e;">*</span></label>
                        <select name="type" id="settingType" class="form-control" required onchange="toggleEncrypted()" style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.9rem;">
                            <option value="string">String</option>
                            <option value="text">Text</option>
                            <option value="number">Number</option>
                            <option value="boolean">Boolean (Yes/No)</option>
                            <option value="email">Email</option>
                            <option value="url">URL</option>
                            <option value="json">JSON</option>
                            <option value="array">Array (comma-separated)</option>
                        </select>
                    </div>
                </div>
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                    <div>
                        <label style="display: block; font-size: 0.85rem; color: #666; margin-bottom: 5px; font-weight: 600;">Group <span style="color: #e53e3e;">*</span></label>
                        <select name="group" id="settingGroup" class="form-control" required onchange="toggleCustomGroup()" style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.9rem;">
                            <?php foreach ($groups as $groupKey => $groupName): ?>
                            <option value="<?php echo $groupKey; ?>"><?php echo htmlspecialchars($groupName); ?></option>
                            <?php endforeach; ?>
                            <option value="custom">+ Custom Group...</option>
                        </select>
                    </div>
                    
                    <div id="customGroupField" style="display: none;">
                        <label style="display: block; font-size: 0.85rem; color: #666; margin-bottom: 5px; font-weight: 600;">Custom Group Name</label>
                        <input type="text" name="custom_group" class="form-control" placeholder="e.g., payment_gateway" style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.9rem;">
                    </div>
                    
                    <div>
                        <label style="display: block; font-size: 0.85rem; color: #666; margin-bottom: 5px; font-weight: 600;">&nbsp;</label>
                        <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                            <input type="checkbox" name="is_encrypted" id="isEncrypted" value="1" style="width: 16px; height: 16px;">
                            <span style="font-size: 0.9rem;">Encrypt this value</span>
                        </label>
                        <small style="display: block; margin-top: 3px; font-size: 0.7rem; color: #999;">For sensitive data like API keys</small>
                    </div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="display: block; font-size: 0.85rem; color: #666; margin-bottom: 5px; font-weight: 600;">Description</label>
                    <textarea name="description" class="form-control" rows="2" placeholder="What is this setting used for?" style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.9rem;"></textarea>
                </div>
                
                <div>
                    <label style="display: block; font-size: 0.85rem; color: #666; margin-bottom: 5px; font-weight: 600;">Value <span style="color: #e53e3e;">*</span></label>
                    <div id="valueInputs">
                        <input type="text" name="value" class="form-control" placeholder="Setting value" style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.9rem;">
                    </div>
                </div>
            </div>
            
            <div class="modal-footer" style="padding: 15px 20px; border-top: 1px solid #ddd; display: flex; justify-content: flex-end; gap: 10px;">
                <button type="button" class="btn btn-outline" onclick="closeModal('addModal')" style="background: transparent; border: 1px solid #ddd; color: #666; padding: 8px 16px; border-radius: 4px; cursor: pointer;">Cancel</button>
                <button type="submit" class="btn btn-success" style="background: #27ae60; color: white; padding: 8px 16px; border-radius: 4px; border: none; cursor: pointer;">Add Setting</button>
            </div>
        </form>
    </div>
</div>

<!-- Import Modal -->
<div class="modal" id="importModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; align-items: center; justify-content: center;">
    <div class="modal-content" style="background: white; border-radius: 8px; width: 90%; max-width: 500px;">
        <div class="modal-header" style="padding: 15px 20px; border-bottom: 1px solid #ddd; display: flex; justify-content: space-between; align-items: center;">
            <h3 style="margin: 0; font-size: 1.2rem; color: #2c3e50;"><i class="fas fa-upload" style="color: #27ae60;"></i> Import Settings</h3>
            <button class="modal-close" onclick="closeModal('importModal')" style="background: transparent; border: none; font-size: 1.5rem; cursor: pointer; color: #666;">&times;</button>
        </div>
        <form id="importForm" enctype="multipart/form-data" onsubmit="importSettings(event)">
            <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
            
            <div class="modal-body" style="padding: 20px;">
                <p style="color: #666; margin-bottom: 15px;">Upload a JSON file exported from the system.</p>
                
                <div style="margin-bottom: 15px;">
                    <label style="display: block; font-size: 0.85rem; color: #666; margin-bottom: 5px; font-weight: 600;">JSON File <span style="color: #e53e3e;">*</span></label>
                    <input type="file" name="import_file" accept=".json,application/json" required style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                
                <div style="background: #fff3cd; color: #856404; padding: 12px 15px; border-radius: 4px; border-left: 4px solid #ffc107; display: flex; align-items: center; gap: 8px;">
                    <i class="fas fa-exclamation-triangle"></i>
                    <strong>Warning:</strong> Importing will overwrite existing settings with matching keys.
                </div>
            </div>
            
            <div class="modal-footer" style="padding: 15px 20px; border-top: 1px solid #ddd; display: flex; justify-content: flex-end; gap: 10px;">
                <button type="button" class="btn btn-outline" onclick="closeModal('importModal')" style="background: transparent; border: 1px solid #ddd; color: #666; padding: 8px 16px; border-radius: 4px; cursor: pointer;">Cancel</button>
                <button type="submit" class="btn btn-success" style="background: #27ae60; color: white; padding: 8px 16px; border-radius: 4px; border: none; cursor: pointer;">Import</button>
            </div>
        </form>
    </div>
</div>

<style>
/* Hover effects for action buttons - matching users page */
.btn-icon:hover {
    background: #f0f0f0;
    color: #27ae60;
}

.btn-icon.delete:hover {
    background: #ffebee;
    color: #e53e3e;
}

/* Filter section styles - matching users page */
.filter-header.active i {
    transform: rotate(180deg);
}

/* Tab button styles */
.tab-btn:hover {
    background: #27ae60 !important;
    color: white !important;
    border-color: #27ae60 !important;
}

/* Modal close button hover */
.modal-close:hover {
    color: #e53e3e;
}

/* Responsive design - matching users page */
@media (max-width: 768px) {
    .header-actions {
        flex-direction: column;
        gap: 10px;
    }
    
    .header-actions .btn,
    .header-actions .btn-success {
        width: 100%;
        justify-content: center;
    }
    
    .filter-body > div:first-child {
        grid-template-columns: 1fr !important;
    }
    
    .modal-content {
        width: 95%;
        margin: 10px;
    }
}

/* Table row hover effect - matching users page */
.asset-table tbody tr:hover {
    background: #f5f5f5;
}

/* Badge styles */
.badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 0.75rem;
    font-weight: 600;
}

/* Form control focus */
.form-control:focus {
    outline: none;
    border-color: #27ae60 !important;
    box-shadow: 0 0 0 3px rgba(39, 174, 96, 0.1);
}

/* Code style */
code {
    font-family: 'Courier New', monospace;
}
</style>

<script>
// Global variables
let csrfToken = '<?php echo $csrfToken; ?>';

// Tab functions
function toggleTabs() {
    const body = document.getElementById('tabBody');
    const header = document.querySelector('.filter-header');
    const chevron = document.getElementById('tabChevron');
    
    if (body.style.display === 'none' || body.style.display === '') {
        body.style.display = 'block';
        header.classList.add('active');
        if (chevron) chevron.style.transform = 'rotate(180deg)';
    } else {
        body.style.display = 'none';
        header.classList.remove('active');
        if (chevron) chevron.style.transform = '';
    }
}

function showGroup(groupKey, btn) {
    // Hide all groups
    document.querySelectorAll('.settings-group').forEach(group => {
        group.style.display = 'none';
    });
    
    // Show selected group
    document.getElementById('group-' + groupKey).style.display = 'block';
    
    // Update tab button styles
    document.querySelectorAll('.tab-btn').forEach(tab => {
        tab.style.background = 'white';
        tab.style.color = '#666';
        tab.style.borderColor = '#ddd';
    });
    
    btn.style.background = '#27ae60';
    btn.style.color = 'white';
    btn.style.borderColor = '#27ae60';
}

// Export settings
function exportSettings() {
    window.location.href = '<?php echo BASE_URL; ?>/settings/export';
}

// Modal functions
function showAddModal() {
    document.getElementById('addModal').style.display = 'flex';
}

function showImportModal() {
    document.getElementById('importModal').style.display = 'flex';
}

function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

// Toggle custom group field
function toggleCustomGroup() {
    const groupSelect = document.getElementById('settingGroup');
    const customField = document.getElementById('customGroupField');
    
    if (groupSelect.value === 'custom') {
        customField.style.display = 'block';
    } else {
        customField.style.display = 'none';
    }
}

// Toggle encrypted checkbox
function toggleEncrypted() {
    const type = document.getElementById('settingType')?.value;
    const encryptedCheckbox = document.getElementById('isEncrypted');
    if (!encryptedCheckbox) return;
    
    const sensitiveTypes = ['string', 'text', 'email', 'url'];
    if (!sensitiveTypes.includes(type)) {
        encryptedCheckbox.checked = false;
        encryptedCheckbox.disabled = true;
    } else {
        encryptedCheckbox.disabled = false;
    }
}

// Add new setting
async function addSetting(event) {
    event.preventDefault();
    
    const form = document.getElementById('addSettingForm');
    const formData = new FormData(form);
    
    // Handle custom group
    if (formData.get('group') === 'custom') {
        const customGroup = formData.get('custom_group');
        if (!customGroup) {
            alert('Please enter a custom group name');
            return;
        }
        formData.set('group', customGroup);
    }
    
    const submitBtn = event.submitter;
    submitBtn.classList.add('btn-loading');
    submitBtn.disabled = true;
    
    try {
        const response = await fetch('<?php echo BASE_URL; ?>/settings/add', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('Setting added successfully');
            closeModal('addModal');
            setTimeout(() => location.reload(), 1000);
        } else {
            alert(result.message || 'Failed to add setting');
        }
    } catch (error) {
        alert('Network error. Please try again.');
        console.error('Add setting error:', error);
    } finally {
        submitBtn.classList.remove('btn-loading');
        submitBtn.disabled = false;
    }
}

// Delete setting
async function deleteSetting(key) {
    if (!confirm('Are you sure you want to delete this setting? This action cannot be undone.')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('key', key);
    formData.append('csrf_token', csrfToken);
    
    try {
        const response = await fetch('<?php echo BASE_URL; ?>/settings/delete', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('Setting deleted successfully');
            setTimeout(() => location.reload(), 1000);
        } else {
            alert(result.message || 'Failed to delete setting');
        }
    } catch (error) {
        alert('Network error. Please try again.');
        console.error('Delete setting error:', error);
    }
}

// Import settings
async function importSettings(event) {
    event.preventDefault();
    
    const form = document.getElementById('importForm');
    const formData = new FormData(form);
    
    const submitBtn = event.submitter;
    submitBtn.classList.add('btn-loading');
    submitBtn.disabled = true;
    
    try {
        const response = await fetch('<?php echo BASE_URL; ?>/settings/import', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('Settings imported successfully');
            closeModal('importModal');
            setTimeout(() => location.reload(), 1000);
        } else {
            alert(result.message || 'Failed to import settings');
        }
    } catch (error) {
        alert('Network error. Please try again.');
        console.error('Import error:', error);
    } finally {
        submitBtn.classList.remove('btn-loading');
        submitBtn.disabled = false;
    }
}

// Edit setting
function editSetting(id) {
    const setting = document.querySelector(`#setting-${id}`);
    if (!setting) return;
    
    const input = setting.querySelector('input[type="text"], input[type="number"], input[type="email"], input[type="url"], select, textarea');
    if (input) {
        input.focus();
        input.select();
    }
}

// Reset form
function resetForm() {
    if (confirm('Reset all unsaved changes?')) {
        location.reload();
    }
}

// Form submission
document.getElementById('settingsForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const submitBtn = document.getElementById('saveSettings');
    submitBtn.classList.add('btn-loading');
    submitBtn.disabled = true;
    
    const formData = new FormData(this);
    
    try {
        const response = await fetch(this.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('Settings saved successfully');
        } else {
            alert(result.message || 'Failed to save settings');
        }
    } catch (error) {
        alert('Network error. Please try again.');
        console.error('Settings save error:', error);
    } finally {
        submitBtn.classList.remove('btn-loading');
        submitBtn.disabled = false;
    }
});

// Close modals when clicking outside
window.addEventListener('click', function(event) {
    if (event.target.classList.contains('modal')) {
        event.target.style.display = 'none';
    }
});

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    toggleEncrypted();
    
    // Set initial tab state for mobile
    if (window.innerWidth <= 768) {
        document.getElementById('tabBody').style.display = 'none';
    } else {
        document.getElementById('tabBody').style.display = 'block';
        document.querySelector('.filter-header').classList.add('active');
    }
});
</script>

<!-- Helper function for group icons -->
<?php
function getGroupIcon($group) {
    $icons = [
        'general' => 'cog',
        'security' => 'shield-alt',
        'email' => 'envelope',
        'notification' => 'bell',
        'payment' => 'credit-card',
        'api' => 'plug',
        'backup' => 'database',
        'maintenance' => 'tools',
        'customization' => 'palette',
        'integration' => 'link'
    ];
    
    return $icons[$group] ?? 'cog';
}

function renderSettingInput($setting) {
    $key = $setting['setting_key'];
    $value = $setting['setting_value'];
    $type = $setting['data_type'];
    $name = "settings[{$key}]";
    
    if ($type === 'boolean' || $type === 'bool') {
        $checked = $value ? 'checked' : '';
        return '
            <div style="display: flex; align-items: center; gap: 10px;">
                <label style="display: flex; align-items: center; gap: 5px; cursor: pointer;">
                    <input type="checkbox" name="' . $name . '" value="1" ' . $checked . '>
                    <span style="font-size: 0.9rem;">Enabled</span>
                </label>
                <input type="hidden" name="' . $name . '" value="0">
            </div>';
    }
    
    if ($type === 'text' || $type === 'textarea') {
        return '<textarea name="' . $name . '" class="form-control" rows="2" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">' . htmlspecialchars($value) . '</textarea>';
    }
    
    if ($type === 'email') {
        return '<input type="email" name="' . $name . '" class="form-control" value="' . htmlspecialchars($value) . '" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">';
    }
    
    if ($type === 'url') {
        return '<input type="url" name="' . $name . '" class="form-control" value="' . htmlspecialchars($value) . '" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">';
    }
    
    if ($type === 'number' || $type === 'integer' || $type === 'float') {
        return '<input type="number" name="' . $name . '" class="form-control" value="' . htmlspecialchars($value) . '" step="any" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">';
    }
    
    if ($type === 'json') {
        $displayValue = is_array($value) ? json_encode($value, JSON_PRETTY_PRINT) : $value;
        return '<textarea name="' . $name . '" class="form-control" rows="2" placeholder="{}" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-family: monospace;">' . htmlspecialchars($displayValue) . '</textarea>';
    }
    
    if ($type === 'array') {
        $displayValue = is_array($value) ? implode(',', $value) : $value;
        return '<input type="text" name="' . $name . '" class="form-control" value="' . htmlspecialchars($displayValue) . '" placeholder="comma,separated,values" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">';
    }
    
    return '<input type="text" name="' . $name . '" class="form-control" value="' . htmlspecialchars($value) . '" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">';
}
?>

<?php
require_once __DIR__ . '/../layouts/footer.php';
?>