<?php
/**
 * AI Monitor — Traffic Panel partial.
 *
 * Renders a per-subscription Traffic block inside the AI Monitor customer
 * dashboard: yesterday's totals, a 14-day human-views sparkline, the top 10
 * URLs / bandwidth consumers (collapsed), and an "Analyze traffic" button
 * that enqueues a traffic-type review via the existing review worker.
 *
 * Required variables in the includer's scope:
 *   $site_id          (int)    — site row id
 *   $username         (string) — owner of the site (filesystem account)
 *   $primary_domain   (string) — display label
 *   $subscription_id  (int)    — AI monitor subscription id (used by enqueue)
 *   $csrf_token       (string) — passed through to JS for the AJAX call
 *
 * The TrafficAnalytics library reads the per-user monthly SQLite at
 * /docker/users/<username>/whp-analytics/<YYYY-MM>.sqlite3. The aggregator
 * cron writes those files at 1 AM, so today's row generally won't exist
 * mid-day — we surface yesterday's snapshot to keep the UI honest.
 */

require_once('/docker/whp/web/libs/traffic_analytics.php');

if (!isset($site_id, $username, $primary_domain, $subscription_id, $csrf_token)) {
    return;
}

$ta = new TrafficAnalytics();
$yesterdayDate = date('Y-m-d', strtotime('-1 day'));

try {
    $yesterday = $ta->getDailyTotals($username, (int)$site_id, $yesterdayDate);
    $last14    = $ta->getRecentDailyTotals($username, (int)$site_id, 14);
    $topUrls   = $ta->getTopUrls($username, (int)$site_id, $yesterdayDate);
    $topBw     = $ta->getTopBandwidth($username, (int)$site_id, $yesterdayDate);
} catch (Throwable $e) {
    error_log('ai-monitor-traffic-panel: ' . $e->getMessage());
    $yesterday = null;
    $last14    = [];
    $topUrls   = [];
    $topBw     = [];
}

if (!function_exists('whp_traffic_human_filesize')) {
    function whp_traffic_human_filesize(int $bytes): string {
        if ($bytes < 1024)               return $bytes . ' B';
        if ($bytes < 1024 * 1024)        return number_format($bytes / 1024, 1) . ' KB';
        if ($bytes < 1024 * 1024 * 1024) return number_format($bytes / 1048576, 1) . ' MB';
        return number_format($bytes / 1073741824, 2) . ' GB';
    }
}

?>
<div class="card mt-3 traffic-panel" data-site-id="<?php echo (int)$site_id; ?>" data-subscription-id="<?php echo (int)$subscription_id; ?>" data-domain="<?php echo htmlspecialchars(strtolower($primary_domain), ENT_QUOTES, 'UTF-8'); ?>">
    <div class="card-header">
        <strong><i class="fa fa-bar-chart"></i> Traffic <span class="text-muted small ms-1">— <?php echo htmlspecialchars($primary_domain, ENT_QUOTES, 'UTF-8'); ?></span></strong>
<?php if (!empty($last14)): ?>
        <span class="text-muted small float-end"><?php echo htmlspecialchars(date('M j, Y', strtotime($yesterdayDate)), ENT_QUOTES, 'UTF-8'); ?></span>
<?php endif; ?>
    </div>
    <div class="card-body">
<?php if (empty($last14)): ?>
        <p class="text-muted mb-0">No traffic data collected yet — the nightly aggregator runs at 1 AM. Check back tomorrow.</p>
<?php else:
    $reqs   = (int)($yesterday['total_requests'] ?? 0);
    $human  = (int)($yesterday['human_views']    ?? 0);
    $bytes  = (int)($yesterday['bytes_sent']     ?? 0);
?>
        <div class="row g-3 mb-3">
            <div class="col-md-4">
                <div class="rounded p-3 text-center h-100" style="background: rgba(13,110,253,0.08); border-top: 4px solid #0d6efd;">
                    <div class="small text-uppercase fw-semibold" style="color:#0d6efd;">Total Requests</div>
                    <div style="font-size: 1.75rem; font-weight: 700; color:#0d6efd;"><?php echo number_format($reqs); ?></div>
                    <div class="text-muted small">all hits, incl. bots</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="rounded p-3 text-center h-100" style="background: rgba(25,135,84,0.08); border-top: 4px solid #198754;">
                    <div class="small text-uppercase fw-semibold" style="color:#198754;">Human Views</div>
                    <div style="font-size: 1.75rem; font-weight: 700; color:#198754;"><?php echo number_format($human); ?></div>
                    <div class="text-muted small">excl. bots &amp; assets</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="rounded p-3 text-center h-100" style="background: rgba(111,66,193,0.08); border-top: 4px solid #6f42c1;">
                    <div class="small text-uppercase fw-semibold" style="color:#6f42c1;">Bandwidth Served</div>
                    <div style="font-size: 1.75rem; font-weight: 700; color:#6f42c1;"><?php echo htmlspecialchars(whp_traffic_human_filesize($bytes), ENT_QUOTES, 'UTF-8'); ?></div>
                    <div class="text-muted small">2xx/3xx responses</div>
                </div>
            </div>
        </div>

<?php
        // HTML/CSS bar chart — server-rendered, no JS, no library. Bars are
        // div blocks sized as percentages of a flex container, so they
        // stretch to fit any width without us measuring. Axes are real
        // text, not stretched SVG glyphs.
        $maxVal = 0;
        foreach ($last14 as $r) { $maxVal = max($maxVal, (int)$r['human_views']); }
        $nBars = count($last14);

        if (!function_exists('whp_traffic_nice_max')) {
            // Round up to a 2-sig-fig "nice" number for the Y axis label
            // so we get e.g. 6100 instead of 6059, 120000 instead of 116355.
            function whp_traffic_nice_max(int $n): int {
                if ($n <= 10) return max(1, $n);
                $mag = (int)pow(10, max(0, floor(log10($n)) - 1));
                return (int)(ceil($n / $mag) * $mag);
            }
            function whp_traffic_format_axis(int $n): string {
                if ($n < 1000)    return number_format($n);
                if ($n < 1000000) return ($n / 1000 < 10 ? number_format($n / 1000, 1) : number_format($n / 1000, 0)) . 'K';
                return ($n / 1000000 < 10 ? number_format($n / 1000000, 1) : number_format($n / 1000000, 0)) . 'M';
            }
        }

        $niceMax  = whp_traffic_nice_max($maxVal);
        $niceMid  = (int)round($niceMax / 2);

        // Pick 5 evenly-spaced bar indices to label on the X axis so 14
        // dates don't pile on top of each other.
        $labelTargetCount = min(5, $nBars);
        $labelIndices = [];
        for ($k = 0; $k < $labelTargetCount; $k++) {
            $labelIndices[(int)round($k * ($nBars - 1) / max(1, $labelTargetCount - 1))] = true;
        }
?>
        <div class="mb-3">
            <div class="text-muted small text-uppercase fw-semibold mb-1">Human views — last 14 days</div>
            <div style="display: flex; height: 130px; font-size: 0.7rem; color: #6c757d;">
                <!-- Y axis: labels are absolutely positioned and centered on
                     the gridline they represent (translateY(-50%)) so each
                     value lines up exactly with its corresponding line. -->
                <div style="position: relative; width: 50px; padding-right: 8px;">
                    <span style="position: absolute; top: 0;     right: 8px; transform: translateY(-50%); white-space: nowrap;"><?php echo htmlspecialchars(whp_traffic_format_axis($niceMax), ENT_QUOTES, 'UTF-8'); ?></span>
                    <span style="position: absolute; top: 50%;   right: 8px; transform: translateY(-50%); white-space: nowrap;"><?php echo htmlspecialchars(whp_traffic_format_axis($niceMid), ENT_QUOTES, 'UTF-8'); ?></span>
                    <span style="position: absolute; bottom: 0;  right: 8px; transform: translateY( 50%); white-space: nowrap;">0</span>
                </div>
                <!-- Plot area. One midline gridline at 50% (the top is
                     already implied by the niceMax Y-axis label and the
                     bars meeting it; drawing a line there fights with
                     bars that touch the top edge). -->
                <div style="flex-grow: 1; position: relative; border-bottom: 1px solid #adb5bd; border-left: 1px solid #adb5bd;">
                    <!-- Bars first; midline drawn AFTER them with a higher
                         stacking context so the gridline is visible across
                         any bar that crosses it. -->
                    <div style="position: absolute; inset: 0; display: flex; align-items: flex-end; gap: 2px; padding: 0 2px; z-index: 1;">
<?php foreach ($last14 as $i => $row):
                        $val = (int)$row['human_views'];
                        $h   = ($niceMax > 0) ? ($val / $niceMax * 100) : 0;
?>
                        <div style="flex: 1 1 0; height: <?php echo number_format($h, 2, '.', ''); ?>%; background: rgba(13, 110, 253, 0.5); min-height: <?php echo $val > 0 ? '1px' : '0'; ?>; border-radius: 2px 2px 0 0;" title="<?php echo htmlspecialchars((string)$row['date'], ENT_QUOTES, 'UTF-8'); ?>: <?php echo number_format($val); ?> human views"></div>
<?php endforeach; ?>
                    </div>
                    <div style="position: absolute; top: 50%; left: 0; right: 0; border-top: 1px dashed #6c757d; pointer-events: none; z-index: 2;" title="<?php echo htmlspecialchars(whp_traffic_format_axis($niceMid) . ' views', ENT_QUOTES, 'UTF-8'); ?>"></div>
                </div>
            </div>
            <div style="display: flex; padding-left: 58px; padding-right: 2px; font-size: 0.7rem; color: #6c757d; margin-top: 4px;">
<?php foreach ($last14 as $i => $row):
                $show = ($i === $nBars - 1) || isset($labelIndices[$i]);
?>
                <span style="flex: 1 1 0; text-align: center; color: #6c757d; white-space: nowrap; overflow: hidden;"><?php echo $show ? htmlspecialchars(substr((string)$row['date'], 5), ENT_QUOTES, 'UTF-8') : '&nbsp;'; ?></span>
<?php endforeach; ?>
            </div>
        </div>

        <details class="mb-2 traffic-details">
            <summary class="fw-semibold"><span class="traffic-details-marker"></span>Top 10 URLs<i class="fa fa-list-ol ms-2 text-muted"></i></summary>
            <div class="table-responsive mt-2">
                <table class="table table-sm table-hover mb-0">
                    <thead><tr><th style="width: 60px;">#</th><th>Path</th><th class="text-end" style="width: 100px;">Hits</th></tr></thead>
                    <tbody>
<?php if (empty($topUrls)): ?>
                        <tr><td colspan="3" class="text-muted text-center">No data for this day.</td></tr>
<?php else: foreach ($topUrls as $row): ?>
                        <tr>
                            <td><?php echo (int)$row['rank']; ?></td>
                            <td class="text-truncate" style="max-width: 480px;" title="<?php echo htmlspecialchars((string)$row['url'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars((string)$row['url'], ENT_QUOTES, 'UTF-8'); ?></td>
                            <td class="text-end"><?php echo number_format((int)$row['hits']); ?></td>
                        </tr>
<?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </details>

        <details class="mb-3 traffic-details">
            <summary class="fw-semibold"><span class="traffic-details-marker"></span>Top 10 Bandwidth Consumers<i class="fa fa-database ms-2 text-muted"></i></summary>
            <div class="table-responsive mt-2">
                <table class="table table-sm table-hover mb-0">
                    <thead><tr><th style="width: 60px;">#</th><th>Path</th><th class="text-end" style="width: 110px;">Bytes</th><th class="text-end" style="width: 90px;">Hits</th></tr></thead>
                    <tbody>
<?php if (empty($topBw)): ?>
                        <tr><td colspan="4" class="text-muted text-center">No data for this day.</td></tr>
<?php else: foreach ($topBw as $row): ?>
                        <tr>
                            <td><?php echo (int)$row['rank']; ?></td>
                            <td class="text-truncate" style="max-width: 440px;" title="<?php echo htmlspecialchars((string)$row['url'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars((string)$row['url'], ENT_QUOTES, 'UTF-8'); ?></td>
                            <td class="text-end"><?php echo htmlspecialchars(whp_traffic_human_filesize((int)$row['bytes_total']), ENT_QUOTES, 'UTF-8'); ?></td>
                            <td class="text-end"><?php echo number_format((int)$row['hits']); ?></td>
                        </tr>
<?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </details>

        <div class="d-flex align-items-center gap-2 flex-wrap">
            <button type="button" class="btn btn-sm btn-primary btn-analyze-traffic"
                    data-subscription-id="<?php echo (int)$subscription_id; ?>"
                    data-site-id="<?php echo (int)$site_id; ?>">
                <i class="fa fa-magic"></i> Analyze Traffic
            </button>
            <span class="analyze-traffic-status text-muted small" data-subscription-id="<?php echo (int)$subscription_id; ?>"></span>
        </div>

<?php endif; ?>
    </div>
</div>
