<?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'));
?>
<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>Likes Per Client</h1>

        <div class="row">
            <div class="col-12 col-lg-6">
                <canvas id="likesBarChart" 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-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('likesBarChart');

                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>
        <script src="<?php echo URL_ASSETS; ?>/js/bootstrap.bundle.min.js"></script>
    </body>
</html>