@extends('layouts.admin')

@section('title', 'Configuration Management')

@section('content')
<div class="container-fluid py-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-md-8">
            <h1 class="h3 mb-0">System Configuration</h1>
            <p class="text-muted">Manage system settings with versioning and rollback support</p>
        </div>
        <div class="col-md-4 text-end">
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#snapshotModal">
                <i class="fas fa-camera"></i> Create Snapshot
            </button>
            <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#versionsModal">
                <i class="fas fa-history"></i> Versions
            </button>
        </div>
    </div>

    <!-- Current Version Info -->
    @if($currentVersion)
    <div class="alert alert-info">
        <strong>Current Version:</strong> {{ $currentVersion->version_name }}
        <br>
        <small class="text-muted">Created by: {{ $currentVersion->creator->name ?? 'System' }} on {{ $currentVersion->created_at->format('M d, Y H:i') }}</small>
    </div>
    @endif

    <!-- Configuration Groups -->
    @foreach($configurations as $group => $configs)
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0">{{ $groups[$group] ?? ucfirst($group) }}</h5>
        </div>
        <div class="card-body">
            <form id="config-form-{{ $group }}" class="configuration-form">
                @csrf
                <div class="row">
                    @foreach($configs as $config)
                    <div class="col-md-6 mb-3">
                        <label class="form-label">
                            {{ $config->description ?? ucfirst(str_replace('_', ' ', $config->key)) }}
                        </label>

                        @if($config->type === 'boolean')
                            <div class="form-check form-switch">
                                <input class="form-check-input config-input" type="checkbox"
                                    name="configurations[{{ $config->key }}]"
                                    value="true"
                                    {{ $config->value === 'true' ? 'checked' : '' }}
                                    data-key="{{ $config->key }}">
                                <label class="form-check-label" for="config-{{ $config->key }}">
                                    {{ $config->value === 'true' ? 'Enabled' : 'Disabled' }}
                                </label>
                            </div>

                        @elseif($config->type === 'select' && $config->options)
                            <select class="form-select form-select-sm config-input"
                                name="configurations[{{ $config->key }}]"
                                data-key="{{ $config->key }}">
                                @php
                                    $options = is_array($config->options)
                                        ? $config->options
                                        : (is_string($config->options) ? json_decode($config->options, true) : []);
                                @endphp
                                @foreach($options as $option)
                                    <option value="{{ $option }}" {{ $config->value === $option ? 'selected' : '' }}>
                                        {{ ucfirst($option) }}
                                    </option>
                                @endforeach
                            </select>

                        @elseif($config->type === 'json')
                            <textarea class="form-control form-control-sm config-input"
                                name="configurations[{{ $config->key }}]"
                                rows="3"
                                data-key="{{ $config->key }}"
                                data-json="true">{{ is_array($config->value) ? json_encode($config->value, JSON_PRETTY_PRINT) : $config->value }}</textarea>

                        @else
                            <input type="text" class="form-control form-control-sm config-input"
                                name="configurations[{{ $config->key }}]"
                                value="{{ $config->value }}"
                                data-key="{{ $config->key }}">
                        @endif

                        @if($config->description)
                            <small class="text-muted d-block mt-1">{{ $config->description }}</small>
                        @endif
                    </div>
                    @endforeach
                </div>

                <div class="mt-3">
                    <button type="submit" class="btn btn-primary btn-sm">
                        <i class="fas fa-save"></i> Save Changes
                    </button>
                </div>
            </form>
        </div>
    </div>
    @endforeach
</div>

<!-- Create Snapshot Modal -->
<div class="modal fade" id="snapshotModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Create Configuration Snapshot</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="snapshot-form">
                @csrf
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Snapshot Name</label>
                        <input type="text" class="form-control" name="version_name"
                            placeholder="e.g., Before Payment Integration" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" rows="3"
                            placeholder="What changes is this snapshot protecting against?"></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">
                        <i class="fas fa-save"></i> Create Snapshot
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Versions Modal -->
<div class="modal fade" id="versionsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Configuration Versions</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="versionsList" class="list-group">
                    Loading versions...
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
// Handle configuration form submission
document.querySelectorAll('.configuration-form').forEach(form => {
    form.addEventListener('submit', async (e) => {
        e.preventDefault();

        const configs = {};
        form.querySelectorAll('.config-input').forEach(input => {
            const key = input.getAttribute('data-key');
            const isJson = input.getAttribute('data-json');
            const value = input.type === 'checkbox' ? input.checked : input.value;

            if (isJson && typeof value === 'string') {
                try {
                    configs[key] = JSON.parse(value);
                } catch (e) {
                    configs[key] = value;
                }
            } else {
                configs[key] = value;
            }
        });

        try {
            const response = await fetch('/api/admin/configurations/bulk-update', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ configurations: Object.entries(configs).map(([key, value]) => ({key, value})) })
            });

            const data = await response.json();
            if (data.success) {
                alert('Configuration updated successfully');
                location.reload();
            } else {
                alert('Error: ' + data.message);
            }
        } catch (error) {
            alert('Error updating configuration');
            console.error(error);
        }
    });
});

// Handle snapshot form
document.getElementById('snapshot-form')?.addEventListener('submit', async (e) => {
    e.preventDefault();

    const formData = new FormData(e.target);

    try {
        const response = await fetch('/api/admin/configurations/snapshot', {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: formData
        });

        const data = await response.json();
        if (data.success) {
            alert('Snapshot created successfully');
            bootstrap.Modal.getInstance(document.getElementById('snapshotModal')).hide();
            e.target.reset();
        } else {
            alert('Error: ' + data.message);
        }
    } catch (error) {
        alert('Error creating snapshot');
        console.error(error);
    }
});

// Load versions when modal is shown
document.getElementById('versionsModal')?.addEventListener('show.bs.modal', async () => {
    try {
        const response = await fetch('/api/admin/configurations/versions');
        const data = await response.json();

        const versionsList = document.getElementById('versionsList');
        versionsList.innerHTML = '';

        data.data.data.forEach(version => {
            const element = document.createElement('div');
            element.className = 'list-group-item';
            element.innerHTML = `
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <h6 class="mb-1">${version.version_name}</h6>
                        <small class="text-muted">
                            Created: ${new Date(version.created_at).toLocaleString()}
                        </small>
                        ${version.description ? `<p class="mb-0 mt-1 text-muted">${version.description}</p>` : ''}
                    </div>
                    <div>
                        ${version.is_current ? '<span class="badge bg-success">Current</span>' : ''}
                        <button class="btn btn-sm btn-primary" onclick="restoreVersion(${version.id})">
                            Restore
                        </button>
                    </div>
                </div>
            `;
            versionsList.appendChild(element);
        });
    } catch (error) {
        document.getElementById('versionsList').innerHTML = 'Error loading versions';
        console.error(error);
    }
});

async function restoreVersion(versionId) {
    if (!confirm('Are you sure you want to restore this configuration? This action cannot be undone.')) {
        return;
    }

    try {
        const response = await fetch(`/api/admin/configurations/versions/${versionId}/restore`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ confirm: true })
        });

        const data = await response.json();
        if (data.success) {
            alert(data.message);
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    } catch (error) {
        alert('Error restoring version');
        console.error(error);
    }
}
</script>
@endpush
@endsection

