<?php include('../include/headscript.php'); ?>
<?php include("../class/company.php"); ?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <?php include('../include/seo.php'); ?>

    <link rel="shortcut icon" href="../assets/images/favicon.ico">
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="../assets/css/icons.css" rel="stylesheet" type="text/css">
    <link href="../assets/css/style.css" rel="stylesheet" type="text/css">
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    <script src="../assets/js/jquery.min.js"></script>

    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.5/css/jquery.dataTables.min.css">

    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.5/js/jquery.dataTables.min.js"></script>
    <!-- DataTables Buttons CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.7/css/buttons.dataTables.min.css">

    <!-- DataTables Buttons JS -->
    <script src="https://cdn.datatables.net/buttons/2.3.7/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.7/js/buttons.flash.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.7/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.7/js/buttons.print.min.js"></script>
    <link href="https://cdn.materialdesignicons.com/5.4.55/css/materialdesignicons.min.css" rel="stylesheet">


</head>

<body class="fixed-left">
    <div id="wrapper">
        <?php include('../include/navigationbar.php'); ?>

        <div class="content-page">
            <div class="content">
                <?php include('../include/topbar.php'); ?>

                <div class="page-content-wrapper">
                    <div class="container-fluid">
                        <br>
                        <div class="row mb-4">
                            <div class="col-md-12">
                                <div class="card p-4">
                                    <div class="rating-box">
                                        <h3 class="m-0">
                                            RATE&GO
                                        </h3>

                                    </div>
                                </div>
                            </div>
                        </div>



                        <!-- Button for Rating Calculation -->
                        <div class="row">
                            <div class="col-md-12 text-right">
                                <button id="calculate-rating" class="btn btn-primary mb-3">
                                    Calculate Ratings
                                </button>
                            </div>
                        </div>

                        <!-- Chart Section -->
                        <div class="row">
                            <div class="col-md-12 text-right">
                                <label for="rating-filter">Filter by Rating:</label>
                                <select id="rating-filter" class="form-control w-auto d-inline-block">
                                    <option value="green">Green (80-100)</option>
                                    <option value="orange">Orange (50-79)</option>
                                    <option value="red">Red (0-49)</option>
                                    <option value="all">All</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div id="supplier-rating-chart"></div>
                            </div>
                        </div>


                        <div class="row">
                            <div class="col-md-12">
                                <div id="supplier-rating-chart"></div>
                            </div>
                        </div>

                        <!-- Table Section -->
                        <div class="row mt-4">
                            <div class="col-md-12">
                                <div class="table-responsive">
                                    <table id="supplierTable" class="table table-bordered table-striped">
                                        <thead>
                                            <tr>
                                                <th>Supplier Name</th>
                                                <th>Number of Products</th>
                                                <th>Total Analyses</th>
                                                <th>PASS Analyses</th>
                                                <th>FAIL Analyses</th>
                                                <th>DATA Analyses</th>
                                                <th>Rating</th>
                                                <th>Date Calculated</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- DataTables popolerà dinamicamente il contenuto -->
                                        </tbody>
                                    </table>
                                </div>


                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include('../include/footer.php'); ?>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            let chart; // Variabile per memorizzare l'istanza del grafico

            // Funzione per generare il grafico
            function renderChart(filteredData) {
                const suppliers = filteredData.map(s => s.name);
                const ratings = filteredData.map(s => s.rating);
                const colors = filteredData.map(s => {
                    if (s.rating >= 80) return '#28a745'; // Green
                    if (s.rating >= 50) return '#ffc107'; // Orange
                    return '#dc3545'; // Red
                });

                const options = {
                    series: [{
                        data: ratings
                    }],
                    chart: {
                        type: 'bar',
                        height: Math.max(filteredData.length * 18, 300), // Altezza dinamica
                        toolbar: {
                            show: true
                        },
                        animations: {
                            enabled: true, // Abilita animazioni fluide
                            easing: 'easeinout',
                            speed: 800
                        }
                    },
                    plotOptions: {
                        bar: {
                            distributed: true,
                            horizontal: true,
                            barHeight: '80%', // Altezza barra
                            dataLabels: {
                                position: 'inside' // Valori all'interno delle barre
                            }
                        }
                    },
                    colors: colors,
                    dataLabels: {
                        enabled: true,
                        style: {
                            colors: ['#000'], // Colore nero per i valori
                            fontWeight: 'bold'
                        },
                        formatter: function(val) {
                            return val; // Mostra il valore direttamente
                        }
                    },
                    xaxis: {
                        categories: suppliers,
                        labels: {
                            style: {
                                fontSize: '12px'
                            }
                        }
                    },
                    legend: {
                        show: false
                    },
                    title: {
                        text: 'Supplier Ratings (Filtered)',
                        align: 'center'
                    }
                };

                // Distruggi il grafico precedente, se esiste
                if (chart) {
                    chart.destroy();
                }

                // Crea un nuovo grafico
                chart = new ApexCharts(document.querySelector("#supplier-rating-chart"), options);
                chart.render();
            }

            // Funzione per filtrare i dati
            function filterData(data, filter) {
                if (filter === "green") return data.filter(s => s.rating >= 80);
                if (filter === "orange") return data.filter(s => s.rating >= 50 && s.rating < 80);
                if (filter === "red") return data.filter(s => s.rating < 50);
                return data; // All
            }

            // Caricamento iniziale
            $.get('get_supplier_ratings.php', function(response) {
                const allData = response;

                // Filtro predefinito: Green
                const defaultFilter = "green";
                const filteredData = filterData(allData, defaultFilter);
                $("#rating-filter").val(defaultFilter); // Imposta il filtro predefinito nel dropdown

                // Renderizza il grafico iniziale
                renderChart(filteredData);

                // Cambia filtro
                $("#rating-filter").on('change', function() {
                    const selectedFilter = $(this).val();
                    const filteredData = filterData(allData, selectedFilter);
                    renderChart(filteredData); // Re-renderizza il grafico con i dati filtrati
                });
            });

            // Inizializza DataTables
            const supplierTable = $('#supplierTable').DataTable({
                ajax: {
                    url: 'get_supplier_ratings.php',
                    dataSrc: '' // I dati JSON sono un array diretto
                },
                columns: [{
                        data: 'name',
                        render: function(data, type, row) {
                            return `<a href="supplier-detail.php?id=${row.id}" class="text-primary">${data}</a>`;
                        }
                    },
                    {
                        data: 'total_products'
                    },
                    {
                        data: 'total_analyses'
                    },
                    {
                        data: 'pass_analyses'
                    },
                    {
                        data: 'fail_analyses'
                    },
                    {
                        data: 'data_analyses'
                    },
                    {
                        data: 'rating',
                        render: function(data, type, row) {
                            const color = data >= 80 ? '#28a745' : data >= 50 ? '#ffc107' : '#dc3545';
                            return `<span style="color: ${color}; font-weight: bold;">${data}</span>`;
                        }
                    },
                    {
                        data: 'date'
                    }
                ],
                order: [
                    [6, 'desc']
                ], // Ordina per rating di default
                pageLength: 50,
                responsive: true,
                dom: 'lBfrtip', // Aggiunge l'area per i pulsanti
                buttons: [
                    'copy', 'csv', 'excel', 'pdf', 'print' // Tipi di esportazione
                ],
                lengthMenu: [
                    [10, 25, 50, 100, -1], // Valori
                    [10, 25, 50, 100, "All"] // Etichette corrispondenti
                ],
                initComplete: function(settings, json) {
                    renderChart(json); // Aggiorna il grafico dopo aver caricato la tabella
                }
            });

            // Funzione per calcolare i rating e aggiornare grafico e tabella
            $('#calculate-rating').on('click', function() {
                $.ajax({
                    url: 'calculate_supplier_ratings.php',
                    method: 'POST',
                    success: function() {
                        alert('Ratings calculated successfully!');
                        supplierTable.ajax.reload(); // Ricarica la tabella
                        $.get('get_supplier_ratings.php', function(response) {
                            renderChart(response); // Aggiorna il grafico
                        });
                    },
                    error: function() {
                        alert('Error calculating ratings.');
                    }
                });
            });
        });
    </script>



</body>

</html>