<?php

$comments = $db->run("SELECT COUNT(*) as count, comment.createdByName FROM comment WHERE comment.createdByName > '' GROUP BY createdByName");
$replies  = $db->run("SELECT COUNT(*) as count, comment.userId, user.name FROM comment, user WHERE comment.userId > '' AND comment.userId = user.id GROUP BY comment.userId");

$cNames = array_column($comments, 'createdByName');
$rNames = array_column($replies, 'name');

$names = array_unique(array_merge($cNames, $rNames));
$labels = "'";
$labels .= implode("','", $names);
$labels .= "'";

$array = [];
$commentsData = '';
$repliesData  = '';
foreach ( $names as $name ) {
    $array[$name]['comments'] = $db->cell("SELECT COUNT(*) as count FROM comment WHERE createdByName = ?", $name);
    $commentsData .= $array[$name]['comments'] ?? "''";
    $commentsData .= ',';

    $array[$name]['replies']  = $db->cell("SELECT COUNT(*) as count, user.name FROM comment, user WHERE comment.userId = user.id AND user.name = ?", $name);
    $repliesData .= $array[$name]['replies'] ?? "''";
    $repliesData .= ',';

    $array[$name]['client'] = ( $db->cell("SELECT clientId FROM user WHERE name = ?", $name) ) ? true : false;
}

?>

<script>
    function getCommentData(name, page = 1) {
        $.ajax({
            url: '/clients/analytics/ajax/chart-comments.php',
            method: 'GET',
            dataType: 'html',
            data: {
                name: name,
                page: page
            },
            success: function (data) {
                console.log(data);
                $('#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: [
                {
                    backgroundColor: '#dc3545',
                    borderWidth: 1,
                    data: [<?php echo $commentsData; ?>],
                    label: "# Comments",
                    stack: "Stack 0"
                },
                {
                    backgroundColor: '#198754',
                    borderWidth: 1,
                    data: [<?php echo $repliesData; ?>],
                    label: "# Replies",
                    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;
                        },
                    },
                    legend: {
                        // display: true,
                        position: 'bottom',
                        onClick: function() { return; }
                    },
                },
                scales: {
                    x: {
                        beginAtZero: true,
                        color: 'blue',
                        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('Comments & Replies');
            $('#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;
            }
            
            getCommentData(name, 1);
        };

        $(document).on('click', '.paginationItem', function(e) {
            getCommentData($(this).data('name'), $(this).data('page'));
        });
    });
</script>