@extends('layouts.developer')

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

@section('content')
<div class="container mx-auto px-4 py-6" x-data="serverConfig()">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800">Server Configuration & Status</h1>
        <div class="flex space-x-3">
            <button @click="clearCaches()" 
                    :disabled="loading"
                    class="px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition flex items-center disabled:opacity-50">
                <span class="mr-2">🧹</span> Clear All Caches
            </button>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Server Status -->
        <div class="lg:col-span-1 space-y-6">
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
                <div class="p-4 border-b border-gray-100 bg-gray-50">
                    <h2 class="font-semibold text-gray-700">System Information</h2>
                </div>
                <div class="p-4">
                    <dl class="space-y-3">
                        @foreach($serverInfo as $key => $value)
                        <div class="flex justify-between">
                            <dt class="text-sm text-gray-500 uppercase">{{ str_replace('_', ' ', $key) }}</dt>
                            <dd class="text-sm font-medium text-gray-800">{{ $value }}</dd>
                        </div>
                        @endforeach
                    </dl>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
                <h3 class="font-semibold text-gray-700 mb-3 text-sm uppercase">Quick Actions</h3>
                <div class="grid grid-cols-1 gap-2">
                    <button @click="runArtisan('config:cache')" class="text-left px-3 py-2 text-sm bg-gray-50 hover:bg-gray-100 rounded border border-gray-200 transition">Optimize Config</button>
                    <button @click="runArtisan('route:cache')" class="text-left px-3 py-2 text-sm bg-gray-50 hover:bg-gray-100 rounded border border-gray-200 transition">Optimize Routes</button>
                    <button @click="runArtisan('view:cache')" class="text-left px-3 py-2 text-sm bg-gray-50 hover:bg-gray-100 rounded border border-gray-200 transition">Compile Views</button>
                </div>
            </div>
        </div>

        <!-- Environment Editor -->
        <div class="lg:col-span-2">
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
                <div class="p-4 border-b border-gray-100 bg-gray-50 flex justify-between items-center">
                    <h2 class="font-semibold text-gray-700">Environment File (.env)</h2>
                    <button @click="saveEnv()" 
                            :disabled="loading"
                            class="px-4 py-1.5 bg-indigo-600 text-white text-sm rounded hover:bg-indigo-700 transition disabled:opacity-50">
                        <span x-show="!loading">Save Changes</span>
                        <span x-show="loading">Saving...</span>
                    </button>
                </div>
                <div class="p-0">
                    <textarea x-model="envContent" 
                              class="w-full h-[600px] p-4 font-mono text-sm bg-gray-900 text-green-400 focus:outline-none resize-none"
                              spellcheck="false"></textarea>
                </div>
            </div>
        </div>
    </div>

    <!-- Notifications -->
    <template x-if="message">
        <div class="fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg text-white"
             :class="messageType === 'success' ? 'bg-green-600' : 'bg-red-600'"
             x-init="setTimeout(() => message = null, 5000)">
            <p x-text="message"></p>
        </div>
    </template>
</div>

@push('scripts')
<script>
function serverConfig() {
    return {
        envContent: `{!! addslashes($envContent) !!}`,
        loading: false,
        message: null,
        messageType: 'success',

        async saveEnv() {
            if (!confirm('Warning: Changing .env values can break your application. Continue?')) return;
            
            this.loading = true;
            try {
                const response = await fetch('{{ route('developer.server.update-env') }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({ env_content: this.envContent })
                });
                const result = await response.json();
                this.message = result.message;
                this.messageType = result.success ? 'success' : 'error';
            } catch (error) {
                this.message = 'Failed to update environment file.';
                this.messageType = 'error';
            } finally {
                this.loading = false;
            }
        },

        async clearCaches() {
            this.loading = true;
            try {
                const response = await fetch('{{ route('developer.server.clear-cache') }}', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    }
                });
                const result = await response.json();
                this.message = result.message;
                this.messageType = result.success ? 'success' : 'error';
            } catch (error) {
                this.message = 'Failed to clear caches.';
                this.messageType = 'error';
            } finally {
                this.loading = false;
            }
        },

        async runArtisan(command) {
            this.loading = true;
            this.message = `Running php artisan ${command}...`;
            this.messageType = 'success';
            
            try {
                const response = await fetch('{{ route('developer.server.run-command') }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({ command: command })
                });
                
                const result = await response.json();
                this.message = result.message;
                this.messageType = result.success ? 'success' : 'error';
            } catch (error) {
                this.message = `Failed to run command ${command}.`;
                this.messageType = 'error';
            } finally {
                this.loading = false;
            }
        }
    }
}
</script>
@endpush
@endsection
