<?php
    $tasks = $db->run("SELECT *, COUNT(*) AS numTasks FROM task WHERE status > '' AND status != 'Daily Log' 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'];
        }
    }

    foreach ( $totalTasks as $key => $value ) {
        $totalTasks[$key] = $totalTasks[$key] - 21;
    }

// echo "Total Tasks:<pre>";
// print_r($totalTasks);
// echo "</pre>";

// echo "Completed Tasks:<pre>";
// print_r($completedTasks);
// echo "</pre>";

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

// echo "Proportion:<pre>";
// print_r($proportionCompletedTasks);
// echo "</pre>";

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

    $tasksData = implode(',', $proportionCompletedTasks);
?>

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

        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>