<?php
// Set page variables for header
$page_title = 'API Error Logs';
$page_description = 'View and analyze API error logs for troubleshooting';

// Get filter parameters
$network = $_GET['network'] ?? '';
$success = $_GET['success'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$page_num = max(1, intval($_GET['page_num'] ?? 1)); // Use 'page_num' instead of 'page' to avoid conflict with routing
$per_page = 20;
$offset = ($page_num - 1) * $per_page;

// Build WHERE clause
$where_conditions = [];
$params = [];
$param_types = '';

if (!empty($network)) {
    $where_conditions[] = "network_type = ?";
    $params[] = $network;
    $param_types .= 's';
}

if ($success !== '') {
    $where_conditions[] = "success = ?";
    $params[] = intval($success);
    $param_types .= 'i';
}

if (!empty($date_from)) {
    $where_conditions[] = "created_at >= ?";
    $params[] = $date_from . ' 00:00:00';
    $param_types .= 's';
}

if (!empty($date_to)) {
    $where_conditions[] = "created_at <= ?";
    $params[] = $date_to . ' 23:59:59';
    $param_types .= 's';
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total count
$count_query = "SELECT COUNT(*) as total FROM api_logs $where_clause";
$count_stmt = $conn->prepare($count_query);
if (!empty($params)) {
    $count_stmt->bind_param($param_types, ...$params);
}
$count_stmt->execute();
$total_count = $count_stmt->get_result()->fetch_assoc()['total'];
$count_stmt->close();

// Get logs
$logs_query = "SELECT * FROM api_logs $where_clause ORDER BY created_at DESC LIMIT ? OFFSET ?";
$logs_stmt = $conn->prepare($logs_query);
$params[] = $per_page;
$params[] = $offset;
$param_types .= 'ii';
$logs_stmt->bind_param($param_types, ...$params);
$logs_stmt->execute();
$logs = $logs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$logs_stmt->close();

// Get network types for filter
$networks_query = "SELECT DISTINCT network_type FROM api_logs ORDER BY network_type";
$networks_result = mysqli_query($conn, $networks_query);
$networks = [];
while ($row = mysqli_fetch_assoc($networks_result)) {
    $networks[] = $row['network_type'];
}

// Calculate pagination
$total_pages = ceil($total_count / $per_page);
?>

<!-- API Error Logs Content -->
<div class="space-y-6">
    <!-- Page Header -->
    <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-2xl p-8 mb-8 border border-slate-600 shadow-2xl">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-4xl font-bold text-white mb-2 flex items-center">
                    <i class="fas fa-bug mr-4 text-red-400"></i>API Error Logs
                </h1>
                <p class="text-slate-300 text-lg">View and analyze API error logs for troubleshooting</p>
            </div>
            <div class="text-right">
                <p class="text-sm text-slate-300">Total Logs</p>
                <p class="text-lg font-semibold text-white"><?= number_format($total_count) ?></p>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl border border-slate-600 shadow-lg">
        <div class="px-6 py-4 border-b border-slate-600">
            <h2 class="text-xl font-bold text-white flex items-center">
                <i class="fas fa-filter mr-3 text-blue-400"></i>Filters
            </h2>
        </div>
        <div class="p-6">
            <form method="GET" class="grid grid-cols-1 md:grid-cols-5 gap-4">
                <input type="hidden" name="page" value="api_error_logs">
                
                <div>
                    <label class="block text-sm font-medium text-slate-300 mb-2">Network</label>
                    <select name="network" class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-slate-200 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                        <option value="">All Networks</option>
                        <?php foreach ($networks as $net): ?>
                        <option value="<?= $net ?>" <?= $network === $net ? 'selected' : '' ?>><?= ucfirst(str_replace('_', ' ', $net)) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-slate-300 mb-2">Status</label>
                    <select name="success" class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-slate-200 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                        <option value="">All Status</option>
                        <option value="1" <?= $success === '1' ? 'selected' : '' ?>>Success</option>
                        <option value="0" <?= $success === '0' ? 'selected' : '' ?>>Failed</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-slate-300 mb-2">From Date</label>
                    <input type="date" name="date_from" value="<?= htmlspecialchars($date_from) ?>" class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-slate-200 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-slate-300 mb-2">To Date</label>
                    <input type="date" name="date_to" value="<?= htmlspecialchars($date_to) ?>" class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-slate-200 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                </div>
                
                <div class="flex items-end space-x-2">
                    <button type="submit" class="flex-1 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white font-medium py-3 px-6 rounded-lg transition-all transform hover:scale-105 shadow-lg flex items-center justify-center">
                        <i class="fas fa-search mr-2"></i>Filter
                    </button>
                    <a href="index.php?page=api_error_logs" class="bg-gradient-to-r from-gray-600 to-gray-700 hover:from-gray-700 hover:to-gray-800 text-white font-medium py-3 px-6 rounded-lg transition-all transform hover:scale-105 shadow-lg text-center flex items-center justify-center">
                        <i class="fas fa-times mr-2"></i>Clear
                    </a>
                </div>
            </form>
        </div>
    </div>

    <!-- Logs Table -->
    <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl border border-slate-600 shadow-lg overflow-hidden">
        <div class="px-6 py-4 border-b border-slate-600">
            <h2 class="text-xl font-bold text-white flex items-center">
                <i class="fas fa-list mr-3 text-green-400"></i>API Logs
                <span class="ml-4 text-sm text-slate-300">(<?= number_format($total_count) ?> total)</span>
            </h2>
        </div>
        
        <?php if (empty($logs)): ?>
        <div class="p-8 text-center text-slate-300">
            <i class="fas fa-search text-5xl mb-4 text-slate-400"></i>
            <p class="text-lg">No API logs found matching the selected filters.</p>
        </div>
        <?php else: ?>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-slate-700/50">
                    <tr>
                        <th class="px-6 py-4 text-left text-xs font-medium text-slate-300 uppercase tracking-wider">Time</th>
                        <th class="px-6 py-4 text-left text-xs font-medium text-slate-300 uppercase tracking-wider">Network</th>
                        <th class="px-6 py-4 text-left text-xs font-medium text-slate-300 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-4 text-left text-xs font-medium text-slate-300 uppercase tracking-wider">HTTP Code</th>
                        <th class="px-6 py-4 text-left text-xs font-medium text-slate-300 uppercase tracking-wider">Error Message</th>
                        <th class="px-6 py-4 text-left text-xs font-medium text-slate-300 uppercase tracking-wider">Response Time</th>
                        <th class="px-6 py-4 text-left text-xs font-medium text-slate-300 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-600">
                    <?php foreach ($logs as $log): ?>
                    <tr class="hover:bg-slate-700/50 transition-colors">
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                            <?= date('M j, Y g:i A', strtotime($log['created_at'])) ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-blue-900/30 text-blue-300 border border-blue-500/30">
                                <?= ucfirst(str_replace('_', ' ', $log['network_type'])) ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <?php if ($log['success']): ?>
                            <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-900/30 text-green-300 border border-green-500/30">
                                <i class="fas fa-check mr-1"></i>Success
                            </span>
                            <?php else: ?>
                            <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-red-900/30 text-red-300 border border-red-500/30">
                                <i class="fas fa-times mr-1"></i>Failed
                            </span>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                            <?php if ($log['response_code']): ?>
                                <?php if ($log['response_code'] >= 200 && $log['response_code'] < 300): ?>
                                    <span class="text-green-400"><?= $log['response_code'] ?></span>
                                <?php elseif ($log['response_code'] >= 400 && $log['response_code'] < 500): ?>
                                    <span class="text-yellow-400"><?= $log['response_code'] ?></span>
                                <?php elseif ($log['response_code'] >= 500): ?>
                                    <span class="text-red-400"><?= $log['response_code'] ?></span>
                                <?php else: ?>
                                    <span class="text-slate-400"><?= $log['response_code'] ?></span>
                                <?php endif; ?>
                            <?php else: ?>
                                <span class="text-slate-500">-</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4 text-sm text-slate-300 max-w-xs truncate">
                            <?php if ($log['error_message']): ?>
                                <span class="text-red-300" title="<?= htmlspecialchars($log['error_message']) ?>">
                                    <?= htmlspecialchars(substr($log['error_message'], 0, 100)) ?>
                                    <?= strlen($log['error_message']) > 100 ? '...' : '' ?>
                                </span>
                            <?php else: ?>
                                <span class="text-slate-500">-</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                            <?= $log['execution_time_ms'] ?>ms
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <button onclick="viewLogDetails(<?= htmlspecialchars(json_encode($log)) ?>)" 
                                    class="text-blue-400 hover:text-blue-300 transition-colors">
                                <i class="fas fa-eye mr-1"></i>View Details
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>

    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
    <div class="flex justify-center items-center space-x-2">
        <?php if ($page_num > 1): ?>
        <?php
        $prev_params = $_GET;
        $prev_params['page'] = 'api_error_logs'; // Preserve routing parameter
        $prev_params['page_num'] = $page_num - 1; // Update pagination parameter
        ?>
        <a href="index.php?<?= http_build_query($prev_params) ?>" 
           class="px-4 py-2 bg-slate-700 text-slate-300 rounded-lg hover:bg-slate-600 transition-colors">
            <i class="fas fa-chevron-left mr-1"></i>Previous
        </a>
        <?php endif; ?>
        
        <span class="px-4 py-2 bg-slate-600 text-white rounded-lg">
            Page <?= $page_num ?> of <?= $total_pages ?>
        </span>
        
        <?php if ($page_num < $total_pages): ?>
        <?php
        $next_params = $_GET;
        $next_params['page'] = 'api_error_logs'; // Preserve routing parameter
        $next_params['page_num'] = $page_num + 1; // Update pagination parameter
        ?>
        <a href="index.php?<?= http_build_query($next_params) ?>" 
           class="px-4 py-2 bg-slate-700 text-slate-300 rounded-lg hover:bg-slate-600 transition-colors">
            Next<i class="fas fa-chevron-right ml-1"></i>
        </a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<!-- Log Details Modal -->
<div id="logModal" class="fixed inset-0 bg-black/50 backdrop-blur-sm hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl shadow-2xl max-w-4xl w-full border border-slate-600">
            <div class="px-6 py-4 border-b border-slate-600">
                <h3 class="text-xl font-bold text-white flex items-center">
                    <i class="fas fa-info-circle mr-3 text-blue-400"></i>API Log Details
                </h3>
            </div>
            <div class="p-6 max-h-96 overflow-y-auto">
                <div id="logDetails"></div>
            </div>
            <div class="px-6 py-4 border-t border-slate-600 flex justify-end">
                <button onclick="closeLogModal()" 
                        class="px-6 py-3 bg-gradient-to-r from-gray-600 to-gray-700 hover:from-gray-700 hover:to-gray-800 text-white rounded-lg transition-all transform hover:scale-105 shadow-lg font-medium">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>

<script>
function viewLogDetails(log) {
    const details = `
        <div class="space-y-4">
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-slate-300 mb-1">Network Type</label>
                    <p class="text-white">${log.network_type}</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-300 mb-1">Status</label>
                    <p class="text-white">${log.success ? 'Success' : 'Failed'}</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-300 mb-1">HTTP Code</label>
                    <p class="text-white">${log.response_code || 'N/A'}</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-300 mb-1">Response Time</label>
                    <p class="text-white">${log.execution_time_ms}ms</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-300 mb-1">Created At</label>
                    <p class="text-white">${new Date(log.created_at).toLocaleString()}</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-300 mb-1">API Endpoint</label>
                    <p class="text-white text-sm break-all">${log.api_endpoint || 'N/A'}</p>
                </div>
            </div>
            
            ${log.error_message ? `
            <div>
                <label class="block text-sm font-medium text-slate-300 mb-1">Error Message</label>
                <div class="bg-red-900/20 border border-red-500/30 rounded-lg p-3">
                    <p class="text-red-300 text-sm">${log.error_message}</p>
                </div>
            </div>
            ` : ''}
            
            ${log.request_data ? `
            <div>
                <label class="block text-sm font-medium text-slate-300 mb-1">Request Data</label>
                <div class="bg-slate-700/50 border border-slate-600 rounded-lg p-3">
                    <pre class="text-slate-300 text-sm overflow-x-auto">${JSON.stringify(JSON.parse(log.request_data), null, 2)}</pre>
                </div>
            </div>
            ` : ''}
            
            ${log.response_data ? `
            <div>
                <label class="block text-sm font-medium text-slate-300 mb-1">Response Data</label>
                <div class="bg-slate-700/50 border border-slate-600 rounded-lg p-3">
                    <pre class="text-slate-300 text-sm overflow-x-auto">${JSON.stringify(JSON.parse(log.response_data), null, 2)}</pre>
                </div>
            </div>
            ` : ''}
        </div>
    `;
    
    document.getElementById('logDetails').innerHTML = details;
    document.getElementById('logModal').classList.remove('hidden');
}

function closeLogModal() {
    document.getElementById('logModal').classList.add('hidden');
}

// Close modal when clicking outside
document.getElementById('logModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeLogModal();
    }
});
</script>
