<?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);

        $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);
        echo "user: $portalUser[name], numViews: $numPageViews, numDays: $difference->days, avg: $avg<br><br>";
    }

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

    $avgData = "'";
    $avgData .= implode("','", $avgs);
    $avgData .= "'";
?>
<pre>
    <?php //echo $labels; ?>
</pre>
<pre>
    <?php //print_r($totalTasks); ?>
</pre>
<pre>
    <?php //print_r($completedTasks); ?>
</pre>
<pre>
    <?php //print_r($proportionCompletedTasks); ?>
</pre>

<!doctype html>
<html lang="en" data-bs-theme="dark">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Charts</title>

        <link href="<?php echo URL_ASSETS; ?>/css/bootstrap.min.css" rel="stylesheet">
        <link href="<?php echo URL_ASSETS; ?>/css/clients.css" rel="stylesheet">

        <script src="<?php echo URL_ASSETS; ?>/js/chartjs/chart.umd.js"></script>
        <script src="<?php echo URL_ASSETS; ?>/js/chartjs/chartjs-plugin-datalabels.min.js"></script>

        <script src="<?php echo URL_ASSETS; ?>/js/jquery.js"></script>
    </head>
    <body>
        <h1>Average Visits Per Day</h1>

        <div class="row">
            <div class="col-12 col-lg-6">
                <canvas id="visitsPieChart" style="overflow-y:visible;"></canvas>
            </div>
            <div class="col-12 col-lg-6">

            </div>
        </div>

        <div id="dataModal" class="modal" tabindex="-1">
            <div class="modal-dialog modal-dialog-scrollable modal-xl">
                <div class="modal-content">
                    <div class="modal-header">
                        <div class="d-block">
                            <h5 id="dataModalTitle" class="modal-title">Data</h5>
                            <!-- <small class="text-muted">Showing last 100 actions</small> -->
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div id="dataModalBody" class="modal-body p-2">
                        
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    
        <script>
            // function getUserLikesData(name) {
            //     $.ajax({
            //         url: '/clients/admin/ajax/chart-days.php',
            //         method: 'GET',
            //         dataType: 'html',
            //         data: {
            //             name: name
            //         },
            //         success: function (data) {
            //             // console.log(data);
            //             $('#dataModalTitle').text(name+' Likes');
            //             $('#dataModalBody').html(data);
            //         },
            //         error: function (e) {
            //             // var error = e.responseJSON.error;
            //             // console.log(error);
            //         }
            //     });
            // }

            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('visitsPieChart');

                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; }
                            },
                            // tooltip: {
                            //     callbacks: {
                            //         label: function(context) {
                            //             let label = context.dataset.label;
                            //             label += "\n10 Actions, 5 Days";
                            //             return label;
                            //         }
                            //     }
                            // }
                        },
                    },
                });
                
                ctx.onclick = ( evt ) => {
                    // const res = chart.getElementsAtEventForMode(
                    //     evt,
                    //     'nearest',
                    //     { intersect: true },
                    //     true
                    // );
                    // if ( res.length === 0 ) {
                    //     return;
                    // }

                    // $('#dataModalTitle').text('User Likes');
                    // $('#dataModalBody').html(loader);
                    // dataModal.show();
                    // // console.log(res);
                    // // alert('You clicked on ' + chart.data.labels[res[0].index]); //label at position index. e.g. "robert lambert"
                    // let name = chart.data.labels[res[0].index];
                    // if ( !name ) {
                    //     return;
                    // }
                    
                    // getUserLikesData(name);
                };
            });
        </script>
        <script src="<?php echo URL_ASSETS; ?>/js/bootstrap.bundle.min.js"></script>
    </body>
</html>