<x-layout.universal>
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="page-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h1 class="page-title">
                                <i class="fas fa-bug text-danger me-3"></i>
                                Sistema Debug NetGescon
                            </h1>
                            <p class="text-muted mb-0">Pannello di controllo per debug, pulizia duplicati e monitoraggio sistema</p>
                        </div>
                        <div class="d-flex gap-2">
                            <button id="refreshStatus" class="btn btn-outline-primary">
                                <i class="fas fa-sync-alt me-2"></i>Aggiorna Status
                            </button>
                            <button id="fullScan" class="btn btn-primary">
                                <i class="fas fa-search me-2"></i>Scansione Completa
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Status Cards -->
                <div class="row mb-4">
                    <div class="col-lg-3 col-md-6 mb-3">
                        <div class="card border-info h-100">
                            <div class="card-body text-center">
                                <div class="display-4 text-info">
                                    <i class="fas fa-server"></i>
                                </div>
                                <h5 class="card-title">Sistema</h5>
                                <p class="card-text">
                                    <small class="text-muted">
                                        PHP {{ $systemStatus['php_version'] }}<br>
                                        Laravel {{ $systemStatus['laravel_version'] }}<br>
                                        {{ ucfirst($systemStatus['environment']) }}
                                    </small>
                                </p>
                                <span class="badge {{ $systemStatus['debug_mode'] ? 'bg-warning' : 'bg-success' }}">
                                    {{ $systemStatus['debug_mode'] ? 'Debug ON' : 'Production' }}
                                </span>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-3 col-md-6 mb-3">
                        <div class="card border-warning h-100">
                            <div class="card-body text-center">
                                <div class="display-4 text-warning">
                                    <i class="fas fa-copy"></i>
                                </div>
                                <h5 class="card-title">File Duplicati</h5>
                                <p class="card-text">
                                    <span class="fs-3 fw-bold">{{ $systemStatus['duplicates_folder_size'] }}</span><br>
                                    <small class="text-muted">in _DUPLICATES_MOVED/</small>
                                </p>
                                <button class="btn btn-sm btn-warning" id="scanDuplicates">
                                    <i class="fas fa-search me-1"></i>Scansiona
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-3 col-md-6 mb-3">
                        <div class="card border-success h-100">
                            <div class="card-body text-center">
                                <div class="display-4 text-success">
                                    <i class="fas fa-file-code"></i>
                                </div>
                                <h5 class="card-title">View & Route</h5>
                                <p class="card-text">
                                    <span class="fs-4 fw-bold">{{ $systemStatus['views_count'] }}</span> View<br>
                                    <span class="fs-4 fw-bold">{{ $systemStatus['routes_count'] }}</span> Route
                                </p>
                                <button class="btn btn-sm btn-success" id="verifyRoutes">
                                    <i class="fas fa-check me-1"></i>Verifica
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-3 col-md-6 mb-3">
                        <div class="card border-primary h-100">
                            <div class="card-body text-center">
                                <div class="display-4 text-primary">
                                    <i class="fas fa-database"></i>
                                </div>
                                <h5 class="card-title">Model & Controller</h5>
                                <p class="card-text">
                                    <span class="fs-4 fw-bold">{{ $systemStatus['models_count'] }}</span> Model<br>
                                    <span class="fs-4 fw-bold">{{ $systemStatus['controllers_count'] }}</span> Controller
                                </p>
                                <button class="btn btn-sm btn-primary" id="checkModels">
                                    <i class="fas fa-link me-1"></i>Controlla
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Action Panel -->
                <div class="row">
                    <div class="col-lg-8 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">
                                    <i class="fas fa-tools me-2"></i>Azioni di Debug
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <button class="btn btn-outline-warning w-100" id="scanDuplicatesAction">
                                            <i class="fas fa-search me-2"></i>
                                            Scansiona Duplicati
                                        </button>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <button class="btn btn-warning w-100" id="cleanDuplicatesAction">
                                            <i class="fas fa-broom me-2"></i>
                                            Pulisci Duplicati
                                        </button>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <button class="btn btn-outline-success w-100" id="verifyRoutesAction">
                                            <i class="fas fa-route me-2"></i>
                                            Verifica Route/View
                                        </button>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <button class="btn btn-outline-primary w-100" id="checkModelsAction">
                                            <i class="fas fa-project-diagram me-2"></i>
                                            Controlla Relationship
                                        </button>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <button class="btn btn-outline-info w-100" id="generateReportAction">
                                            <i class="fas fa-file-alt me-2"></i>
                                            Genera Report
                                        </button>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <button class="btn btn-primary w-100" id="fullScanAction">
                                            <i class="fas fa-search-plus me-2"></i>
                                            Scansione Completa
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-4 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">
                                    <i class="fas fa-info-circle me-2"></i>Info Sistema
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="list-group list-group-flush">
                                    <div class="list-group-item d-flex justify-content-between">
                                        <span>Storage Scrivibile</span>
                                        <span class="badge {{ $systemStatus['storage_writable'] ? 'bg-success' : 'bg-danger' }}">
                                            {{ $systemStatus['storage_writable'] ? 'SI' : 'NO' }}
                                        </span>
                                    </div>
                                    <div class="list-group-item d-flex justify-content-between">
                                        <span>Ultimo Scan</span>
                                        <span class="text-muted small">{{ $systemStatus['last_debug_scan'] }}</span>
                                    </div>
                                    <div class="list-group-item d-flex justify-content-between">
                                        <span>Ambiente</span>
                                        <span class="badge bg-secondary">{{ ucfirst($systemStatus['environment']) }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Output Console -->
                <div class="row">
                    <div class="col-12">
                        <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-terminal me-2"></i>Output Console
                                </h5>
                                <button class="btn btn-sm btn-outline-secondary" id="clearConsole">
                                    <i class="fas fa-trash me-1"></i>Pulisci
                                </button>
                            </div>
                            <div class="card-body p-0">
                                <div id="debugOutput" class="bg-dark text-light p-3" style="height: 300px; overflow-y: auto; font-family: 'Courier New', monospace; font-size: 14px;">
                                    <div class="text-success">🚀 NetGescon Debug Console pronto...</div>
                                    <div class="text-info">💡 Clicca su un'azione per iniziare il debug</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Loading Modal -->
    <div class="modal fade" id="loadingModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-body text-center py-4">
                    <div class="spinner-border text-primary mb-3" role="status"></div>
                    <h5 id="loadingText">Elaborazione in corso...</h5>
                    <p class="text-muted mb-0">Attendere prego</p>
                </div>
            </div>
        </div>
    </div>

    <style>
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            margin: -20px -20px 20px -20px;
            padding: 30px 20px;
            border-radius: 0 0 10px 10px;
        }
        
        .card {
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border: none;
            transition: transform 0.2s;
        }
        
        .card:hover {
            transform: translateY(-2px);
        }
        
        #debugOutput {
            background: linear-gradient(135deg, #1a1a1a, #2d2d2d);
        }
        
        .console-success { color: #28a745; }
        .console-warning { color: #ffc107; }
        .console-error { color: #dc3545; }
        .console-info { color: #17a2b8; }
    </style>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const debugOutput = document.getElementById('debugOutput');
            const loadingModal = new bootstrap.Modal(document.getElementById('loadingModal'));
            
            function addToConsole(message, type = 'info') {
                const timestamp = new Date().toLocaleTimeString();
                const colorClass = `console-${type}`;
                const icon = {
                    'success': '✅',
                    'error': '❌',
                    'warning': '⚠️',
                    'info': 'ℹ️'
                }[type] || 'ℹ️';
                
                debugOutput.innerHTML += `<div class="${colorClass}">[${timestamp}] ${icon} ${message}</div>`;
                debugOutput.scrollTop = debugOutput.scrollHeight;
            }
            
            function executeAction(url, actionName) {
                document.getElementById('loadingText').textContent = `Esecuzione ${actionName}...`;
                loadingModal.show();
                addToConsole(`Iniziando ${actionName}...`, 'info');
                
                fetch(url, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    loadingModal.hide();
                    if (data.success) {
                        addToConsole(data.message, 'success');
                        if (data.output) {
                            const lines = data.output.split('\n');
                            lines.forEach(line => {
                                if (line.trim()) {
                                    if (line.includes('⚠️') || line.includes('Trovate') || line.includes('Trovati')) {
                                        addToConsole(line.trim(), 'warning');
                                    } else if (line.includes('❌') || line.includes('Errore')) {
                                        addToConsole(line.trim(), 'error');
                                    } else if (line.includes('✅') || line.includes('completata')) {
                                        addToConsole(line.trim(), 'success');
                                    } else {
                                        addToConsole(line.trim(), 'info');
                                    }
                                }
                            });
                        }
                    } else {
                        addToConsole(`Errore: ${data.message}`, 'error');
                    }
                })
                .catch(error => {
                    loadingModal.hide();
                    addToConsole(`Errore di rete: ${error.message}`, 'error');
                });
            }
            
            // Event Listeners
            document.getElementById('scanDuplicatesAction').addEventListener('click', () => {
                executeAction('{{ route("admin.debug.scan-duplicates") }}', 'Scansione Duplicati');
            });
            
            document.getElementById('cleanDuplicatesAction').addEventListener('click', () => {
                if (confirm('Sei sicuro di voler pulire i file duplicati?')) {
                    executeAction('{{ route("admin.debug.clean-duplicates") }}', 'Pulizia Duplicati');
                }
            });
            
            document.getElementById('verifyRoutesAction').addEventListener('click', () => {
                executeAction('{{ route("admin.debug.verify-routes") }}', 'Verifica Route');
            });
            
            document.getElementById('checkModelsAction').addEventListener('click', () => {
                executeAction('{{ route("admin.debug.check-models") }}', 'Controllo Model');
            });
            
            document.getElementById('generateReportAction').addEventListener('click', () => {
                executeAction('{{ route("admin.debug.generate-report") }}', 'Generazione Report');
            });
            
            document.getElementById('fullScanAction').addEventListener('click', () => {
                executeAction('{{ route("admin.debug.full-scan") }}', 'Scansione Completa');
            });
            
            document.getElementById('clearConsole').addEventListener('click', () => {
                debugOutput.innerHTML = '<div class="text-success">🚀 Console pulita...</div>';
            });
            
            document.getElementById('refreshStatus').addEventListener('click', () => {
                window.location.reload();
            });
            
            // Quick buttons
            document.getElementById('scanDuplicates').addEventListener('click', () => {
                executeAction('{{ route("admin.debug.scan-duplicates") }}', 'Scansione Duplicati');
            });
            
            document.getElementById('verifyRoutes').addEventListener('click', () => {
                executeAction('{{ route("admin.debug.verify-routes") }}', 'Verifica Route');
            });
            
            document.getElementById('checkModels').addEventListener('click', () => {
                executeAction('{{ route("admin.debug.check-models") }}', 'Controllo Model');
            });
            
            document.getElementById('fullScan').addEventListener('click', () => {
                executeAction('{{ route("admin.debug.full-scan") }}', 'Scansione Completa');
            });
        });
    </script>
</x-layout.universal>
