// Initialize all tables with class "datatable-init" or by ID loop
document.querySelectorAll('table[id^="table"]').forEach(table => {
    new simpleDatatables.DataTable(table, {
        searchable: true,
        fixedHeight: false,
        perPage: 10
    });
});

// document.addEventListener('DOMContentLoaded', function() {
//     const truckSelect = document.getElementById('truck_license-colum');
//     const driverInput = document.getElementById('driver_id_colum');

//     truckSelect.addEventListener('change', function() {
//         const selectedOption = truckSelect.options[truckSelect.selectedIndex];
//         const selectedDriverId = selectedOption.getAttribute('data-driver-id');
//         driverInput.value = selectedDriverId;        
//     });
// });

$(document).ready(function () {
const customerSelect = document.getElementById('customer-colum');
const locationInput = document.getElementById('location-column');

customerSelect.addEventListener('change', function() {
    const selectedId = this.value;
    if (customerMap.hasOwnProperty(selectedId)) {
        locationInput.value = customerMap[selectedId].address;
    } else {
        locationInput.value = '';
    }
});
});


document.addEventListener('DOMContentLoaded', function() {
    const truckSelects = document.querySelectorAll('[id^="truck_license_plate-"]');
    function updateDriverId(selectElement) {
        const suffix = selectElement.id.substring("truck_license_plate-".length);
        const driverInput = document.getElementById('truck_driver_id-' + suffix);
        if (driverInput && selectElement.options.length > 0) {
            const selectedOption = selectElement.options[selectElement.selectedIndex];
            const selectedDriverId = selectedOption.getAttribute('data-driver-id');
            driverInput.value = selectedDriverId;
        }
    }
    truckSelects.forEach(selectElement => {
        updateDriverId(selectElement);
        selectElement.addEventListener('change', function() {
            updateDriverId(this);
        });
    });
});
    


    
const dataElement = document.getElementById('chart-data');
const rawChartDataString = dataElement.getAttribute('data-chart');
const rawChartData = JSON.parse(rawChartDataString);
const labels = rawChartData.map(item => item.label);
const costValues = rawChartData.map(item => item.cost);
const currentMonthLabel = '<?php echo $current_year . '-' . $current_month; ?>';
const currentMonthIndex = labels.indexOf(currentMonthLabel);
const backgroundColors = costValues.map((_, index) => 
    index === currentMonthIndex ? 'rgba(78, 115, 223, 1)' : 'rgba(54, 185, 204, 0.7)'
);

const data = {
    labels: labels,
    datasets: [{
        label: 'Maintenance Cost',
        data: costValues,
        backgroundColor: backgroundColors,
        borderColor: backgroundColors,
        borderWidth: 2,
        tension: 0.3 
    }]
};
const config = {
    type: 'line', 
    data: data,
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false 
            },
            tooltip: {
                callbacks: {
                    label: function(context) {
                        let label = context.dataset.label || '';
                        if (label) {
                            label += ': ';
                        }
                        if (context.parsed.y !== null) {
                            label += '₦ ' + context.parsed.y.toLocaleString();
                        }
                        return label;
                    }
                }
            }
        },
        scales: {
            x: {
                title: {
                    display: true,
                    text: 'Month'
                }
            },
            y: {
                beginAtZero: true,
                title: {
                    display: true,
                    text: 'Cost (₦)'
                }
            }
        }
    }
};
maintenanceChart = document.getElementById('maintenanceChart');
if (maintenanceChart) {
    new Chart(
        maintenanceChart,
        config
    );  
}


// const tripsData = document.getElementById('trips-data');
// const rawChartDatas = tripsData.getAttribute('data-chart');
// const rawData = JSON.parse(rawChartDatas);
// const triplabels = rawData.map(item => item.license_plate); 
// const tripValues = rawData.map(item => item.trips); 
// const tripdata = {
//     labels: triplabels,
//     datasets: [{
//         label: 'Total Completed Trips',
//         data: tripValues,
//         backgroundColor: 'rgba(54, 162, 235, 0.7)', // Blue
//         borderColor: 'rgba(54, 162, 235, 1)',
//         borderWidth: 1
//     }]
// };
// const tripconfig = {
//     type: 'bar', 
//     data: tripdata,
//     options: {
//         responsive: true,
//         maintainAspectRatio: false,
//         scales: {
//             y: {
//                 beginAtZero: true,
//                 title: {
//                     display: true,
//                     text: 'Number of Trips'
//                 }
//             }
//         }
//     }
// };
// tripBarChart = document.getElementById('tripBarChart');
// if(tripBarChart) {
//     new Chart(
//         tripBarChart,
//         tripconfig
//     );
// }


// Embed the radial value calculated in PHP
const chartContainer = document.getElementById('radialBars');
if (chartContainer) {

    const radialValue = +chartContainer.dataset.radialValue ; 
    const currentTotal = chartContainer.dataset.totalEarnings;

    var options = {
        chart: {
            height: 250,
            type: 'radialBar',
        },
        series: [radialValue], // The main percentage value
        plotOptions: {
            radialBar: {
                hollow: {
                    margin: 15,
                    size: '70%',
                    background: '#fff',
                    image: undefined,
                    imageClipped: false
                },
                dataLabels: {
                    showOn: 'always',
                    name: {
                        show: true,
                        fontSize: '14px',
                        formatter: function (val) {
                            return "Achieved";
                        }
                    },
                    value: {
                        show: true,
                        fontSize: '24px',
                        formatter: function (val) {
                            // Display the actual current total inside the radial bar
                            return '₦' + currentTotal; 
                        }
                    }
                }
            }
        },
        fill: {
            type: 'gradient',
            gradient: {
                shade: 'dark',
                type: 'horizontal',
                shadeIntensity: 0.5,
                gradientToColors: ['#34A853'], // Green gradient end
                inverseColors: true,
                opacityFrom: 1,
                opacityTo: 1,
                stops: [0, 100]
            }
        },
        stroke: {
            lineCap: 'round'
        },
        labels: ['Current Month'],
        tooltip: {
            enabled: false
        }
    };

    var chart = new ApexCharts(document.querySelector("#radialBars"), options);
    chart.render();
}

document.addEventListener('DOMContentLoaded', function() {
  const profilePicInput = document.getElementById('profile-pic-input');
  const profilePicPreview = document.querySelector('.profile-pic-preview');

  // Check if the element was found before adding the event listener
  if (profilePicInput) {
    profilePicInput.addEventListener('change', function(event) {
      const file = event.target.files[0]; // Get the selected file

      if (file) {
        const reader = new FileReader(); // Create a FileReader object

        reader.onload = function(e) {
          // Set the background image of the preview div to the selected image
          if (profilePicPreview) { // Check if the preview element exists
            profilePicPreview.style.backgroundImage = `url(${e.target.result})`;
          }
        };

        reader.readAsDataURL(file); // Read the selected file as a data URL
      }
    });
  }
});


$('#userProfilePicInput').on('change', function() {
    const file = $(this)[0].files[0];
    if (file) {
        const reader = new FileReader()
        reader.onload = function(e) {
            $('#profilePreview').attr('src', e.target.result);
        };
        reader.readAsDataURL(file);
    }
});

 // Logic for Bar Chart (Truck ID vs Cost)
// 1. Grab the element and parse the JSON attribute 
if (document.getElementById('maintenanceBarChart') || document.getElementById('repairPieChart')) {
    const tripsElement = document.getElementById('main-data');
    const mainChartData = tripsElement.getAttribute('data-chart');
    const chartData = JSON.parse(mainChartData);

    // 2. Destructure or access the variables from the object
    const truckLabels = chartData.truck_labels;
    const truckData   = chartData.truck_data;
    const catLabels   = chartData.cat_labels;
    const catData     = chartData.cat_data;

    // 3. Now initialize your charts as usual
    if (truckLabels.length > 0) {
        new Chart(document.getElementById('maintenanceBarChart'), {
            type: 'bar',
            data: {
                labels: truckLabels,
                datasets: [{
                    label: 'Cost (₦)',
                    data: truckData,
                    backgroundColor: '#5dade2'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: true,
                        position: 'bottom',
                        labels: { boxWidth: 12, font: { family: 'Inter, sans-serif' } }
                    },
                    tooltip: {
                        backgroundColor: '#1c2833', // Dark professional tooltip
                        padding: 12,
                        callbacks: {
                            // Formats the hover value as Naira
                            label: function(context) {
                                let val = context.parsed.y || context.parsed;
                                return ' ₦ ' + new Intl.NumberFormat('en-NG').format(val);
                            }
                        }
                    }
                },
                scales: {
                    x: { grid: { display: false } }, // Remove vertical lines
                    y: { 
                        beginAtZero: true,
                        ticks: {
                            // Adds ₦ to the Y-axis labels
                            callback: function(value) { return '₦' + value.toLocaleString(); }
                        }
                    }
                }
            }
        });
    }
    if (catLabels.length > 0) {
        new Chart(document.getElementById('repairPieChart'), {
            type: 'doughnut',
            data: {
                labels: catLabels,
                datasets: [{
                    data: catData,
                    backgroundColor: ['#5dade2', '#2ecc71', '#f1c40f', '#e74c3c'],
                    borderWidth: 0,   // Removes the white border around segments
                    borderRadius: 5,
                    spacing: 3
                }]
            },
            options: {
        cutout: '75%',
        plugins: {
            legend: {
                position: 'bottom',
                labels: { usePointStyle: true, padding: 20 }
            }
        }
    }

        });
    }
}

function exportPDF() {
    const year = document.getElementById('yearFilter').value;
    window.open(`exports/dashboard_pdf.php?year=${year}`, '_blank');
}

function exportExcel() {
    const year = document.getElementById('yearFilter').value;
    window.location = `exports/dashboard_excel.php?year=${year}`;
}

document.addEventListener('DOMContentLoaded', function() {
    const canvas = document.getElementById('tripFrequencyChart');
    const tripElement = document.getElementById('trip_data');

    // 1. Check if BOTH elements exist on the page
    if (canvas && tripElement) {
        try {
            // 2. Parse the data
            const tripChartData = JSON.parse(tripElement.getAttribute('data-chart'));
            
            const customerLabels = tripChartData.customer_name;
            const triptotalData   = tripChartData.trip_count;

            // 3. Initialize the Chart
            new Chart(canvas.getContext('2d'), {
                type: 'bar',
                data: {
                    labels: customerLabels,
                    datasets: [{
                        label: 'Trips',
                        data: triptotalData,
                        backgroundColor: '#28a745',
                        borderRadius: 5
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: { 
                            beginAtZero: true, 
                            ticks: { stepSize: 1 } 
                        }
                    }
                }
            });
            console.log("Chart successfully initialized");
        } catch (e) {
            console.error("Error parsing chart data: ", e);
        }
    }
});

function viewTransactionDetails(transId) {
    $('#transactionDetailModal').modal('show');
    $('#transaction_details_content').html('<div class="text-center p-4"><div class="spinner-border text-primary"></div></div>');

    $.ajax({
        url: 'inc/code_query.php',
        method: 'POST',
        data: { action: 'getTransactionDetails', tid: transId },
        success: function(response) {
            $('#transaction_details_content').html(response);
        }
    });
}

function openEditModal(data) {
    // Basic Info
    $('#edit_trip_id').val(data.trip_id);
    $('#edit_atc_display').val(data.atc_number + " - " + data.name);
    
    // Dropdowns
    $('#edit_truck_id').val(data.truck_id);
    $('#edit_driver_id').val(data.driver_id);
    
    // Fuel Info (Matching your new column names)
    $('#edit_filling_station').val(data.filling_station);
    $('#edit_date_filled').val(data.date_filled);
    $('#edit_liters_filled').val(data.liters_filled);
    $('#edit_cost_per_liter').val(data.cost_per_liter);
    $('#edit_used_liters').val(data.used_liters); 
    $('#edit_initial_fuel').val(data.initial_fuel);
    
    // Calculate initial total
    calculateTotal();
    
    $('#editAssignmentModal').modal('show');
}

// Live Calculation
$('.calc-trigger').on('input', function() {
    calculateTotal();
});

function calculateTotal() {
    // 1. Get Values
    let initial   = parseFloat($('#edit_initial_fuel').val()) || 0;
    let filled    = parseFloat($('#edit_liters_filled').val()) || 0;
    let cost      = parseFloat($('#edit_cost_per_liter').val()) || 0;
    let remaining = parseFloat($('#edit_remaining_fuel').val()) || 0;
    let used_liters    = parseFloat($('#edit_used_liters').val()) || 0;

    // 2. Perform Calculations
    let totalCost = filled * cost;
    let totalAvailable = initial + filled;
    let used = totalAvailable - remaining;
    $('#edit_total_cost').val(totalCost.toLocaleString(undefined, {minimumFractionDigits: 2}));
    $('#edit_fuel_balance').val(totalAvailable.toFixed(2) + ' Ltrs');
}

function previewAssignment(data) {
    // We use the 'data' object passed from the button
    $("#p_atc").text(data.atc_number);
    $("#p_truck").text(data.license_plate || "Not Assigned");
    $("#p_driver").text(data.first_name + " " + data.last_name);
    $("#p_station").text(data.filling_station || "N/A");
    $('#p_initial').text(data.initial_fuel || '0.00');
    $('#p_used').text('₦' + data.used_liters);
    let status = data.status;
    let badgeElement = $("#p_status");
    
    // Reset classes first to prevent color overlapping
    badgeElement.removeClass("bg-warning bg-info bg-success bg-secondary");

    if (status === "Pending") {
        badgeElement.text("Pending").addClass("bg-warning text-dark");
    } else if (status === "In Progress" || status === "In Transit") {
        badgeElement.text("In Transit").addClass("bg-info text-white");
    } else if (status === "Completed") {
        badgeElement.text("Completed").addClass("bg-success text-white");
    } else {
        badgeElement.text(status).addClass("bg-secondary text-white");
    }
    
    // Calculations
    let liters = parseFloat(data.liters_filled) || 0;
    let rate = parseFloat(data.cost_per_liter) || 0;
    let total = liters * rate;

    $("#p_liters").text(liters.toFixed(2) + " Ltrs");
    $("#p_rate").text("₦" + rate.toLocaleString());
    $("#p_total").text("₦" + total.toLocaleString());
    $("#p_date").text(data.date_filled || "---");

    // Open the modal
    $("#previewTripModal").modal('show');
}


function openResendModal(id, currentEmail) {
    // 1. Set the values in the modal inputs using jQuery
    $('#resend_log_id').val(id);
    $('#resend_email_input').val(currentEmail);

    // 2. Initialize and show the Bootstrap 5 Modal
    // We use the native Bootstrap constructor here
    var modalElement = document.getElementById('resendModal');
    var modalInstance = new bootstrap.Modal(modalElement);
    
    modalInstance.show();
}

function toggleTripStatus(tripData) {
    Swal.fire({
        title: 'Finalize Trip?',
        text: "This will debit the customer wallet and set the truck to 'In Service'.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, Complete it!',
        showLoaderOnConfirm: true,
        preConfirm: () => {
            // This part handles the AJAX request
            const formData = new FormData();
            formData.append('action', 'toggleStatus');
            formData.append('trip_id', tripData.trip_id);
            formData.append('unit', tripData.unit);
            formData.append('selling', tripData.selling_price);
            formData.append('customer_id', tripData.customer_id);
            formData.append('truck_id', tripData.truck_id);
            formData.append('atc_id', tripData.atc_id);

            return fetch('inc/code_query.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                if (data.trim() !== "1") {
                    throw new Error(data);
                }
                return data;
            })
            .catch(error => {
                Swal.showValidationMessage(`Request failed: ${error}`);
            });
        },
        allowOutsideClick: () => !Swal.isLoading()
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Completed!',
                text: 'Trip finalized and wallet debited.',
                icon: 'success'
            }).then(() => {
                location.reload(); // Reload to update table status and icons
            });
        }
    });
}

function cancelTrip(tripData) {
    Swal.fire({
        title: 'Cancel Trip?',
        text: "Are you sure? This will void the trip and release the ATC volume.",
        icon: 'error',
        input: 'text',
        inputPlaceholder: 'Enter reason for cancellation...',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        confirmButtonText: 'Yes, Cancel it!',
        inputValidator: (value) => {
            if (!value) {
                return 'You need to provide a reason!'
            }
        },
        showLoaderOnConfirm: true,
        preConfirm: (reason) => {
            const formData = new FormData();
            formData.append('action', 'cancelTrip');
            formData.append('trip_id', tripData.trip_id);
            formData.append('atc_id', tripData.atc_id);
            formData.append('reason', reason);

            return fetch('process_trip.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                if (data.trim() !== "1") throw new Error(data);
                return data;
            })
            .catch(error => {
                Swal.showValidationMessage(`Request failed: ${error}`);
            });
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire('Cancelled!', 'The trip has been voided.', 'success')
                .then(() => location.reload());
        }
    });
}

function toggleCustomDate(val) {
    const customRange = document.getElementById('customDateRange');
    if (val === 'custom') {
        customRange.classList.remove('d-none');
    } else {
        customRange.classList.add('d-none');
    }
}