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

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

    $daysSinceCreated = [];
    $daysLoggedIn     = [];
    foreach ( $users as $user ) {
        $today   = new DateTime(date('Y-m-d', time()));
        $created = new DateTime(explode(' ', $user['createdAt'])[0]);
        $difference = $created->diff($today);
        $daysSinceCreated[] = $difference->days;

        $result = $db->run("SELECT DISTINCT SUBSTRING(createdAt, 1, 10) FROM action WHERE userId = ?", $user['id']);
        $daysLoggedIn[] = count($result);
    }

    $daysSinceData = "'";
    $daysSinceData .= implode("','", $daysSinceCreated);
    $daysSinceData .= "'";

    $daysLoggedInData = "'";
    $daysLoggedInData .= implode("','", $daysLoggedIn);
    $daysLoggedInData .= "'";
?>

<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: [
                {
                    backgroundColor: '#dc3545',
                    borderWidth: 1,
                    data: [<?php echo $daysSinceData; ?>],
                    label: "# Days Since Created",
                    stack: "Stack 0"
                },
                {
                    backgroundColor: '#198754',
                    borderWidth: 1,
                    data: [<?php echo $daysLoggedInData; ?>],
                    label: "# Days Logged In",
                    stack: "Stack 1"
                }
            ]
        }

        const chart = new Chart(ctx, {
            plugins: [ChartDataLabels],
            type: 'bar',
            data: set,
            options: {
                plugins: {
                    datalabels: {
                        align: 'start',
                        anchor: 'end',
                        color: function() {
                            return ( document.documentElement.dataset.bsTheme == 'light' )
                                ? 'black' //light color
                                : 'white' //dark color
                            ;
                        },
                        display: function(context) {
                            return context.dataset.data[context.dataIndex] > 0; // or >= 1 or ...
                        },
                        font : {
                            size: 14,
                            weight: 'bold',
                        },
                        offset: function(context) {
                            // var value = context.dataset.data[context.dataIndex];
                            // return ( value < 5 ) ? -15 : -10;
                            return -17;
                        },
                    },
                    legend: {
                        // display: true,
                        position: 'bottom',
                        onClick: function() { return; }
                    },
                },
                scales: {
                    x: {
                        beginAtZero: true,
                        grid: {
                            color: function(context) {
                                return ( document.documentElement.dataset.bsTheme == 'light' )
                                    ? 'gray' //light color
                                    : 'gray' //dark color
                                ;
                            }
                        }
                    },
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: function() {
                                return ( document.documentElement.dataset.bsTheme == 'light' )
                                    ? 'gray' //light color
                                    : 'gray' //dark color
                                ;
                            }
                        }
                    }
                },
            },
        });
        
        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>