<?php
    $likes = $db->run("SELECT COUNT(thumb.id) AS count, thumb.userId, user.name FROM thumb, user WHERE thumb.userId = user.id AND user.clientId > 0 GROUP BY thumb.userId ORDER BY count DESC");

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

    $likesData = implode(',', array_column($likes, 'count'));
?>

<script>
    function getUserLikesData(name) {
        $.ajax({
            url: '/clients/analytics/ajax/chart-likes.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('chartCanvas');

        const set = {
            labels: [<?php echo $labels; ?>],
            datasets: [
                {
                    label: '# Likes',
                    backgroundColor: '#dc3545',
                    borderWidth: 1,
                    data: [<?php echo $likesData; ?>],
                    // stack: "Stack 0"
                }
            ]
        }

        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>