<?php
    $tasks = $db->run("SELECT *, COUNT(*) AS numTasks FROM task WHERE status != 'N/A' AND status > '' GROUP BY status, projectId");
    $projectIds = array_unique(array_column($tasks, 'projectId'));

    $totalTasks = [];
    $completedTasks = [];
    foreach ( $tasks as $task ) {
        $totalTasks[$task['projectId']] += $task['numTasks'];
        if ( $task['status'] == 'Completed' ) {
            $completedTasks[$task['projectId']] += $task['numTasks'];
        }
    }

    $proportionCompletedTasks = [];
    for ( $i = 1; $i <= max(array_keys($totalTasks)); $i++ ) {
        // echo "$i<br>";
        if ( $totalTasks[$i] ) {
            $proportionCompletedTasks[$i] = round($completedTasks[$i] / $totalTasks[$i] * 100, 1);
        }
    }

    $projectTitles = $db->run("SELECT id, title FROM project");
    $titles = array_column($projectTitles, 'title');
    $labels = "'";
    $labels .= implode("','", $titles);
    $labels .= "'";

    $tasksData = implode(',', $proportionCompletedTasks);
?>
<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>Tasks Per Project</h1>

        <div class="row">
            <div class="col-12 col-lg-6">
                <canvas id="tasksPieChart" 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 getProjectTaskData(projectTitle) {
                $.ajax({
                    url: '/clients/admin/ajax/chart-tasks.php',
                    method: 'GET',
                    dataType: 'html',
                    data: {
                        projectTitle: projectTitle
                    },
                    success: function (data) {
                        // console.log(data);
                        $('#dataModalTitle').text(projectTitle+' Tasks');
                        $('#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('tasksPieChart');

                const set = {
                    labels: [<?php echo $labels; ?>],
                    datasets: [
                        {
                            backgroundColor: '#dc3545',
                            borderWidth: 1,
                            data: [<?php echo $tasksData; ?>],
                            backgroundColor: [
                                'red',
                                'green',
                                'blue',
                                'purple',
                                'orange',
                                'yellow',
                                'brown',
                                'black',
                                'aqua',
                                'khaki',
                                'gainsboro'
                            ],
                            label: "% Tasks Completed"
                        }
                    ]
                }

                const chart = new Chart(ctx, {
                    // plugins: [ChartDataLabels],
                    type: 'pie',
                    data: set,
                    options: {
                        plugins: {
                            legend: {
                                onClick: function() { return; }
                            }
                        },
                    },
                });
                
                ctx.onclick = ( evt ) => {
                    const res = chart.getElementsAtEventForMode(
                        evt,
                        'nearest',
                        { intersect: true },
                        true
                    );
                    if ( res.length === 0 ) {
                        return;
                    }

                    $('#dataModalTitle').text('Project Tasks');
                    $('#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 title = chart.data.labels[res[0].index];
                    if ( !title ) {
                        return;
                    }
                    
                    getProjectTaskData(title);
                };
            });
        </script>
        <script src="<?php echo URL_ASSETS; ?>/js/bootstrap.bundle.min.js"></script>
    </body>
</html>