<?php
    $portalUsers = $db->run("SELECT * FROM user WHERE clientId > 0");

    $avgs = [];
    foreach ( $portalUsers as $portalUser ) {
        $today   = new DateTime(date('Y-m-d', time()));
        $created = new DateTime(explode(' ', $portalUser['createdAt'])[0]);
        $difference = ( $created->diff($today) < 1 )
            ? 1
            : $created->diff($today)
        ;
echo $difference.'<br>';
        $numPageViews = $db->cell("SELECT COUNT(*) FROM action WHERE userId = ? AND action = 'pageview' AND target NOT LIKE '%ajax%'", $portalUser['id']);
        $avgs[] = round($numPageViews / $difference->days, 1);
    }

    $names = array_column($portalUsers, 'name');
    $labels = "'";
    $labels .= implode("','", $names);
    $labels .= "'";

    $avgData = "'";
    $avgData .= implode("','", $avgs);
    $avgData .= "'";
?>

<script>
    document.addEventListener("DOMContentLoaded", () => {
        const loader = '<div class="d-flex"><div class="spinner-border text-danger" role="status"><span class="visually-hidden">Loading...</span></div></div>';
        const dataModal = new bootstrap.Modal('#dataModal');

        const ctx = document.getElementById('chartCanvas');

        const set = {
            labels: [<?php echo $labels; ?>],
            datasets: [
                {
                    borderWidth: 1,
                    data: [<?php echo $avgData; ?>],
                    label: "Average # Visits Per Day",
                    backgroundColor: [
                        'red',
                        'green',
                        'blue',
                        'purple',
                        'orange',
                        'yellow',
                        'brown',
                        'black',
                        'aqua',
                        'khaki',
                        'gainsboro'
                    ]
                }
            ]
        }

        const chart = new Chart(ctx, {
            type: 'pie',
            data: set,
            options: {
                plugins: {
                    legend: {
                        onClick: function() { return; }
                    },
                },
            },
        });
        
        ctx.onclick = ( evt ) => {

        };
    });
</script>