<?php
/**
 * Webhook Monitor - Real-time webhook activity monitoring
 * This script provides a simple interface to monitor webhook activity
 */

require_once '../config.php';
require_once '../app/classes/AdminAuth.php';

$adminAuth = new AdminAuth($conn);

// Check if admin is authenticated
if (!$adminAuth->isAuthenticated()) {
    die('Unauthorized access');
}

// Set content type
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Webhook Monitor | D-Bundles Stores</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Admin Dark Theme CSS -->
    <link rel="stylesheet" href="assets/admin-dark-theme.css">
    <script>
        // Auto-refresh every 30 seconds
        setTimeout(function() {
            location.reload();
        }, 30000);
    </script>
</head>
<body class="bg-gray-100">
    <div class="container mx-auto px-4 py-8">
        <div class="flex justify-between items-center mb-8">
            <h1 class="text-3xl font-bold">📡 Webhook Monitor</h1>
            <div class="text-sm text-gray-500">
                <i class="fas fa-sync-alt mr-1"></i>Auto-refresh: 30s
            </div>
        </div>
        
        <?php
        // Get webhook statistics
        $stats_query = "
            SELECT 
                COUNT(*) as total_webhooks,
                SUM(CASE WHEN processed = 1 THEN 1 ELSE 0 END) as processed_webhooks,
                SUM(CASE WHEN processed = 0 THEN 1 ELSE 0 END) as failed_webhooks,
                COUNT(DISTINCT external_transaction_id) as unique_transactions
            FROM webhook_logs
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
        ";
        
        $stats_result = mysqli_query($conn, $stats_query);
        $stats = mysqli_fetch_assoc($stats_result);
        
        // Get recent webhook activity
        $recent_webhooks_query = "
            SELECT 
                wl.*,
                o.order_reference,
                o.beneficiary_number,
                o.status as order_status
            FROM webhook_logs wl
            LEFT JOIN orders o ON wl.order_id = o.id
            ORDER BY wl.created_at DESC
            LIMIT 20
        ";
        
        $recent_webhooks_result = mysqli_query($conn, $recent_webhooks_query);
        ?>
        
        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white rounded-lg shadow-md p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Total Webhooks (24h)</p>
                        <p class="text-2xl font-bold text-gray-900"><?= $stats['total_webhooks'] ?></p>
                    </div>
                    <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
                        <i class="fas fa-broadcast-tower text-blue-600 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow-md p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Processed</p>
                        <p class="text-2xl font-bold text-green-600"><?= $stats['processed_webhooks'] ?></p>
                    </div>
                    <div class="w-12 h-12 bg-green-100 rounded-xl flex items-center justify-center">
                        <i class="fas fa-check text-green-600 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow-md p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Failed</p>
                        <p class="text-2xl font-bold text-red-600"><?= $stats['failed_webhooks'] ?></p>
                    </div>
                    <div class="w-12 h-12 bg-red-100 rounded-xl flex items-center justify-center">
                        <i class="fas fa-times text-red-600 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow-md p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Unique Transactions</p>
                        <p class="text-2xl font-bold text-purple-600"><?= $stats['unique_transactions'] ?></p>
                    </div>
                    <div class="w-12 h-12 bg-purple-100 rounded-xl flex items-center justify-center">
                        <i class="fas fa-fingerprint text-purple-600 text-xl"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Recent Webhook Activity -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-xl font-semibold mb-4">📋 Recent Webhook Activity</h2>
            
            <?php if ($recent_webhooks_result && mysqli_num_rows($recent_webhooks_result) > 0): ?>
                <div class="overflow-x-auto">
                    <table class="min-w-full table-auto">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-4 py-2 text-left">Time</th>
                                <th class="px-4 py-2 text-left">External TX ID</th>
                                <th class="px-4 py-2 text-left">Order Reference</th>
                                <th class="px-4 py-2 text-left">Phone</th>
                                <th class="px-4 py-2 text-left">Status</th>
                                <th class="px-4 py-2 text-left">Order Status</th>
                                <th class="px-4 py-2 text-left">Processed</th>
                                <th class="px-4 py-2 text-left">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($row = mysqli_fetch_assoc($recent_webhooks_result)): ?>
                                <tr class="border-t hover:bg-gray-50">
                                    <td class="px-4 py-2 text-sm">
                                        <?= date('H:i:s', strtotime($row['created_at'])) ?>
                                        <br>
                                        <span class="text-gray-500"><?= date('M j', strtotime($row['created_at'])) ?></span>
                                    </td>
                                    <td class="px-4 py-2 font-mono text-sm">
                                        <?= htmlspecialchars($row['external_transaction_id']) ?>
                                    </td>
                                    <td class="px-4 py-2">
                                        <?= htmlspecialchars($row['order_reference'] ?? 'N/A') ?>
                                    </td>
                                    <td class="px-4 py-2">
                                        <?= htmlspecialchars($row['beneficiary_number'] ?? 'N/A') ?>
                                    </td>
                                    <td class="px-4 py-2">
                                        <span class="px-2 py-1 rounded-full text-xs font-medium
                                            <?php 
                                            switch($row['response_status']) {
                                                case 'delivered': echo 'bg-green-100 text-green-800'; break;
                                                case 'failed': echo 'bg-red-100 text-red-800'; break;
                                                case 'processing': echo 'bg-yellow-100 text-yellow-800'; break;
                                                default: echo 'bg-gray-100 text-gray-800';
                                            }
                                            ?>">
                                            <?= htmlspecialchars($row['response_status']) ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-2">
                                        <span class="px-2 py-1 rounded-full text-xs font-medium
                                            <?php 
                                            switch($row['order_status']) {
                                                case 'delivered': echo 'bg-green-100 text-green-800'; break;
                                                case 'failed': echo 'bg-red-100 text-red-800'; break;
                                                case 'processing': echo 'bg-yellow-100 text-yellow-800'; break;
                                                default: echo 'bg-gray-100 text-gray-800';
                                            }
                                            ?>">
                                            <?= htmlspecialchars($row['order_status'] ?? 'N/A') ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-2">
                                        <?php if ($row['processed']): ?>
                                            <span class="text-green-600">
                                                <i class="fas fa-check"></i> Yes
                                            </span>
                                        <?php else: ?>
                                            <span class="text-red-600">
                                                <i class="fas fa-times"></i> No
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-4 py-2">
                                        <button onclick="viewWebhookDetails(<?= $row['id'] ?>)" 
                                                class="text-blue-600 hover:text-blue-800 text-sm">
                                            <i class="fas fa-eye"></i> View
                                        </button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="text-center py-8 text-gray-500">
                    <i class="fas fa-inbox text-4xl mb-4"></i>
                    <p>No webhook activity found</p>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Webhook Log File Viewer -->
        <div class="bg-white rounded-lg shadow-md p-6 mt-6">
            <h2 class="text-xl font-semibold mb-4">📄 Webhook Debug Log (Last 20 lines)</h2>
            
            <?php
            $log_file = '../webhook_debug.log';
            if (file_exists($log_file)) {
                $log_lines = file($log_file);
                $last_lines = array_slice($log_lines, -20);
                
                echo "<div class='bg-gray-900 text-green-400 p-4 rounded-lg font-mono text-sm overflow-x-auto max-h-96'>";
                foreach ($last_lines as $line) {
                    echo htmlspecialchars($line) . "<br>";
                }
                echo "</div>";
            } else {
                echo "<p class='text-gray-500'>Webhook debug log file not found</p>";
            }
            ?>
        </div>
        
        <div class="mt-8 text-center">
            <a href="test_webhook_system.php" class="bg-green-500 hover:bg-green-600 text-white px-6 py-2 rounded-lg inline-block">
                <i class="fas fa-cog mr-2"></i>Test Webhook System
            </a>
        </div>
    </div>
    
    <!-- Webhook Details Modal -->
    <div id="webhookModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-96 overflow-y-auto">
                <div class="p-6">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-lg font-semibold">Webhook Details</h3>
                        <button onclick="closeWebhookModal()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div id="webhookDetails" class="space-y-4">
                        <!-- Details will be loaded here -->
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        function viewWebhookDetails(webhookId) {
            // This would typically make an AJAX call to get webhook details
            // For now, we'll show a placeholder
            document.getElementById('webhookDetails').innerHTML = `
                <p>Webhook ID: ${webhookId}</p>
                <p class="text-gray-500">Detailed webhook information would be loaded here via AJAX.</p>
            `;
            document.getElementById('webhookModal').classList.remove('hidden');
        }
        
        function closeWebhookModal() {
            document.getElementById('webhookModal').classList.add('hidden');
        }
        
        // Close modal when clicking outside
        document.getElementById('webhookModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeWebhookModal();
            }
        });
    </script>
</body>
</html>
