<?php
/**
 * ============================================================================
 * admin/network-usage.php - Network Usage Monitoring
 * Track bandwidth and API usage
 * ============================================================================
 */

require_once __DIR__ . '/includes/base.php';

if (!hasAdminPermission('view_network_usage')) {
    setFlashMessage('Access denied.', 'error');
    header('Location: ' . APP_URL . '/admin/index.php');
    exit();
}

$breadcrumbs = [['title' => 'Network Usage', 'url' => '']];

// Get network statistics
try {
    // Today's usage
    $sql = "SELECT 
                COUNT(*) as total_requests,
                SUM(request_size) as total_request_bytes,
                SUM(response_size) as total_response_bytes,
                AVG(response_time) as avg_response_time,
                endpoint
            FROM network_usage 
            WHERE DATE(recorded_at) = CURDATE()
            GROUP BY endpoint
            ORDER BY total_requests DESC
            LIMIT 20";
    $stmt = $db->query($sql);
    $endpoint_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Total bandwidth today
    $sql = "SELECT 
                SUM(request_size + response_size) / 1024 / 1024 as total_mb,
                COUNT(*) as total_requests
            FROM network_usage 
            WHERE DATE(recorded_at) = CURDATE()";
    $stmt = $db->query($sql);
    $today_total = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Hourly breakdown
    $sql = "SELECT 
                HOUR(recorded_at) as hour,
                COUNT(*) as requests,
                SUM(request_size + response_size) / 1024 / 1024 as bandwidth_mb
            FROM network_usage 
            WHERE DATE(recorded_at) = CURDATE()
            GROUP BY HOUR(recorded_at)
            ORDER BY hour";
    $stmt = $db->query($sql);
    $hourly_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Top users by bandwidth
    $sql = "SELECT 
                u.full_name,
                u.phone_number,
                COUNT(*) as requests,
                SUM(request_size + response_size) / 1024 / 1024 as bandwidth_mb
            FROM network_usage n
            LEFT JOIN users u ON n.user_id = u.id
            WHERE DATE(n.recorded_at) = CURDATE()
            GROUP BY n.user_id
            ORDER BY bandwidth_mb DESC
            LIMIT 10";
    $stmt = $db->query($sql);
    $top_users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    logError('Network usage error: ' . $e->getMessage());
    $endpoint_stats = [];
    $today_total = ['total_mb' => 0, 'total_requests' => 0];
    $hourly_stats = [];
    $top_users = [];
}

renderAdminHeader('Network Usage', $breadcrumbs);
?>

<!-- Summary Cards -->
<div class="row mb-4">
    <div class="col-md-4">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted">Total Bandwidth (Today)</h6>
                <h2 class="fw-bold"><?php echo number_format($today_total['total_mb'], 2); ?> MB</h2>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted">Total Requests</h6>
                <h2 class="fw-bold"><?php echo number_format($today_total['total_requests']); ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted">Avg Per Request</h6>
                <h2 class="fw-bold">
                    <?php 
                    $avg = $today_total['total_requests'] > 0 ? 
                        ($today_total['total_mb'] * 1024) / $today_total['total_requests'] : 0;
                    echo number_format($avg, 2); 
                    ?> KB
                </h2>
            </div>
        </div>
    </div>
</div>

<!-- Hourly Chart -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-header bg-white">
        <h5 class="mb-0 fw-bold">Hourly Network Usage</h5>
    </div>
    <div class="card-body">
        <canvas id="hourlyChart" height="80"></canvas>
    </div>
</div>

<!-- Endpoint Statistics -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-header bg-white">
        <h5 class="mb-0 fw-bold">Top Endpoints by Traffic</h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>Endpoint</th>
                        <th class="text-end">Requests</th>
                        <th class="text-end">Request Size</th>
                        <th class="text-end">Response Size</th>
                        <th class="text-end">Avg Response Time</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($endpoint_stats as $stat): ?>
                    <tr>
                        <td class="fw-semibold"><?php echo htmlspecialchars($stat['endpoint']); ?></td>
                        <td class="text-end"><?php echo number_format($stat['total_requests']); ?></td>
                        <td class="text-end"><?php echo number_format($stat['total_request_bytes'] / 1024, 2); ?> KB</td>
                        <td class="text-end"><?php echo number_format($stat['total_response_bytes'] / 1024, 2); ?> KB</td>
                        <td class="text-end"><?php echo number_format($stat['avg_response_time']); ?> ms</td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Top Users -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white">
        <h5 class="mb-0 fw-bold">Top Users by Bandwidth</h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>User</th>
                        <th>Phone</th>
                        <th class="text-end">Requests</th>
                        <th class="text-end">Bandwidth</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($top_users as $user): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($user['full_name'] ?? 'Anonymous'); ?></td>
                        <td><?php echo htmlspecialchars($user['phone_number'] ?? '-'); ?></td>
                        <td class="text-end"><?php echo number_format($user['requests']); ?></td>
                        <td class="text-end"><?php echo number_format($user['bandwidth_mb'], 2); ?> MB</td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
// Hourly Chart
const hourlyData = <?php echo json_encode($hourly_stats); ?>;
const ctx = document.getElementById('hourlyChart').getContext('2d');

new Chart(ctx, {
    type: 'bar',
    data: {
        labels: hourlyData.map(d => d.hour + ':00'),
        datasets: [{
            label: 'Bandwidth (MB)',
            data: hourlyData.map(d => parseFloat(d.bandwidth_mb)),
            backgroundColor: 'rgba(5, 150, 105, 0.7)',
            borderColor: 'rgb(5, 150, 105)',
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: true,
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});
</script>

<?php renderAdminFooter(); ?>