let hoursChart = null;
let leavesChart = null;
let workdaysChart = null;

const donutCtxLeaves = document.getElementById('leavesChart').getContext('2d');
const donutCtxWorkdays = document.getElementById('workdaysChart').getContext('2d');

function loadGraphs(empIds) {

    fetch('api/get-employee-hours.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ emp_ids: empIds })  // expecting array of emp_ids
    })
        .then(response => response.json())
        .then(data => {
            const weekDays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
            const labels = weekDays;
            const hoursData = weekDays.map(day => parseFloat(data[day] ?? 0)); // from avg map returned

            if (hoursChart) {
                hoursChart.destroy();
            }

            hoursChart = new Chart(document.getElementById('hoursChart'), {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Avg Hours Worked',
                        data: hoursData,
                        backgroundColor: 'rgba(54, 162, 235, 0.4)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 2,
                        fill: true,
                        tension: 0.4
                    }]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true,
                            min: 0,
                            suggestedMax: 9,
                            ticks: {
                                stepSize: 0.5,
                                precision: 1
                            }
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function (context) {
                                    return `${context.dataset.label}: ${context.parsed.y.toFixed(1)} hrs`;
                                }
                            }
                        }
                    }
                }
            });
        })
        .catch(error => console.error('Error loading hours chart:', error));


    fetch('api/get-employee-leaves.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ emp_ids: empIds })
    })
        .then(res => res.json())
        .then(data => {
            if (data.error) {
                console.error('Leaves API error:', data.error);
                return;
            }

            const taken = data.total_leaves_taken || 0;
            const total = data.total_possible_leaves || 1;
            const remaining = total - taken;

            if (leavesChart) {
                leavesChart.destroy();
            }

            leavesChart = new Chart(donutCtxLeaves, {
                type: 'doughnut',
                data: {
                    labels: [
                        `Leaves Taken (${taken})`,
                        // `Remaining Leaves (${remaining})`
                    ],
                    datasets: [{
                        data: [taken, remaining],
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.8)',
                            'rgba(100, 255, 100, 0.5)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(100, 255, 100, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    cutout: '70%',
                    plugins: {
                        legend: {
                            display: true,
                            position: 'bottom'
                        },
                        tooltip: {
                            callbacks: {
                                label: function (context) {
                                    return `${context.label}: ${context.parsed} day${context.parsed !== 1 ? 's' : ''}`;
                                }
                            }
                        }
                    }
                }
            });
        })
        .catch(err => console.error('Error loading leaves data:', err));

    // fetch(`api/get-employee-leaves.php?emp_id=${empId}`)
    //     .then(res => res.json())
    //     .then(data => {
    //         const leaves = data.leaves || 0;
    //         const total = data.total_allocated_leaves || 22; // fallback
    //         const available = total - leaves;

    //         if (leavesChart) {
    //             leavesChart.destroy();
    //         }

    //         leavesChart = new Chart(donutCtxLeaves, {
    //             type: 'doughnut',
    //             data: {
    //                 labels: [
    //                     `Leaves Taken (${leaves})`
    //                     // `Leaves Remaining (${available})`
    //                 ],
    //                 datasets: [{
    //                     data: [leaves, available],
    //                     backgroundColor: [
    //                         'rgba(255, 99, 132, 0.8)',
    //                         'rgba(100, 255, 100, 0.5)'
    //                     ],
    //                     borderColor: [
    //                         'rgba(255, 99, 132, 1)',
    //                         'rgba(100, 255, 100, 1)'
    //                     ],
    //                     borderWidth: 1
    //                 }]
    //             },
    //             options: {
    //                 cutout: '70%',
    //                 plugins: {
    //                     legend: {
    //                         display: true,
    //                         position: 'bottom'
    //                     },
    //                     tooltip: {
    //                         callbacks: {
    //                             label: function (context) {
    //                                 return `${context.label}: ${context.parsed} day${context.parsed !== 1 ? 's' : ''}`;
    //                             }
    //                         }
    //                     }
    //                 }
    //             }
    //         });
    //     })
    //     .catch(err => console.error('Error loading leaves data:', err));




    // fetch(`api/get-employee-workdays.php?emp_id=${empId}`)
    //     .then(res => res.json())
    //     .then(data => {
    //         const worked = data.days_worked;
    //         const total = data.total_working_days;
    //         const remaining = total - worked;

    //         if (workdaysChart) {
    //             workdaysChart.destroy();
    //         }
    //         workdaysChart = new Chart(donutCtxWorkdays, {
    //             type: 'doughnut',
    //             data: {
    //                 labels: [
    //                     `Days Worked (${worked} / ${total})`,
    //                     `Remaining Days (${remaining})`
    //                 ],
    //                 datasets: [{
    //                     data: [worked, remaining],
    //                     backgroundColor: [
    //                         'rgba(243, 135, 255, 0.8)',
    //                         'rgba(200, 200, 200, 0.5)'
    //                     ],
    //                     borderColor: [
    //                         'rgba(243, 135, 255, 1)',
    //                         'rgba(200, 200, 200, 1)'
    //                     ],
    //                     borderWidth: 1
    //                 }]
    //             },
    //             options: {
    //                 cutout: '70%',
    //                 plugins: {
    //                     legend: {
    //                         display: true,
    //                         position: 'bottom'
    //                     },
    //                     tooltip: {
    //                         callbacks: {
    //                             label: function (context) {
    //                                 return `${context.label}: ${context.parsed} day${context.parsed !== 1 ? 's' : ''}`;
    //                             }
    //                         }
    //                     }
    //                 }
    //             }
    //         });
    //     })
    //     .catch(err => console.error('Error loading working days data:', err));

    const idParam = empIds.join(',');

    fetch(`api/get-employee-workdays.php?emp_ids=${idParam}`)
        .then(res => res.json())
        .then(data => {
            const worked = data.days_worked;
            // data.total_working_days
            const countEmployees = data.total_employees;
            // console.log(daysInThisMonth());
            const totalWorkingDays = daysInThisMonth() * countEmployees;
            const remaining = totalWorkingDays - worked;

            if (workdaysChart) {
                workdaysChart.destroy();
            }

            workdaysChart = new Chart(donutCtxWorkdays, {
                type: 'doughnut',
                data: {
                    labels: [
                        `Total Days Worked (${worked} / ${totalWorkingDays})`,
                        `Remaining Days (${remaining})`
                    ],
                    datasets: [{
                        data: [worked, remaining],
                        backgroundColor: [
                            'rgba(243, 135, 255, 0.8)',
                            'rgba(200, 200, 200, 0.5)'
                        ],
                        borderColor: [
                            'rgba(243, 135, 255, 1)',
                            'rgba(200, 200, 200, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    cutout: '70%',
                    plugins: {
                        legend: {
                            display: true,
                            position: 'bottom'
                        },
                        tooltip: {
                            callbacks: {
                                label: function (context) {
                                    return `${context.label}: ${context.parsed} day${context.parsed !== 1 ? 's' : ''}`;
                                }
                            }
                        }
                    }
                }
            });
        })
        .catch(err => console.error('Error loading working days data:', err));
}

function daysInThisMonth() {
    var now = new Date();
    return new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
}