<?php
    $hostBreakdown = isset($hostBreakdown) && is_array($hostBreakdown) ? $hostBreakdown : [];
    $totalAmount = isset($totalAmount) ? (float)$totalAmount : 0.0;
    $totalAdminShare = isset($totalAdminShare) ? (float)$totalAdminShare : 0.0;
    $totalUserShare = isset($totalUserShare) ? (float)$totalUserShare : 0.0;
    $totalCoins = isset($totalCoins) ? (int)$totalCoins : 0;
    $transactionCount = isset($transactionCount) ? (int)$transactionCount : 0;
    $filters = isset($filters) && is_array($filters) ? $filters : ['start_date' => date('Y-m-d'), 'end_date' => date('Y-m-d'), 'is_custom' => false];
    $startDateValue = htmlspecialchars($filters['start_date'] ?? date('Y-m-d'), ENT_QUOTES, 'UTF-8');
    $endDateValue = htmlspecialchars($filters['end_date'] ?? date('Y-m-d'), ENT_QUOTES, 'UTF-8');
    $uniqueHosts = count($hostBreakdown);
    $currency = function ($value) {
        return number_format((float)$value, 2, '.', ',');
    };
?>

<main class="main-wrapper">
    <div class="main-content">
        <div class="d-flex flex-wrap justify-content-between align-items-start align-items-lg-center gap-3 mb-4">
            <div>
                <h2 class="fw-semibold mb-1">Revenue by User</h2>
                <p class="text-muted mb-0">
                    <?php if (!empty($filters['is_custom'])): ?>
                        Host earnings between <span class="fw-semibold"><?= $startDateValue; ?></span> and <span class="fw-semibold"><?= $endDateValue; ?></span>.
                    <?php else: ?>
                        Host earnings for today (<?= $startDateValue; ?>).
                    <?php endif; ?>
                </p>
            </div>
            <form method="get" action="<?= htmlspecialchars(base_url('site/revenueByUser'), ENT_QUOTES, 'UTF-8'); ?>" class="row g-2 align-items-center">
                <div class="col-auto">
                    <label for="revenueUserStartDate" class="form-label mb-0 text-muted small">Start date</label>
                    <input type="date" class="form-control" id="revenueUserStartDate" name="start_date" value="<?= $startDateValue; ?>" max="<?= date('Y-m-d'); ?>">
                </div>
                <div class="col-auto">
                    <label for="revenueUserEndDate" class="form-label mb-0 text-muted small">End date</label>
                    <input type="date" class="form-control" id="revenueUserEndDate" name="end_date" value="<?= $endDateValue; ?>" max="<?= date('Y-m-d'); ?>">
                </div>
                <div class="col-auto d-flex gap-2 pt-3 pt-md-4">
                    <button type="submit" class="btn btn-primary px-3">
                        <i class="bi bi-funnel me-1"></i>Filter
                    </button>
                    <a href="<?= htmlspecialchars(base_url('site/revenueByUser'), ENT_QUOTES, 'UTF-8'); ?>" class="btn btn-outline-secondary px-3">
                        <i class="bi bi-arrow-counterclockwise me-1"></i>Reset
                    </a>
                </div>
            </form>
        </div>

        <ul class="nav nav-tabs custom-tabs mb-4" role="tablist">
            <li class="nav-item" role="presentation">
                <a class="nav-link" href="<?= htmlspecialchars(base_url('site/revenue'), ENT_QUOTES, 'UTF-8'); ?>">
                    All Revenue
                </a>
            </li>
            <li class="nav-item" role="presentation">
                <span class="nav-link active" aria-current="page">Revenue by User</span>
            </li>
            <li class="nav-item" role="presentation">
                <a class="nav-link" href="<?= htmlspecialchars(base_url('site/revenueBreakdown'), ENT_QUOTES, 'UTF-8'); ?>">
                    Breakdown
                </a>
            </li>
            <li class="nav-item" role="presentation">
                <a class="nav-link" href="<?= htmlspecialchars(base_url('site/revenueCoins'), ENT_QUOTES, 'UTF-8'); ?>">
                    Coins
                </a>
            </li>
        </ul>

        <div class="alert alert-info d-flex align-items-center gap-2 py-2 px-3 mb-4">
            <i class="bi bi-lightbulb"></i>
            <span class="small mb-0">Each row below represents a unique host within the selected date range.</span>
        </div>

        <div class="row g-3 mb-4">
            <div class="col-lg-3 col-sm-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted text-uppercase fw-semibold small mb-1">Total Revenue</p>
                            <h3 class="mb-0">$<?= $currency($totalAmount); ?></h3>
                        </div>
                        <div class="avatar bg-primary bg-opacity-10 text-primary rounded-circle p-3">
                            <i class="bi bi-cash-stack fs-4"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-sm-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted text-uppercase fw-semibold small mb-1">Admin Share</p>
                            <h3 class="mb-0">$<?= $currency($totalAdminShare); ?></h3>
                        </div>
                        <div class="avatar bg-success bg-opacity-10 text-success rounded-circle p-3">
                            <i class="bi bi-briefcase fs-4"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-sm-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted text-uppercase fw-semibold small mb-1">User Share</p>
                            <h3 class="mb-0">$<?= $currency($totalUserShare); ?></h3>
                        </div>
                        <div class="avatar bg-warning bg-opacity-10 text-warning rounded-circle p-3">
                            <i class="bi bi-people fs-4"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-sm-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted text-uppercase fw-semibold small mb-1">Unique Hosts</p>
                            <h3 class="mb-0"><?= number_format($uniqueHosts); ?></h3>
                            <small class="text-muted">Across <?= number_format($transactionCount); ?> transactions</small>
                        </div>
                        <div class="avatar bg-info bg-opacity-10 text-info rounded-circle p-3">
                            <i class="bi bi-person-badge fs-4"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-3 mb-4">
            <div class="col-lg-4 col-md-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <?php $avgRevenuePerHost = $uniqueHosts > 0 ? $totalAmount / $uniqueHosts : 0; ?>
                        <h6 class="text-muted text-uppercase small mb-2">Average Revenue per Host</h6>
                        <h3 class="fw-semibold">$<?= $currency($avgRevenuePerHost); ?></h3>
                        <p class="text-muted small mb-0">Helps benchmark host performance.</p>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 col-md-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <?php $avgCoinsPerHost = $uniqueHosts > 0 ? $totalCoins / $uniqueHosts : 0; ?>
                        <h6 class="text-muted text-uppercase small mb-2">Average Coins per Host</h6>
                        <h3 class="fw-semibold"><?= number_format($avgCoinsPerHost, 2); ?></h3>
                        <p class="text-muted small mb-0">Coin distribution across active hosts.</p>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 col-md-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <?php $avgTransactionsPerHost = $uniqueHosts > 0 ? $transactionCount / $uniqueHosts : 0; ?>
                        <h6 class="text-muted text-uppercase small mb-2">Transactions per Host</h6>
                        <h3 class="fw-semibold"><?= number_format($avgTransactionsPerHost, 2); ?></h3>
                        <p class="text-muted small mb-0">Workload spread among hosts.</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-bottom-0 d-flex justify-content-between align-items-center">
                <div>
                    <h5 class="mb-0">Host Revenue Summary</h5>
                    <small class="text-muted">Aggregated metrics for each host in the selected period.</small>
                </div>
            </div>
            <?php if (empty($hostBreakdown)): ?>
                <div class="card-body text-center text-muted py-5">
                    <i class="bi bi-person-x fs-1 d-block mb-3"></i>
                    No host activity recorded for this period.
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover table-nowrap mb-0 align-middle">
                        <thead class="bg-light">
                            <tr>
                                <th class="text-muted text-uppercase small">Host</th>
                                <th class="text-muted text-uppercase small">Transactions</th>
                                <th class="text-muted text-uppercase small">Coins</th>
                                <th class="text-muted text-uppercase small">Total Revenue</th>
                                <th class="text-muted text-uppercase small">Admin Share</th>
                                <th class="text-muted text-uppercase small">User Share</th>
                                <th class="text-muted text-uppercase small">Last Activity</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($hostBreakdown as $host): ?>
                                <?php
                                    $hostName = htmlspecialchars($host['hostName'] ?? 'Unknown host', ENT_QUOTES, 'UTF-8');
                                    $hostId = htmlspecialchars($host['hostId'] ?? '', ENT_QUOTES, 'UTF-8');
                                    $lastActivity = isset($host['lastTransaction']) && $host['lastTransaction'] > 0
                                        ? date('M j, Y g:i A', $host['lastTransaction'] / 1000)
                                        : '—';
                                ?>
                                <tr>
                                    <td>
                                        <div class="d-flex flex-column">
                                            <span class="fw-semibold"><?= $hostName; ?></span>
                                            <?php if (!empty($hostId)): ?>
                                                <small class="text-muted"><?= $hostId; ?></small>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td><?= number_format((int)($host['transactions'] ?? 0)); ?></td>
                                    <td><?= number_format((int)($host['totalCoins'] ?? 0)); ?></td>
                                    <td>$<?= $currency($host['totalAmount'] ?? 0); ?></td>
                                    <td>$<?= $currency($host['totalAdminShare'] ?? 0); ?></td>
                                    <td>$<?= $currency($host['totalUserShare'] ?? 0); ?></td>
                                    <td><?= htmlspecialchars($lastActivity, ENT_QUOTES, 'UTF-8'); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <div class="row g-3">
            <div class="col-xl-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-white border-bottom-0">
                        <h5 class="mb-0">Top Hosts by Revenue</h5>
                        <small class="text-muted">Highlighting the highest-earning hosts.</small>
                    </div>
                    <?php if (empty($hostBreakdown)): ?>
                        <div class="card-body text-center text-muted py-4">No data available.</div>
                    <?php else: ?>
                        <div class="card-body p-0">
                            <ul class="list-group list-group-flush">
                                <?php
                                    $topRevenueHosts = $hostBreakdown;
                                    usort($topRevenueHosts, static function ($a, $b) {
                                        return ($b['totalAmount'] ?? 0) <=> ($a['totalAmount'] ?? 0);
                                    });
                                    $topRevenueHosts = array_slice($topRevenueHosts, 0, 5);
                                ?>
                                <?php foreach ($topRevenueHosts as $host): ?>
                                    <?php
                                        $hostName = htmlspecialchars($host['hostName'] ?? 'Unknown host', ENT_QUOTES, 'UTF-8');
                                        $hostId = htmlspecialchars($host['hostId'] ?? '', ENT_QUOTES, 'UTF-8');
                                    ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <div>
                                            <span class="fw-semibold"><?= $hostName; ?></span>
                                            <?php if (!empty($hostId)): ?>
                                                <small class="d-block text-muted"><?= $hostId; ?></small>
                                            <?php endif; ?>
                                        </div>
                                        <span class="badge bg-success-subtle text-success">$<?= $currency($host['totalAmount'] ?? 0); ?></span>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="col-xl-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-white border-bottom-0">
                        <h5 class="mb-0">Top Hosts by Coins</h5>
                        <small class="text-muted">Track engagement based on coin totals.</small>
                    </div>
                    <?php if (empty($hostBreakdown)): ?>
                        <div class="card-body text-center text-muted py-4">No data available.</div>
                    <?php else: ?>
                        <div class="card-body p-0">
                            <ul class="list-group list-group-flush">
                                <?php
                                    $topCoinHosts = $hostBreakdown;
                                    usort($topCoinHosts, static function ($a, $b) {
                                        return ($b['totalCoins'] ?? 0) <=> ($a['totalCoins'] ?? 0);
                                    });
                                    $topCoinHosts = array_slice($topCoinHosts, 0, 5);
                                ?>
                                <?php foreach ($topCoinHosts as $host): ?>
                                    <?php
                                        $hostName = htmlspecialchars($host['hostName'] ?? 'Unknown host', ENT_QUOTES, 'UTF-8');
                                        $hostId = htmlspecialchars($host['hostId'] ?? '', ENT_QUOTES, 'UTF-8');
                                    ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <div>
                                            <span class="fw-semibold"><?= $hostName; ?></span>
                                            <?php if (!empty($hostId)): ?>
                                                <small class="d-block text-muted"><?= $hostId; ?></small>
                                            <?php endif; ?>
                                        </div>
                                        <span class="badge bg-primary-subtle text-primary"><?= number_format((int)($host['totalCoins'] ?? 0)); ?> coins</span>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</main>

