<?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 .= "'";
    // echo $labels."<br>";

    $array = [];
    $commentsData = '';
    $repliesData  = '';
    foreach ( $names as $name ) {
        // echo $name."<br>";
        $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;
    }

    // if ( count($comments) > count($replies) ) {
    //     $diff = count($comments) - count($replies);
    //     $pad  = 'repliesData';
    // } elseif ( count($comments) == count($replies) ) {
    //     $pad = false;
    // } else {
    //     $diff = count($replies) - count($comments);
    //     $pad  = 'commentsData';
    // }

    // $commentsData   = '';
    // foreach ( $comments as $comment ) {
    //     $commentsData .= $comment['count'].',';
    // }

    // $repliesData   = '';
    // foreach ( $replies as $reply ) {
    //     $repliesData .= $reply['count'].',';
    // }

    // if ( $pad ) {
    //     // if ( $pad == 'repliesData' ) {
    //         //add to repliesData
    //     // } else {
    //         for ( $i = 0; $i < $diff; $i++ ) {
    //             $$pad .= '0,';
    //         }
    //     // }
    // }
?>
<pre>
    <?php //echo $labels; ?>
</pre>
<pre>
    <?php //print_r($comments); ?>
</pre>
<pre>
    <?php //print_r($replies); ?>
</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>Comments & Replies Per User</h1>



        <div class="container-fluid my-5">
            <div class="card">
            <div class="card-header"><h5 class="mb-0">Comments & Replies</h5></div>
                <div class="card-body p-5">
                    <canvas id="commentsAndRepliesChart" style="overflow-y:visible;"></canvas>
                </div>
            </div>
        </div>

        <div id="dataModal" class="modal" tabindex="-1">
            <div class="modal-dialog modal-dialog-scrollable modal-lg">
                <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 px-0">
                        
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    
        <script>
            function getCommentData(name, page = 1) {
                $.ajax({
                    url: '/clients/admin/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('commentsAndRepliesChart');

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