{% extends "base.html" %}

{% block title %}System Settings - Admin{% endblock %}

{% block extra_css %}
<!-- Bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-cogs"></i> System Settings</h2>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="{{ url_for('main.dashboard') }}">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="{{ url_for('main.admin_panel') }}">Admin</a></li>
                        <li class="breadcrumb-item active">System Settings</li>
                    </ol>
                </nav>
            </div>

            <!-- Quick Settings Cards -->
            <div class="row mb-4">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-user-plus"></i> Registration Settings
                            </h5>
                        </div>
                        <div class="card-body">
                            <p class="card-text">Control user registration availability</p>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="registrationToggle"
                                       {% if settings.get('registration_enabled') == True or settings.get('registration_enabled') == 'true' %}checked{% endif %}
                                       onchange="toggleRegistration(this.checked)">
                                <label class="form-check-label" for="registrationToggle">
                                    Enable User Registration
                                </label>
                            </div>
                            <small class="text-muted">
                                Current status:
                                <span class="badge {% if settings.get('registration_enabled') == True or settings.get('registration_enabled') == 'true' %}bg-success{% else %}bg-danger{% endif %}">
                                    {% if settings.get('registration_enabled') == True or settings.get('registration_enabled') == 'true' %}Enabled{% else %}Disabled{% endif %}
                                </span>
                            </small>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-wrench"></i> Maintenance Mode
                            </h5>
                        </div>
                        <div class="card-body">
                            <p class="card-text">Enable maintenance mode for system updates</p>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="maintenanceToggle"
                                       {% if settings.get('maintenance_mode') == True or settings.get('maintenance_mode') == 'true' %}checked{% endif %}
                                       onchange="toggleMaintenance(this.checked)">
                                <label class="form-check-label" for="maintenanceToggle">
                                    Enable Maintenance Mode
                                </label>
                            </div>
                            <small class="text-muted">
                                Current status:
                                <span class="badge {% if settings.get('maintenance_mode') == True or settings.get('maintenance_mode') == 'true' %}bg-warning{% else %}bg-success{% endif %}">
                                    {% if settings.get('maintenance_mode') == True or settings.get('maintenance_mode') == 'true' %}Maintenance{% else %}Active{% endif %}
                                </span>
                            </small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- All Settings Table -->
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">
                        <i class="fas fa-list"></i> All System Settings
                    </h5>
                    <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addSettingModal">
                        <i class="fas fa-plus"></i> Add Setting
                    </button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Setting Key</th>
                                    <th>Value</th>
                                    <th>Type</th>
                                    <th>Description</th>
                                    <th>Last Updated</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for key, value in settings.items() %}
                                <tr>
                                    <td><code>{{ key }}</code></td>
                                    <td>
                                        {% if key in ['registration_enabled', 'maintenance_mode'] %}
                                            <span class="badge {% if value == True or value == 'true' %}bg-success{% else %}bg-danger{% endif %}">
                                                {{ value }}
                                            </span>
                                        {% else %}
                                            {{ value }}
                                        {% endif %}
                                    </td>
                                    <td>
                                        <span class="badge bg-secondary">
                                            {% if key in ['registration_enabled', 'maintenance_mode'] %}boolean{% else %}string{% endif %}
                                        </span>
                                    </td>
                                    <td>
                                        {% if key == 'registration_enabled' %}
                                            Enable or disable user registration
                                        {% elif key == 'maintenance_mode' %}
                                            Enable maintenance mode for system updates
                                        {% elif key == 'app_name' %}
                                            Application name displayed in UI
                                        {% else %}
                                            Custom setting
                                        {% endif %}
                                    </td>
                                    <td>
                                        <small class="text-muted">Recently</small>
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <button type="button" class="btn btn-outline-primary"
                                                    onclick="editSetting('{{ key }}', '{{ value }}')"
                                                    title="Edit Setting">
                                                <i class="fas fa-edit"></i> Edit
                                            </button>
                                            {% if key not in ['registration_enabled', 'maintenance_mode', 'app_name'] %}
                                            <button type="button" class="btn btn-outline-danger"
                                                    onclick="deleteSetting('{{ key }}')"
                                                    title="Delete Setting">
                                                <i class="fas fa-trash"></i> Delete
                                            </button>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Setting Modal -->
<div class="modal fade" id="addSettingModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Setting</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addSettingForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="settingKey" class="form-label">Setting Key</label>
                        <input type="text" class="form-control" id="settingKey" required>
                        <div class="form-text">Use lowercase with underscores (e.g., max_upload_size)</div>
                    </div>
                    <div class="mb-3">
                        <label for="settingValue" class="form-label">Value</label>
                        <input type="text" class="form-control" id="settingValue" required>
                    </div>
                    <div class="mb-3">
                        <label for="settingType" class="form-label">Type</label>
                        <select class="form-select" id="settingType">
                            <option value="string">String</option>
                            <option value="boolean">Boolean</option>
                            <option value="integer">Integer</option>
                            <option value="float">Float</option>
                            <option value="json">JSON</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="settingDescription" class="form-label">Description</label>
                        <textarea class="form-control" id="settingDescription" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Setting</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Setting Modal -->
<div class="modal fade" id="editSettingModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Setting</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editSettingForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="editSettingKey" class="form-label">Setting Key</label>
                        <input type="text" class="form-control" id="editSettingKey" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="editSettingValue" class="form-label">Value</label>
                        <input type="text" class="form-control" id="editSettingValue" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Setting</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Toggle registration setting
function toggleRegistration(enabled) {
    fetch('/admin/settings/registration', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            registration_enabled: enabled
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error updating registration setting: ' + data.message);
            // Revert toggle
            document.getElementById('registrationToggle').checked = !enabled;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error updating registration setting');
        // Revert toggle
        document.getElementById('registrationToggle').checked = !enabled;
    });
}

// Toggle maintenance mode
function toggleMaintenance(enabled) {
    fetch('/admin/settings/maintenance_mode', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            value: enabled ? 'true' : 'false'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error updating maintenance mode: ' + data.message);
            // Revert toggle
            document.getElementById('maintenanceToggle').checked = !enabled;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error updating maintenance mode');
        // Revert toggle
        document.getElementById('maintenanceToggle').checked = !enabled;
    });
}

// Edit setting
function editSetting(key, value) {
    document.getElementById('editSettingKey').value = key;
    document.getElementById('editSettingValue').value = value;
    new bootstrap.Modal(document.getElementById('editSettingModal')).show();
}

// Delete setting
function deleteSetting(key) {
    if (confirm('Are you sure you want to delete the setting "' + key + '"?')) {
        fetch('/admin/settings/' + key, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert('Error deleting setting: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error deleting setting');
        });
    }
}

// Add setting form handler
document.getElementById('addSettingForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const key = document.getElementById('settingKey').value;
    const value = document.getElementById('settingValue').value;
    const type = document.getElementById('settingType').value;
    const description = document.getElementById('settingDescription').value;
    
    fetch('/admin/settings/' + key, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            value: value,
            type: type,
            description: description
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error adding setting: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error adding setting');
    });
});

// Edit setting form handler
document.getElementById('editSettingForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const key = document.getElementById('editSettingKey').value;
    const value = document.getElementById('editSettingValue').value;
    
    fetch('/admin/settings/' + key, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            value: value
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error updating setting: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error updating setting');
    });
});
</script>
{% endblock %}

{% block extra_js %}
<!-- Bootstrap 5 JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
{% endblock %}