$(document).ready(function() {

    // Initialize jQuery DateTimePicker
    $(".date_class").datetimepicker({
        format: 'Y-m-d H:i:s',   // set format for backend
        step: 1                  // allow seconds
    });

    // Set default today values
    const now = new Date();
    const pad = n => n.toString().padStart(2, '0');

    const todayYMD = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}`;
    const startOfDay = `${todayYMD} 00:00:00`;
    const endOfDay   = `${todayYMD} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;

    $("#fromDate").val(startOfDay);
    $("#toDate").val(endOfDay);

    // Function to fetch and update stats
    function fetchCaseSummary() {
        const fromDate = $("#fromDate").val();
        const toDate = $("#toDate").val();

        $.ajax({
            url: "Dashboard/dashboardFunctions.php",
            type: "POST",
            dataType: "json",
            data: { from: fromDate, to: toDate },
            beforeSend: function () {
                $("#filterBtn").prop("disabled", true).text("Loading...");
            },
            success: function (res) {
                if (res.success && res.data) {
                    $("#totalCases").text(res.data.total || 0);
                    $("#complaints").text(res.data.complaints || 0);
                    $("#enquiries").text(res.data.enquiries || 0);
                    $("#others").text(res.data.others || 0);
                    $("#active").text(res.data.active || 0);
                    $("#resolved").text(res.data.resolved || 0);
                    $("#cancelled").text(res.data.cancelled || 0);
                    // FCR by source
                    // updated js code for fcr and non fcr cases [vastvikta][01-12-2025]
                    $("#fcr_phone .value").text(res.data.fcr_phone || 0);
                    $("#fcr_walkin .value").text(res.data.fcr_walkin || 0);
                    $("#fcr_x .value").text(res.data.fcr_x || 0);
                    $("#fcr_mail .value").text(res.data.fcr_mail || 0);
                    $("#fcr_messenger .value").text(res.data.fcr_messenger || 0);

                    // Non-FCR by source
                    $("#nonfcr_phone .value").text(res.data.nonfcr_phone || 0);
                    $("#nonfcr_walkin .value").text(res.data.nonfcr_walkin || 0);
                    $("#nonfcr_x .value").text(res.data.nonfcr_x || 0);
                    $("#nonfcr_mail .value").text(res.data.nonfcr_mail || 0);
                    $("#nonfcr_messenger .value").text(res.data.nonfcr_messenger || 0);

                    // $("#inprogress").text(res.data.inprogress || 0);
                    // $("#waiting").text(res.data.waiting || 0);
                    // $("#onhold").text(res.data.onhold || 0);
                    // $("#research").text(res.data.research || 0);
                    // $("#resolved").text(res.data.resolved || 0);
                    // $("#active").text(res.data.resolved || 0);
                    // $("#resolved").text(res.data.resolved || 0);
                    // $("#cancelled").text(res.data.resolved || 0);

                    // Use PHP formatted TAT or calculate here
                    let formattedTAT = '00:00:00';
                    if (res.data.avg_tat_formatted) {
                        formattedTAT = res.data.avg_tat_formatted;
                    } else if (res.data.avg_tat_seconds) {
                        let totalSeconds = parseInt(res.data.avg_tat_seconds, 10);
                        let h = Math.floor(totalSeconds / 3600);
                        let m = Math.floor((totalSeconds % 3600) / 60);
                        let s = totalSeconds % 60;
                        formattedTAT = [h, m, s].map(v => v.toString().padStart(2, '0')).join(':');
                    }

                    $("#avgtat").text(formattedTAT);
                    $("#avgresolution").text(formattedTAT);
                    // Format FCR rate in JS
                    let fcrRate = parseFloat(res.data.fcr_rate) || 0; // safe if null/NaN
                    fcrRate = fcrRate.toFixed(2) + '%';
                    $("#fcrrate").text(fcrRate || "0%");
                } else {
                    $(".fw-bold.mb-0").text("0");
                }
            },
            error: function (xhr, status, error) {
                console.error("AJAX Error:", error);
                alert("Something went wrong while fetching data.");
            },
            complete: function () {
                $("#filterBtn").prop("disabled", false).text("Submit");
            }
        });
    }

    function fetchCharts() {
      const fromDate = $("#fromDate").val();
      const toDate = $("#toDate").val();

      $.ajax({
          url: "Dashboard/dashboardCharts.php",
          type: "POST",
          dataType: "json",
          data: { from: fromDate, to: toDate },
          success: function (res) {
          if (res.success) {
                    // ==== Product Chart FIX (final clean version) ====
                    const productLabels = res.products.map(p => p.productName || 'Unknown');
                    const productCounts = res.products.map(p => parseInt(p.total));

                    // destroy properly
                    if (productChart) {
                        productChart.destroy();
                    }

                    // get fresh context (important)
                    const productCtx = document.getElementById('productChart').getContext('2d');

                    productChart = new Chart(productCtx, {
                        type: 'pie',
                        data: {
                            labels: productLabels,
                            datasets: [{
                                data: productCounts
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: 'bottom',   // 👈 FIX
                                    labels: {
                                        boxWidth: 12
                                    }
                                }
                            }
                        }
                    });

                    // ==== Department Chart (unchanged) ====
                    const deptLabels = res.departments.map(d => d.department || 'Unknown');
                    const deptCounts = res.departments.map(d => parseInt(d.total));

                    departmentChart.data.labels = deptLabels;
                    departmentChart.data.datasets[0].data = deptCounts;
                    departmentChart.update();

                } else {
                    console.warn("No chart data found:", res.message);
                }
          },
          error: function (xhr, status, error) {
              console.error("Chart AJAX error:", error);
          }
      });
    }



    // Fetch today's cases on page load
    fetchCaseSummary();
    fetchCharts();

    // Fetch on Submit click
    $("#filterBtn").on("click", function() {
        fetchCaseSummary();
        fetchCharts();
    });
});


// Bar Chart - Products
// ✅ FIXED Product Chart (proper pie config like department)

const ctxProduct = document.getElementById('productChart');

let productChart = new Chart(ctxProduct, {
    type: 'pie',
    data: {
        labels: [],
        datasets: [{
            data: [],
            backgroundColor: [
                '#4e79a7','#f28e2b','#e15759','#76b7b2','#59a14f',
                '#edc949','#af7aa1','#ff9da7','#9c755f','#bab0ab'
            ]
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: true,
                position: 'top'
            }
        }
    }
});

const ctxDept = document.getElementById('departmentChart');
const departmentChart = new Chart(ctxDept, {
    type: 'pie',
    data: {
        labels: [],
        datasets: [{
            data: [],
            backgroundColor: ['#267a3f', '#d79b00', '#804c57', '#4c678a', '#093553'],
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { position: 'bottom' }
        }
    }
});
