<?php require 'auth.php'; require_login(); ?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Autocomplete API</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
</head>
<body>
    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fa fa-bug me-2"></i>Debug Autocomplete API</h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <i class="fa fa-info-circle me-2"></i>
                            Test untuk mendiagnosis masalah "terjadi kesalahan data" pada autocomplete nomor perkara.
                        </div>
                        
                        <div class="mb-3">
                            <label for="test_query" class="form-label">Test Query:</label>
                            <input type="text" class="form-control" id="test_query" value="123" placeholder="Masukkan kata kunci pencarian">
                        </div>
                        
                        <div class="d-flex gap-2 mb-3">
                            <button type="button" class="btn btn-primary" onclick="testAPI()">
                                <i class="fa fa-play me-1"></i>Test API
                            </button>
                            <button type="button" class="btn btn-secondary" onclick="clearResults()">
                                <i class="fa fa-times me-1"></i>Clear
                            </button>
                        </div>
                        
                        <div id="loading" class="text-center d-none">
                            <i class="fa fa-spinner fa-spin"></i> Testing API...
                        </div>
                        
                        <div id="results" class="mt-3"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        async function testAPI() {
            const query = document.getElementById('test_query').value;
            const loading = document.getElementById('loading');
            const results = document.getElementById('results');
            
            if (!query) {
                alert('Masukkan kata kunci pencarian');
                return;
            }
            
            loading.classList.remove('d-none');
            results.innerHTML = '';
            
            try {
                console.log('Testing API with query:', query);
                const response = await fetch(`api/search-nomor-perkara.php?q=${encodeURIComponent(query)}`);
                
                console.log('Response status:', response.status);
                console.log('Response headers:', response.headers);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                console.log('Response data:', data);
                
                displayResults(data, response.status);
                
            } catch (error) {
                console.error('API Error:', error);
                displayError(error.message);
            } finally {
                loading.classList.add('d-none');
            }
        }
        
        function displayResults(data, status) {
            const results = document.getElementById('results');
            
            let html = `<div class="alert alert-success">
                <h6><i class="fa fa-check-circle me-2"></i>API Response (Status: ${status})</h6>
            </div>`;
            
            if (Array.isArray(data) && data.length > 0) {
                html += `<div class="alert alert-info">
                    <strong>Found ${data.length} results:</strong>
                </div>`;
                
                html += '<div class="table-responsive"><table class="table table-sm table-bordered">';
                html += '<thead><tr><th>Nomor Perkara</th><th>Nomor Arsip</th><th>Ruang</th><th>Lemari</th><th>Rak</th><th>Berkas</th></tr></thead><tbody>';
                
                data.forEach(item => {
                    html += `<tr>
                        <td><strong>${item.nomor_perkara || '-'}</strong></td>
                        <td>${item.nomor_arsip || '-'}</td>
                        <td>${item.no_ruang || '-'}</td>
                        <td>${item.no_lemari || '-'}</td>
                        <td>${item.no_rak || '-'}</td>
                        <td>${item.no_berkas || '-'}</td>
                    </tr>`;
                });
                
                html += '</tbody></table></div>';
                
            } else if (Array.isArray(data) && data.length === 0) {
                html += '<div class="alert alert-warning">No results found for this query.</div>';
            } else {
                html += '<div class="alert alert-warning">Unexpected response format:</div>';
                html += `<pre>${JSON.stringify(data, null, 2)}</pre>`;
            }
            
            // Show raw JSON
            html += '<div class="mt-3"><h6>Raw JSON Response:</h6>';
            html += `<pre class="bg-light p-2 rounded">${JSON.stringify(data, null, 2)}</pre></div>`;
            
            results.innerHTML = html;
        }
        
        function displayError(message) {
            const results = document.getElementById('results');
            results.innerHTML = `
                <div class="alert alert-danger">
                    <h6><i class="fa fa-exclamation-triangle me-2"></i>API Error</h6>
                    <p><strong>Error:</strong> ${message}</p>
                    <hr>
                    <p><strong>Possible causes:</strong></p>
                    <ul>
                        <li>API endpoint path incorrect</li>
                        <li>Database connection issue</li>
                        <li>Authentication problem</li>
                        <li>Server error</li>
                    </ul>
                </div>
            `;
        }
        
        function clearResults() {
            document.getElementById('results').innerHTML = '';
            document.getElementById('test_query').value = '';
        }
        
        // Test on page load
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Page loaded. Ready to test API.');
        });
    </script>
</body>
</html>
