<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

analytics_module_boot();

$pageTitle = 'Site Analytics';
$analyticsFiltersFromRequest = static fn(array $source): array => analytics_filters_from_request($source);
$analyticsFilterSummary = static fn(array $filters): array => analytics_filter_summary($filters);
$analyticsTrackingIsSupported = static fn(): bool => analytics_tracking_is_supported();
$analyticsOverview = static fn(array $filters): array => analytics_overview($filters);
$analyticsDailyVisits = static fn(array $filters): array => analytics_daily_visits($filters);
$analyticsDailyChartPoints = static fn(array $dailyVisits): array => analytics_daily_chart_points($dailyVisits);
$analyticsTopPages = static fn(array $filters, int $limit = 10): array => analytics_top_pages($filters, $limit);
$analyticsRecentReferrers = static fn(array $filters, int $limit = 10): array => analytics_recent_referrers($filters, $limit);

$filters = $analyticsFiltersFromRequest($_GET);
$filterSummary = $analyticsFilterSummary($filters);
$trackingReady = $analyticsTrackingIsSupported();
$overview = $analyticsOverview($filters);
$dailyVisits = $analyticsDailyVisits($filters);
$dailyChartPoints = $analyticsDailyChartPoints($dailyVisits);
$topPages = $analyticsTopPages($filters, 10);
$referrers = $analyticsRecentReferrers($filters, 10);

require dirname(__DIR__, 2) . '/includes/header.php';
require dirname(__DIR__, 2) . '/includes/sidebar.php';
require dirname(__DIR__, 2) . '/includes/topbar.php';
require dirname(__DIR__, 2) . '/includes/flash.php';
?>
<section class="panel-card mb-4">
    <div class="panel-card-header mb-3">
        <div>
            <p class="eyebrow mb-1">Audience analytics</p>
            <h2 class="h4 mb-0">Public site traffic</h2>
            <div class="small text-muted mt-1">Logged automatically for public page requests, filtered to remove bots, internal traffic, and visits from signed-in admins.</div>
        </div>
    </div>

    <?php if (!$trackingReady): ?>
        <div class="alert alert-warning mb-0">
            Analytics tracking is not active yet. Run the migration for the <code>site_visits</code> table, then reload this page.
        </div>
    <?php else: ?>
        <form class="row g-3" method="get" action="<?php echo e(base_url('app/modules/analytics/index.php')); ?>">
            <div class="col-md-3">
                <label class="form-label" for="start_date">Start date</label>
                <input class="form-control" type="date" id="start_date" name="start_date" value="<?php echo e((string) $filters['start_date']); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label" for="end_date">End date</label>
                <input class="form-control" type="date" id="end_date" name="end_date" value="<?php echo e((string) $filters['end_date']); ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label" for="path">Page</label>
                <select class="form-select" id="path" name="path">
                    <option value="">All public pages</option>
                    <?php foreach (($filters['available_paths'] ?? []) as $pathOption): ?>
                        <option value="<?php echo e((string) $pathOption); ?>" <?php echo (string) $filters['path'] === (string) $pathOption ? 'selected' : ''; ?>><?php echo e((string) $pathOption); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2 d-flex align-items-end gap-2">
                <button class="btn btn-jlfc w-100" type="submit">Apply</button>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/analytics/index.php')); ?>">Reset</a>
            </div>
        </form>
    <?php endif; ?>
</section>

<section class="row g-3 mb-4">
    <div class="col-md-4 col-xl-2">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-bar-chart-fill"></i></div>
            <span class="metric-label">Pageviews</span>
            <strong class="metric-value"><?php echo e((string) $overview['pageviews']); ?></strong>
            <small class="text-muted"><?php echo e($filterSummary['range_label']); ?></small>
        </article>
    </div>
    <div class="col-md-4 col-xl-2">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-people-fill"></i></div>
            <span class="metric-label">Unique visitors</span>
            <strong class="metric-value"><?php echo e((string) $overview['unique_visitors']); ?></strong>
            <small class="text-muted"><?php echo e($filterSummary['path_label']); ?></small>
        </article>
    </div>
    <div class="col-md-4 col-xl-2">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-graph-up-arrow"></i></div>
            <span class="metric-label">Daily average</span>
            <strong class="metric-value"><?php echo e((string) $overview['average_daily_pageviews']); ?></strong>
            <small class="text-muted"><?php echo e((string) $filterSummary['days']); ?> day range</small>
        </article>
    </div>
    <div class="col-md-4 col-xl-2">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-fire"></i></div>
            <span class="metric-label">Peak day</span>
            <strong class="metric-value"><?php echo e((string) $overview['peak_day_pageviews']); ?></strong>
            <small class="text-muted">Highest daily pageviews</small>
        </article>
    </div>
    <div class="col-md-4 col-xl-2">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-files"></i></div>
            <span class="metric-label">Tracked pages</span>
            <strong class="metric-value"><?php echo e((string) $overview['tracked_pages']); ?></strong>
            <small class="text-muted">Pages in the filtered result</small>
        </article>
    </div>
    <div class="col-md-4 col-xl-2">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-box-arrow-up-right"></i></div>
            <span class="metric-label">Referrers</span>
            <strong class="metric-value"><?php echo e((string) $overview['referrers']); ?></strong>
            <small class="text-muted">Distinct traffic sources</small>
        </article>
    </div>
</section>

<section class="row g-4">
    <div class="col-12 col-xl-6">
        <article class="panel-card h-100">
            <div class="panel-card-header mb-3">
                <div>
                    <p class="eyebrow mb-1">Trend</p>
                    <h3 class="h5 mb-0">Daily traffic</h3>
                </div>
            </div>
            <div class="traffic-chart mb-4" role="img" aria-label="Daily traffic chart">
                <?php if ($dailyChartPoints === []): ?>
                    <div class="text-muted small">No visit data has been logged for this filter yet.</div>
                <?php else: ?>
                    <?php foreach ($dailyChartPoints as $point): ?>
                        <div class="traffic-chart-bar-wrap">
                            <span class="traffic-chart-value"><?php echo e((string) $point['pageviews']); ?></span>
                            <div class="traffic-chart-bar" style="height: <?php echo e((string) $point['height']); ?>%;"></div>
                            <span class="traffic-chart-label"><?php echo e((string) $point['label']); ?></span>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            <div class="table-responsive">
                <table class="table align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Pageviews</th>
                            <th>Visitors</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($dailyVisits === []): ?><tr>
                                <td colspan="3" class="text-center text-muted py-4">No visit data has been logged yet.</td>
                            </tr><?php endif; ?>
                        <?php foreach ($dailyVisits as $row): ?>
                            <tr>
                                <td><?php echo e((string) $row['visit_date']); ?></td>
                                <td><?php echo e((string) $row['pageviews']); ?></td>
                                <td><?php echo e((string) $row['visitors']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </article>
    </div>
    <div class="col-12 col-xl-6">
        <article class="panel-card h-100">
            <div class="panel-card-header mb-3">
                <div>
                    <p class="eyebrow mb-1">Content</p>
                    <h3 class="h5 mb-0">Top pages</h3>
                </div>
            </div>
            <div class="page-share-list mb-4">
                <?php if ($topPages === []): ?>
                    <div class="text-muted small">No tracked pages yet for this filter.</div>
                <?php else: ?>
                    <?php foreach ($topPages as $row): ?>
                        <div class="page-share-item">
                            <div class="d-flex justify-content-between gap-3 small mb-2">
                                <strong class="text-truncate"><?php echo e((string) $row['path']); ?></strong>
                                <span><?php echo e((string) $row['share_percent']); ?>%</span>
                            </div>
                            <div class="page-share-bar-track">
                                <div class="page-share-bar-fill" style="width: <?php echo e((string) $row['bar_percent']); ?>%;"></div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            <div class="table-responsive">
                <table class="table align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Path</th>
                            <th>Pageviews</th>
                            <th>Visitors</th>
                            <th>Last hit</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($topPages === []): ?><tr>
                                <td colspan="4" class="text-center text-muted py-4">No tracked pages yet.</td>
                            </tr><?php endif; ?>
                        <?php foreach ($topPages as $row): ?>
                            <tr>
                                <td><code><?php echo e((string) $row['path']); ?></code></td>
                                <td><?php echo e((string) $row['pageviews']); ?></td>
                                <td><?php echo e((string) $row['visitors']); ?></td>
                                <td><?php echo e((string) $row['last_visit_at']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </article>
    </div>
</section>

<section class="panel-card mt-4">
    <div class="panel-card-header mb-3">
        <div>
            <p class="eyebrow mb-1">Sources</p>
            <h3 class="h5 mb-0">Recent referrers</h3>
        </div>
    </div>
    <div class="table-responsive">
        <table class="table align-middle mb-0">
            <thead>
                <tr>
                    <th>Referrer</th>
                    <th>Visits</th>
                    <th>Last hit</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($referrers === []): ?><tr>
                        <td colspan="3" class="text-center text-muted py-4">No external referrers have been recorded yet.</td>
                    </tr><?php endif; ?>
                <?php foreach ($referrers as $row): ?>
                    <tr>
                        <td><?php echo e((string) $row['referrer']); ?></td>
                        <td><?php echo e((string) $row['visits']); ?></td>
                        <td><?php echo e((string) $row['last_visit_at']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>

<?php require dirname(__DIR__, 2) . '/includes/footer.php'; ?>