<?php
require_once 'auth_rbac.php';
require_once '../db_config.php';
require_once '../webhook_service.php';

// Require admin login with settings permission
requirePermission('settings', 'view');

$currentPage = 'settings';
$subPage = 'webhooks';

// Pagination
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 50;
$offset = ($page - 1) * $per_page;

// Filters
$event_filter = $_GET['event'] ?? '';
$status_filter = $_GET['status'] ?? '';
$date_filter = $_GET['date'] ?? '';

try {
    $pdo = getDBConnection();
    $webhookService = new WebhookService($pdo);
    
    // Build WHERE clause for filtering
    $where_conditions = [];
    $params = [];
    
    if (!empty($event_filter)) {
        $where_conditions[] = "event = ?";
        $params[] = $event_filter;
    }
    
    if (!empty($status_filter)) {
        switch ($status_filter) {
            case 'success':
                $where_conditions[] = "http_code >= 200 AND http_code < 300";
                break;
            case 'failed':
                $where_conditions[] = "http_code >= 400";
                break;
            case 'server_error':
                $where_conditions[] = "http_code >= 500";
                break;
        }
    }
    
    if (!empty($date_filter)) {
        $where_conditions[] = "DATE(created_at) = ?";
        $params[] = $date_filter;
    }
    
    $where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";
    
    // Get total count for pagination
    $count_query = "SELECT COUNT(*) FROM webhook_logs {$where_clause}";
    $stmt = $pdo->prepare($count_query);
    $stmt->execute($params);
    $total_records = $stmt->fetchColumn();
    $total_pages = ceil($total_records / $per_page);
    
    // Get webhook logs with pagination
    $query = "
        SELECT * FROM webhook_logs 
        {$where_clause}
        ORDER BY created_at DESC 
        LIMIT {$per_page} OFFSET {$offset}
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $webhookLogs = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get available events for filter
    $events_stmt = $pdo->prepare("SELECT DISTINCT event FROM webhook_logs ORDER BY event");
    $events_stmt->execute();
    $availableEvents = $events_stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Get webhook stats
    $webhookStats = $webhookService->getWebhookStats();
    
} catch (Exception $e) {
    $error = "Database error: " . $e->getMessage();
    $webhookLogs = [];
    $total_records = 0;
    $total_pages = 0;
    $availableEvents = [];
    $webhookStats = [];
}

// Helper function to get status badge class
function getStatusBadgeClass($httpCode) {
    if ($httpCode >= 200 && $httpCode < 300) {
        return 'status-success';
    } elseif ($httpCode >= 400 && $httpCode < 500) {
        return 'status-warning';
    } elseif ($httpCode >= 500) {
        return 'status-error';
    } else {
        return 'status-info';
    }
}

// Helper function to get status text
function getStatusText($httpCode) {
    if ($httpCode >= 200 && $httpCode < 300) {
        return 'Success';
    } elseif ($httpCode >= 400 && $httpCode < 500) {
        return 'Client Error';
    } elseif ($httpCode >= 500) {
        return 'Server Error';
    } else {
        return 'Unknown';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Webhook Logs - XChange Admin</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>

    <div class="admin-content">
        <div class="page-header">
            <div>
                <h1><i class="fas fa-list-alt"></i> Webhook Logs</h1>
                <p>Monitor webhook delivery status and troubleshoot issues</p>
            </div>
            <div class="page-actions">
                <a href="webhook-settings.php" class="btn btn-secondary">
                    <i class="fas fa-cog"></i> Webhook Settings
                </a>
            </div>
        </div>

        <?php if (isset($error)): ?>
            <div class="alert alert-error mb-4"><i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <!-- Webhook Statistics -->
        <?php if (!empty($webhookStats)): ?>
        <div class="stats-grid">
            <div class="stat-card">
                <h3><i class="fas fa-chart-bar"></i> Total Webhooks</h3>
                <div class="stat-layout">
                    <div>
                        <p class="stat-number"><?php echo number_format($webhookStats['total_webhooks'] ?? 0); ?></p>
                        <p class="stat-label">Total Sent</p>
                    </div>
                </div>
            </div>
            
            <div class="stat-card">
                <h3><i class="fas fa-check-circle"></i> Successful</h3>
                <div class="stat-layout">
                    <div>
                        <p class="stat-number"><?php echo number_format($webhookStats['successful'] ?? 0); ?></p>
                        <p class="stat-label">Delivered</p>
                    </div>
                    <div class="stat-right-align">
                        <p class="stat-revenue"><?php echo $webhookStats['total_webhooks'] > 0 ? round(($webhookStats['successful'] / $webhookStats['total_webhooks']) * 100, 1) : 0; ?>%</p>
                        <p class="stat-label">Success Rate</p>
                    </div>
                </div>
            </div>
            
            <div class="stat-card">
                <h3><i class="fas fa-exclamation-triangle"></i> Failed</h3>
                <div class="stat-layout">
                    <div>
                        <p class="stat-number"><?php echo number_format($webhookStats['failed'] ?? 0); ?></p>
                        <p class="stat-label">Client Errors</p>
                    </div>
                </div>
            </div>
            
            <div class="stat-card">
                <h3><i class="fas fa-times-circle"></i> Server Errors</h3>
                <div class="stat-layout">
                    <div>
                        <p class="stat-number"><?php echo number_format($webhookStats['server_errors'] ?? 0); ?></p>
                        <p class="stat-label">Retry Needed</p>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Filters -->
        <div class="filters">
            <h3 style="margin: 0 0 20px 0; color: #1e293b;"><i class="fas fa-search"></i> Filter Logs</h3>
            <form method="GET" class="filter-form">
                <div class="filter-row">
                    <div class="filter-field">
                        <label for="event" class="filter-label">Event Type</label>
                        <select id="event" name="event" class="filter-input">
                            <option value="">All Events</option>
                            <?php foreach ($availableEvents as $event): ?>
                                <option value="<?php echo htmlspecialchars($event); ?>" 
                                        <?php echo $event_filter === $event ? 'selected' : ''; ?>>
                                    <?php echo ucwords(str_replace('_', ' ', $event)); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="filter-field">
                        <label for="status" class="filter-label">Status</label>
                        <select id="status" name="status" class="filter-input">
                            <option value="">All Statuses</option>
                            <option value="success" <?php echo $status_filter === 'success' ? 'selected' : ''; ?>>Success</option>
                            <option value="failed" <?php echo $status_filter === 'failed' ? 'selected' : ''; ?>>Failed</option>
                            <option value="server_error" <?php echo $status_filter === 'server_error' ? 'selected' : ''; ?>>Server Error</option>
                        </select>
                    </div>
                    
                    <div class="filter-field">
                        <label for="date" class="filter-label">Date</label>
                        <input type="date" id="date" name="date" class="filter-input" 
                               value="<?php echo htmlspecialchars($date_filter); ?>">
                    </div>
                    
                    <div class="filter-actions">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-filter"></i>
                            Filter
                        </button>
                        <a href="webhook-logs.php" class="btn btn-secondary">
                            <i class="fas fa-undo"></i>
                            Reset
                        </a>
                    </div>
                </div>
            </form>
        </div>

        <!-- Webhook Logs Table -->
        <div class="data-table">
            <h2><i class="fas fa-list-alt"></i> Webhook Logs (<?php echo number_format($total_records); ?> total)</h2>
            <div class="table-container">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Event</th>
                            <th>Webhook ID</th>
                            <th>HTTP Code</th>
                            <th>Status</th>
                            <th>Response</th>
                            <th>Error</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($webhookLogs)): ?>
                        <tr>
                            <td colspan="7" class="empty-state">
                                <i class="fas fa-file-alt" style="width: 64px; height: 64px; margin-bottom: 1rem; opacity: 0.5; font-size: 64px;"></i>
                                <div style="font-size: 18px; color: #374151; margin-bottom: 8px;">No webhook logs found</div>
                                <div style="font-size: 14px; color: #6b7280;">Webhook logs will appear here once webhooks are sent</div>
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($webhookLogs as $log): ?>
                        <tr>
                            <td>
                                <span class="status-badge badge-type">
                                    <?php echo ucwords(str_replace('_', ' ', $log['event'])); ?>
                                </span>
                            </td>
                            <td>
                                <code class="text-xs"><?php echo htmlspecialchars($log['webhook_id']); ?></code>
                            </td>
                            <td>
                                <span class="status-badge <?php echo getStatusBadgeClass($log['http_code']); ?>">
                                    <?php echo $log['http_code']; ?>
                                </span>
                            </td>
                            <td>
                                <span class="status-badge <?php echo getStatusBadgeClass($log['http_code']); ?>">
                                    <?php echo getStatusText($log['http_code']); ?>
                                </span>
                            </td>
                            <td>
                                <?php if (!empty($log['response'])): ?>
                                    <div class="webhook-response" id="response-<?php echo $log['id']; ?>">
                                        <?php echo htmlspecialchars(substr($log['response'], 0, 100)); ?>
                                        <?php if (strlen($log['response']) > 100): ?>...<?php endif; ?>
                                    </div>
                                    <?php if (strlen($log['response']) > 100): ?>
                                        <a href="#" class="expand-response" onclick="toggleResponse(<?php echo $log['id']; ?>)">Expand</a>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="text-xs muted">—</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if (!empty($log['error_message'])): ?>
                                    <div class="webhook-response" id="error-<?php echo $log['id']; ?>">
                                        <?php echo htmlspecialchars(substr($log['error_message'], 0, 100)); ?>
                                        <?php if (strlen($log['error_message']) > 100): ?>...<?php endif; ?>
                                    </div>
                                    <?php if (strlen($log['error_message']) > 100): ?>
                                        <a href="#" class="expand-response" onclick="toggleError(<?php echo $log['id']; ?>)">Expand</a>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="text-xs muted">—</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div><?php echo date('M j, Y', strtotime($log['created_at'])); ?></div>
                                <div class="text-xxs muted">
                                    <?php echo date('H:i:s', strtotime($log['created_at'])); ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?>&event=<?php echo urlencode($event_filter); ?>&status=<?php echo urlencode($status_filter); ?>&date=<?php echo urlencode($date_filter); ?>">
                    Previous
                </a>
            <?php endif; ?>
            
            <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                <?php if ($i === $page): ?>
                    <span class="current"><?php echo $i; ?></span>
                <?php else: ?>
                    <a href="?page=<?php echo $i; ?>&event=<?php echo urlencode($event_filter); ?>&status=<?php echo urlencode($status_filter); ?>&date=<?php echo urlencode($date_filter); ?>">
                        <?php echo $i; ?>
                    </a>
                <?php endif; ?>
            <?php endfor; ?>
            
            <?php if ($page < $total_pages): ?>
                <a href="?page=<?php echo $page + 1; ?>&event=<?php echo urlencode($event_filter); ?>&status=<?php echo urlencode($status_filter); ?>&date=<?php echo urlencode($date_filter); ?>">
                    Next
                </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>

    <style>
        .webhook-response {
            max-width: 300px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .webhook-response.expanded {
            max-width: none;
            white-space: pre-wrap;
            word-break: break-all;
        }
        
        .expand-response {
            color: #2563eb;
            text-decoration: none;
            font-size: 0.875rem;
            cursor: pointer;
        }
        
        .expand-response:hover {
            text-decoration: underline;
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #6b7280;
        }
        
        .empty-state i {
            width: 64px;
            height: 64px;
            margin-bottom: 1rem;
            opacity: 0.5;
            font-size: 64px;
        }
        
        .stat-card h3 i {
            margin-right: 8px;
            color: #64748b;
        }
        
        .filters h3 i {
            margin-right: 8px;
            color: #64748b;
        }
        
        .data-table h2 i {
            margin-right: 8px;
            color: #64748b;
        }
        
        .page-header h1 i {
            margin-right: 12px;
            color: #2563eb;
        }
        
        .page-actions .btn i {
            margin-right: 6px;
        }
        
        .filter-actions .btn i {
            margin-right: 6px;
        }
    </style>

    <script>
        function toggleResponse(id) {
            const responseDiv = document.getElementById('response-' + id);
            responseDiv.classList.toggle('expanded');
            const link = responseDiv.nextElementSibling;
            if (link) {
                link.textContent = responseDiv.classList.contains('expanded') ? 'Collapse' : 'Expand';
            }
        }
        
        function toggleError(id) {
            const errorDiv = document.getElementById('error-' + id);
            errorDiv.classList.toggle('expanded');
            const link = errorDiv.nextElementSibling;
            if (link) {
                link.textContent = errorDiv.classList.contains('expanded') ? 'Collapse' : 'Expand';
            }
        }
    </script>

    <?php include 'includes/footer.php'; ?>
</body>
</html>
