<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include('../include/headscript.php'); ?>
<?php include("../class/company.php");

$page = 'products.php';
$conn = new mysqli($servername, $username, $password, $database);
// Recupera le impostazioni delle colonne e dell'ordinamento dal database
$query = "SELECT column_visibility, column_order FROM user_table_settings WHERE iduser = ? AND page = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("is", $iduserlogin, $page);
$stmt->execute();
$stmt->bind_result($column_visibility, $column_order);
$stmt->fetch();
$stmt->close();
?>

<?php
$conn = new mysqli($servername, $username, $password, $database);

// Query per ottenere tutti i prodotti
$query = "SELECT * FROM products";
$result = $conn->query($query);
?>

<!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">
    <title>Products</title>
    <link rel="shortcut icon" href="../assets/images/favicon.ico">

    <!-- Includi prima jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.min.css">
    <!-- DataTables Buttons CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.1/css/buttons.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/colreorder/1.5.6/css/colReorder.dataTables.min.css">


    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
    <!-- DataTables Buttons JS -->
    <script src="https://cdn.datatables.net/buttons/2.3.1/js/dataTables.buttons.min.js"></script>
    <!-- Buttons ColVis JS -->
    <script src="https://cdn.datatables.net/buttons/2.3.1/js/buttons.colVis.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/colreorder/1.5.6/js/dataTables.colReorder.min.js"></script>



    <!-- Altri riferimenti al CSS e JS -->
    <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">
    <link href="https://cdn.jsdelivr.net/npm/boxicons@2.0.7/css/boxicons.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.css">
</head>

<style>
    .bg-danger {
        background-color: #ff4d4d !important;
        /* Rosso per fallimenti */
    }

    .bg-success {
        background-color: #28a745 !important;
        /* Verde per successi */
    }

    .bg-warning {
        background-color: #ffc107 !important;
        /* Giallo per N/A o // */
    }

    .text-white {
        color: white !important;
    }

    .text-dark {
        color: black !important;
    }

    .custom-colvis-btn .dt-button {
        background-color: #f8f9fa !important;
        /* Colore di sfondo chiaro per i pulsanti */
        color: #343a40 !important;
        /* Testo scuro per il contrasto */
        border: 1px solid #ced4da !important;
        /* Bordo leggero */
    }

    .custom-colvis-btn .dt-button.active {
        background-color: #007bff !important;
        /* Colore di sfondo attivo (blu) */
        color: white !important;
        /* Testo bianco per il contrasto */
    }

    .custom-colvis-btn .dt-button:hover {
        background-color: #0056b3 !important;
        /* Colore al passaggio del mouse (blu più scuro) */
        color: white !important;
    }

    /* Forza il contrasto per i pulsanti del selettore */
    .dt-button-collection button.active {
        background-color: #007bff !important;
        /* Colore per il bottone selezionato */
        color: #007bff !important;
    }

    .dt-button-collection button {
        background-color: #f8f9fa !important;
        /* Colore per i bottoni non attivi */
        color: #000 !important;
    }
</style>

<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">

                        <div class="row">
                            <div class="col-sm-12">
                                <div class="page-title-box">
                                    <h4 class="page-title">Products</h4>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-xl-12">
                                <div class="card">
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table id="productsTable" class="table table-striped table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Product Ref</th>
                                                        <th>Description</th>
                                                        <th>Style</th>
                                                        <th>Color</th>
                                                        <th>Season</th>
                                                        <th>Market</th>
                                                        <th>SKU</th>
                                                        <th>Order</th>
                                                        <th>Buyer</th>
                                                        <th>Fiber Content Result</th>
                                                        <th>Supplier</th>
                                                        <th>Department</th>
                                                        <th>Production Date</th>
                                                        <th>Date In Lab</th>
                                                        <th>Date Out Lab</th>
                                                        <th>Lab Service</th>
                                                        <th>Age Range</th>
                                                        <th>Division</th>
                                                        <th>Phase</th>
                                                        <th>Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php while ($row = $result->fetch_assoc()) { ?>
                                                        <tr data-productid="<?php echo $row['idproducts']; ?>">
                                                            <td><?php echo $row['products_refnumber']; ?></td>
                                                            <td><?php echo $row['products_description']; ?></td>
                                                            <td><?php echo $row['products_style']; ?></td>
                                                            <td><?php echo $row['products_color']; ?></td>
                                                            <td><?php echo $row['products_season']; ?></td>
                                                            <td><?php echo $row['products_market']; ?></td>
                                                            <td><?php echo $row['products_sku']; ?></td>
                                                            <td><?php echo $row['products_order']; ?></td>
                                                            <td><?php echo $row['product_buyer']; ?></td>
                                                            <td><?php echo $row['products_fibercontentresult']; ?></td>
                                                            <td><?php echo $row['namesupplier']; ?></td>
                                                            <td><?php echo $row['iddepartment']; ?></td>
                                                            <td><?php echo $row['dateprod']; ?></td>
                                                            <td><?php echo $row['dateinlab']; ?></td>
                                                            <td><?php echo $row['dateoutlab']; ?></td>
                                                            <td><?php echo $row['labservice']; ?></td>
                                                            <td><?php echo $row['agerange']; ?></td>
                                                            <td><?php echo $row['products_division']; ?></td>
                                                            <td><?php echo $row['products_phase']; ?></td>
                                                            <td>
                                                                <button class="btn btn-info btn-sm show-reports">Reports</button>
                                                            </td>
                                                        </tr>
                                                    <?php } ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>


                    </div><!-- container -->
                </div><!-- Page content Wrapper -->
            </div><!-- content -->
            <?php include('../include/footer.php'); ?>
        </div>
    </div>
    <script>
        $(document).ready(function() {
            var hasUserInteracted = false; // Flag per tracciare l'interazione dell'utente

            // Carica le impostazioni salvate dal server prima di inizializzare DataTables
            var stateLoaded = false;
            var columnSettings = {}; // Variabile per memorizzare le impostazioni della tabella

            // Recupera le impostazioni salvate dal server
            $.ajax({
                url: 'get_user_table_settings.php', // PHP che recupera i settaggi
                method: 'POST',
                data: {
                    user: "<?php echo $iduserlogin; ?>", // ID utente
                    table: 'products' // Nome della tabella
                },
                async: false, // Carica in modo sincrono per garantire che le impostazioni siano pronte prima di DataTables
                success: function(response) {
                    columnSettings = JSON.parse(response);
                    console.log("Impostazioni recuperate:", columnSettings);
                },
                error: function(xhr, status, error) {
                    console.error('Errore nel caricamento delle impostazioni:', xhr.responseText);
                }
            });

            // Inizializza DataTables con ColReorder, filtri e ColVis
            var table = $('#productsTable').DataTable({
                responsive: true,
                pageLength: 50,
                order: [
                    [1, 'asc']
                ], // Ordina per descrizione
                colReorder: {
                    order: columnSettings && columnSettings.ColReorder ? columnSettings.ColReorder : null // Usa le impostazioni di ColReorder se presenti
                },
                dom: 'Bfrtip', // Integra i bottoni
                buttons: [{
                    extend: 'colvis', // ColVis per mostrare/nascondere colonne
                    collectionLayout: 'fixed four-column', // Layout del dropdown
                    text: 'Select Columns', // Testo del bottone dropdown
                    postfixButtons: ['colvisRestore'], // Pulsante per ripristinare la configurazione iniziale
                    columns: ':not(:last-child)' // Non nascondere l'ultima colonna (Actions)
                }],
                initComplete: function() {
                    console.log("DataTables initComplete");

                    // Se sono state caricate impostazioni di visibilità delle colonne, applicale
                    if (columnSettings && columnSettings.columns) {
                        console.log("Applico visibilità colonne:", columnSettings.columns);
                        this.api().columns().every(function(index) {
                            var column = this;
                            column.visible(columnSettings.columns[index].visible, false); // Non ridisegnare ogni volta
                        });
                    }

                    this.api().columns.adjust().draw(false); // Ridisegna la tabella alla fine

                    // Aggiungi i filtri per ogni colonna (eccetto la colonna delle azioni)
                    this.api().columns().every(function() {
                        var column = this;
                        if (column.index() !== 6) { // Escludi la colonna "Action"
                            var input = $('<input class="form-control form-control-sm" type="text" placeholder="Search"/>')
                                .appendTo($(column.header()))
                                .on('keyup change clear', function() {
                                    if (column.search() !== this.value) {
                                        column.search(this.value).draw();
                                    }
                                });
                        }
                    });
                },
                stateSave: true,
                stateSaveCallback: function(settings, data) {
                    console.log("Salvataggio stato tabella");

                    // Salva le impostazioni sul server solo se l'utente ha interagito
                    if (hasUserInteracted) {
                        $.ajax({
                            url: 'save_user_table_settings.php', // PHP che salva i settaggi
                            method: 'POST',
                            data: {
                                user: "<?php echo $iduserlogin; ?>", // ID utente
                                table: 'products', // Nome della tabella
                                settings: JSON.stringify(data) // Impostazioni della tabella
                            },
                            success: function(response) {
                                console.log('Impostazioni salvate:', response);
                            },
                            error: function(xhr, status, error) {
                                console.error('Errore nel salvataggio delle impostazioni:', xhr.responseText);
                            }
                        });
                    }
                }
            });

            // Imposta il flag `hasUserInteracted` quando l'utente modifica qualcosa (colonne o riordina)
            table.on('column-reorder', function() {
                hasUserInteracted = true;
                console.log("Colonne riordinate");
            });

            table.on('column-visibility', function() {
                hasUserInteracted = true;
                console.log("Visibilità colonna cambiata");
            });

            // Gestione del click su "Reports" per visualizzare la tabella child con i report e le analisi
            $('#productsTable').on('click', '.show-reports', function() {
                var tr = $(this).closest('tr');
                var productId = tr.data('productid');
                var row = $('#productsTable').DataTable().row(tr);
                var button = $(this);

                button.prop('disabled', true);
                button.html('<i class="fa fa-spinner fa-spin"></i> Loading...');

                // Se la riga child è già visibile, nascondila
                if (row.child.isShown()) {
                    row.child.hide();
                    tr.removeClass('shown');
                    button.html('Reports');
                    button.prop('disabled', false);
                    return;
                }

                // Carica i report e le analisi tramite AJAX
                $.ajax({
                    url: 'get_reports_and_analysis.php',
                    type: 'POST',
                    data: {
                        productId: productId
                    },
                    success: function(data) {
                        row.child(formatReportsAndAnalysis(data)).show();
                        tr.addClass('shown');
                    },
                    complete: function() {
                        button.prop('disabled', false);
                        button.html('Reports');
                    },
                    error: function() {
                        Swal.fire('Error!', 'There was an error loading the reports and analysis.', 'error');
                        button.prop('disabled', false);
                        button.html('Reports');
                    }
                });
            });

            // Funzione per formattare i report e le analisi nella stessa tabella
            function formatReportsAndAnalysis(data) {
                var parsedData = JSON.parse(data);
                var reports = parsedData.reports;
                var html = '<table class="table table-bordered child-table">';
                html += '<thead><tr><th>Report Number</th><th>Report Date</th><th>Rating</th><th>Analysis (Name)</th><th>Final Rating</th><th>Action</th></tr></thead>';
                html += '<tbody>';

                $.each(reports, function(index, report) {
                    // Definisci la classe di stile per il rating del report
                    var ratingClass = '';
                    var ratingValue = report.reportsRating.toLowerCase(); // Converte il valore in minuscolo

                    if (ratingValue === 'fail') {
                        ratingClass = 'bg-danger text-white';
                    } else if (ratingValue === 'pass') {
                        ratingClass = 'bg-success text-white';
                    } else if (ratingValue === '//' || ratingValue === 'n/a') {
                        ratingClass = 'bg-warning text-dark';
                    }

                    html += '<tr>';
                    html += '<td>' + report.reportsNumberLab + '</td>';
                    html += '<td>' + report.reportDateIn + '</td>';
                    html += '<td class="' + ratingClass + '">' + report.reportsRating + '</td>'; // Applica la classe alla cella
                    html += '<td colspan="2"></td>'; // Righe vuote per mantenere l'allineamento
                    html += '<td><button class="btn btn-primary btn-sm report-details" data-reportid="' + report.idreports + '">Details</button></td>';
                    html += '</tr>';

                    // Se ci sono analisi associate, aggiungi le righe per ciascuna analisi
                    if (report.analysis.length > 0) {
                        $.each(report.analysis, function(i, analysis) {
                            var ratingClass = '';
                            if (analysis.finalRating === 'FAIL') {
                                ratingClass = 'bg-danger text-white';
                            } else if (analysis.finalRating === 'PASS') {
                                ratingClass = 'bg-success text-white';
                            } else if (analysis.finalRating === '//' || analysis.finalRating === 'N/A') {
                                ratingClass = 'bg-warning text-dark';
                            }

                            html += '<tr>';
                            html += '<td></td>';
                            html += '<td></td>';
                            html += '<td></td>';
                            html += '<td>' + (analysis.name ? analysis.name : 'N/A') + '</td>';
                            html += '<td class="' + ratingClass + '">' + (analysis.finalRating ? analysis.finalRating : 'N/A') + '</td>';
                            html += '<td></td>';
                            html += '</tr>';
                        });
                    } else {
                        html += '<tr><td colspan="5">No analysis available for this report.</td></tr>';
                    }
                });


                html += '</tbody></table>';
                return html;
            }

            // Funzione per la visualizzazione dei dettagli del report
            $(document).on('click', '.report-details', function() {
                var reportId = $(this).data('reportid');
                window.location.href = 'reportdetails.php?idreports=' + reportId;
            });
        });
    </script>


</body>

</html>