<?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'); ?>

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <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">
    <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">
    <script src="../assets/js/jquery.min.js"></script>
    <link rel="stylesheet" href="../assets/plugins/select2/select2.min.css">
    <script src="../assets/plugins/select2/select2.min.js"></script>

    <script src="../assets/js/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/js/select2.min.js"></script>

    <style>
        .width-100 {
            width: 100%;
        }

        .flex_center {
            display: flex;
            align-items: center;
        }

        .mg_none {
            margin: 0 !important;
        }

        .hidden {
            display: none !important;
        }

        .table-custom tr {
            height: 40px;
            line-height: 40px;
        }

        #ajax_preloader {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: transparent;
            z-index: 9999999;
        }

        .table-custom td,
        .table-custom th {
            padding: 4px 8px;
        }

        .table-custom .btn {
            padding: 2px 15px;
            line-height: 1.7;
            font-size: 14px;
        }

        .form-row {
            display: flex;
            align-items: center;
            /* Questo allinea verticalmente gli elementi nella riga */
            gap: 10px;
            /* Questo crea una piccola distanza tra gli elementi nella riga */
        }

        .table-custom .form-control,
        .table-custom .form-select {
            height: 25px;
            /* Puoi modificare questo valore per adattarlo al tuo design */
            padding: 2px 6px;
            /* riduce la dimensione del padding */
            font-size: 14px;
            /* riduce la dimensione del font */
        }

        .table-custom .form-control-sm.analysis-input {
            height: 25px;
            /* Questo modifica la dimensione degli input con classe 'form-control-sm' e 'analysis-input' */
            padding: 2px 6px;
            font-size: 12px;
        }

        .padding_none {
            padding: 0 !important;
        }

        .select2-container--open {
            z-index: 9999;
        }
    </style>
</head>


<body class="fixed-left">

    <!-- Loader -->
    <div id="preloader">
        <div id="status">
            <div class="spinner"></div>
        </div>
    </div>



    <!-- Begin page -->
    <div id="wrapper">

        <?php include('../include/navigationbar.php'); ?>

        <!-- Start right Content here -->

        <div class="content-page">
            <!-- Start content -->
            <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">
                                    <div class="btn-group float-right">
                                        <ol class="breadcrumb hide-phone p-0 m-0">
                                            <li class="breadcrumb-item"><a href="#">Reportify</a></li>
                                            <li class="breadcrumb-item active">Importify</li>
                                        </ol>
                                    </div>
                                    <h4 class="page-title">Importify</h4>
                                </div>
                            </div>
                        </div>
                        <!-- end page title end breadcrumb -->

                        <div class="row">
                            <div class="col-xl-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h5 class="header-title pb-3 mt-0">Importify: <?php echo $dashboard; ?></h5>
                                        <br><br>
                                        <div class="table-responsive">
                                            <table id="analysisTable" class="table table-striped table-custom">
                                                <thead>
                                                    <tr>
                                                        <th>ID</th>
                                                        <th>Analysis Name</th>
                                                        <th>Kind</th>
                                                        <th>Code</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody></tbody>
                                            </table>
                                        </div>

                                        <input id="f_csv" type="file" name="f_csv" style="display: none" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/csv">

                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- end row -->


                    </div><!-- container -->

                </div> <!-- Page content Wrapper -->

            </div> <!-- content -->

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

        </div>
        <!-- End Right content here -->

    </div>
    <!-- END wrapper -->

    <script>
        $(document).ready(function() {
            var table = $('#analysisTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: 'get_analysis_data.php',
                    type: 'POST'
                },
                columns: [{
                        data: 'idanalysisvocabulary'
                    },
                    {
                        data: 'nameanalysisvoc',
                        render: function(data, type, row) {
                            return '<span class="editable-field" data-id="' + row.idanalysisvocabulary + '" data-field="nameanalysisvoc">' + data + '</span>';
                        }
                    },
                    {
                        data: 'kindanalysisvoc',
                        render: function(data, type, row) {
                            return '<span class="editable-field" data-id="' + row.idanalysisvocabulary + '" data-field="kindanalysisvoc">' + data + '</span>';
                        }
                    },
                    {
                        data: 'analysiscode',
                        render: function(data, type, row) {
                            return '<span class="editable-field" data-id="' + row.idanalysisvocabulary + '" data-field="analysiscode">' + data + '</span>';
                        }
                    },
                    {
                        data: null,
                        className: 'dt-center',
                        render: function(data, type, row) {
                            return '<button class="btn btn-sm btn-primary show-synonyms" data-id="' + row.idanalysisvocabulary + '">Show Synonyms</button>' +
                                ' <button class="btn btn-sm btn-danger show-compounds" data-id="' + row.idanalysisvocabulary + '">Show Compounds</button>';
                        }
                    }
                ]
            });

            // Double-click to transform field into input or select
            $('#analysisTable').on('dblclick', '.editable-field', function() {
                var span = $(this);
                var currentValue = span.text();
                var field = span.data('field');
                var id = span.data('id');

                if (field === 'kindanalysisvoc') {
                    var select = '<select class="form-control edit-field" data-id="' + id + '" data-field="' + field + '">' +
                        '<option value="CH"' + (currentValue === 'CH' ? ' selected' : '') + '>CH</option>' +
                        '<option value="MB"' + (currentValue === 'MB' ? ' selected' : '') + '>MB</option>' +
                        '<option value="PM"' + (currentValue === 'PM' ? ' selected' : '') + '>PM</option>' +
                        '</select>';
                    span.replaceWith(select);
                } else {
                    var input = '<input type="text" class="form-control edit-field" value="' + currentValue + '" data-id="' + id + '" data-field="' + field + '">';
                    span.replaceWith(input);
                }
            });

            // Handle update on blur
            $('#analysisTable').on('blur', '.edit-field', function() {
                var input = $(this);
                var id = input.data('id');
                var field = input.data('field');
                var value = input.val();

                $.ajax({
                    url: 'update_analysis.php',
                    type: 'POST',
                    data: {
                        id: id,
                        field: field,
                        value: value
                    },
                    success: function(response) {
                        var jsonResponse = JSON.parse(response);
                        if (jsonResponse.success) {
                            var newText = $('<span class="editable-field" data-id="' + id + '" data-field="' + field + '">' + value + '</span>');
                            input.replaceWith(newText);
                            Swal.fire('Success', 'The analysis has been updated successfully!', 'success');
                        } else {
                            Swal.fire('Error', jsonResponse.error || 'There was a problem updating the analysis.', 'error');
                        }
                    },
                    error: function() {
                        Swal.fire('Error', 'Server communication error.', 'error');
                    }
                });
            });

            // Show synonyms and allow editing of synonyms
            $('#analysisTable').on('click', '.show-synonyms', function() {
                var tr = $(this).closest('tr');
                var row = table.row(tr);
                var analysisId = $(this).data('id');

                if (row.child.isShown()) {
                    row.child.hide();
                    tr.removeClass('shown');
                } else {
                    $.ajax({
                        url: 'get_synonymsvoc.php',
                        type: 'POST',
                        data: {
                            id: analysisId
                        },
                        success: function(response) {
                            var synonyms = JSON.parse(response);
                            var childTable = '<table class="table table-custom"><tr><th>ID</th><th>Synonym</th><th>Actions</th></tr>';

                            $.each(synonyms, function(index, synonym) {
                                childTable += '<tr><td>' + synonym.idanalysisvocabulary + '</td>' +
                                    '<td><span class="editable-synonym-field" data-id="' + synonym.idanalysisvocabulary + '" data-field="nameanalysisvoc">' + synonym.nameanalysisvoc + '</span></td>' +
                                    '<td><button class="btn btn-danger delete-synonym" data-id="' + synonym.idanalysisvocabulary + '">Delete</button></td></tr>';
                            });

                            // Add row for adding a new synonym
                            childTable += '<tr><td>New</td>' +
                                '<td><input type="text" class="form-control new-synonym-input" placeholder="Enter synonym" data-id="' + analysisId + '"></td>' +
                                '<td><button class="btn btn-success add-synonym" data-id="' + analysisId + '">Add</button></td></tr>';

                            childTable += '</table>';

                            row.child(childTable).show();
                            tr.addClass('shown');
                        }
                    });
                }
            });

            // Handle delete synonym
            $('#analysisTable').on('click', '.delete-synonym', function() {
                var id = $(this).data('id');

                Swal.fire({
                    title: 'Are you sure?',
                    text: 'This will delete the synonym.',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, delete it!',
                    cancelButtonText: 'Close Window'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: 'delete_synonymvoc.php',
                            type: 'POST',
                            data: {
                                id: id
                            },
                            success: function(response) {
                                var jsonResponse = JSON.parse(response);
                                if (jsonResponse.success) {
                                    Swal.fire('Deleted!', 'The synonym has been deleted.', 'success');
                                    table.ajax.reload(); // Reload DataTables
                                } else {
                                    Swal.fire('Error', jsonResponse.error || 'There was a problem deleting the synonym.', 'error');
                                }
                            },
                            error: function() {
                                Swal.fire('Error', 'Server communication error.', 'error');
                            }
                        });
                    }
                });
            });

            // Handle add new synonym
            $('#analysisTable').on('click', '.add-synonym', function() {
                var analysisId = $(this).data('id');
                var newSynonym = $(this).closest('tr').find('.new-synonym-input').val();

                if (newSynonym) {
                    $.ajax({
                        url: 'add_synonymvoc.php',
                        type: 'POST',
                        data: {
                            refid: analysisId,
                            name: newSynonym
                        },
                        success: function(response) {
                            var jsonResponse = JSON.parse(response);
                            if (jsonResponse.success) {
                                Swal.fire('Success', 'New synonym has been added successfully!', 'success');
                                table.ajax.reload(); // Reload DataTables to show the new synonym
                            } else {
                                Swal.fire('Error', jsonResponse.error || 'There was a problem adding the synonym.', 'error');
                            }
                        },
                        error: function() {
                            Swal.fire('Error', 'Server communication error.', 'error');
                        }
                    });
                } else {
                    Swal.fire('Error', 'Please enter a synonym.', 'error');
                }
            });

            // Show compounds and allow editing of compounds
            // Show compounds and allow editing of compounds
            $('#analysisTable').on('click', '.show-compounds', function() {
                var tr = $(this).closest('tr');
                var row = table.row(tr);
                var analysisId = $(this).data('id');

                if (row.child.isShown()) {
                    row.child.hide();
                    tr.removeClass('shown');
                } else {
                    $.ajax({
                        url: 'get_compounds.php',
                        type: 'POST',
                        data: {
                            id: analysisId
                        },
                        success: function(response) {
                            var compounds = JSON.parse(response);
                            var childTable = '<table class="table table-custom"><tr><th>Compound Name</th><th>CAS</th><th>Actions</th></tr>';

                            if (compounds.length > 0) {
                                $.each(compounds, function(index, compound) {
                                    childTable += '<tr>' +
                                        '<td>' + compound.namecompoundsvocabulary + '</td>' +
                                        '<td>' + compound.cascompoundvocabulary + '</td>' +
                                        '<td><button class="btn btn-danger delete-compound" data-id="' + compound.idcompoundsvocabulary + '" data-analysis-id="' + analysisId + '">Delete</button></td></tr>';
                                });
                            } else {

                                childTable += '<tr><td colspan="3">No compounds found</td></tr>';
                            }

                            // Add row for adding a new compound
                            childTable += '<tr><td>New</td>' +
                                '<td><select class="form-control new-compound-select" data-id="' + analysisId + '"></select></td>' +
                                '<td><button class="btn btn-success add-compound" data-id="' + analysisId + '">Add</button></td></tr>';

                            childTable += '</table>';

                            row.child(childTable).show();
                            tr.addClass('shown');

                            // Load compound options into the select dropdown with Select2
                            $.ajax({
                                url: 'get_compounds_list.php',
                                type: 'GET',
                                success: function(data) {
                                    var compoundsList = JSON.parse(data);
                                    var select = tr.next().find('.new-compound-select');

                                    // Aggiungi un'opzione iniziale per indicare di selezionare un composto
                                    select.append('<option value="" disabled selected>Select a compound...</option>');

                                    // Popola il select con le opzioni
                                    $.each(compoundsList, function(index, compound) {
                                        var option = new Option(compound.text, compound.id, false, false);
                                        select.append(option);
                                    });

                                    // Inizializza Select2 dopo aver popolato il select
                                    select.select2({
                                        placeholder: "Select a compound...",
                                        width: 'resolve',
                                        allowClear: true
                                    });
                                },
                                error: function() {
                                    Swal.fire('Error', 'Error loading compounds list.', 'error');
                                }
                            });



                        },
                        error: function() {
                            Swal.fire('Error', 'Server communication error.', 'error');
                        }
                    });
                }
            });


            $('#analysisTable').on('click', '.add-compound', function() {
                var analysisId = $(this).data('id');
                var compoundId = $(this).closest('tr').find('.new-compound-select').val();
                var tr = $(this).closest('tr').prev(); // Trova la riga principale dell'analisi
                var row = table.row(tr);

                if (compoundId) {
                    $.ajax({
                        url: 'add_compound.php',
                        type: 'POST',
                        data: {
                            analysis_id: analysisId,
                            compound_id: compoundId
                        },
                        success: function(response) {
                            var jsonResponse = JSON.parse(response);
                            if (jsonResponse.success) {
                                Swal.fire('Success', 'New compound has been added successfully!', 'success');

                                // Ricarica solo la lista dei composti nel child table senza chiudere
                                reloadChildCompounds(analysisId, row);
                            } else {
                                Swal.fire('Error', jsonResponse.error || 'There was a problem adding the compound.', 'error');
                            }
                        },
                        error: function() {
                            Swal.fire('Error', 'Server communication error.', 'error');
                        }
                    });
                } else {
                    Swal.fire('Error', 'Please select a compound.', 'error');
                }
            });

            // Funzione per ricaricare il child table dei composti
            function reloadChildCompounds(analysisId, row) {
                $.ajax({
                    url: 'get_compounds.php',
                    type: 'POST',
                    data: {
                        id: analysisId
                    },
                    success: function(response) {
                        var compounds = JSON.parse(response);
                        var childTable = '<table class="table table-custom"><tr><th>Compound Name</th><th>CAS</th><th>Actions</th></tr>';

                        if (compounds.length > 0) {
                            $.each(compounds, function(index, compound) {
                                childTable += '<tr>' +
                                    '<td>' + compound.namecompoundsvocabulary + '</td>' +
                                    '<td>' + compound.cascompoundvocabulary + '</td>' +
                                    '<td><button class="btn btn-danger delete-compound" data-id="' + compound.idcompoundsvocabulary + '" data-analysis-id="' + analysisId + '">Delete</button></td></tr>';
                            });
                        } else {
                            childTable += '<tr><td colspan="3">No compounds found</td></tr>';
                        }

                        // Aggiungi una riga per aggiungere un nuovo composto
                        childTable += '<tr><td>New</td>' +
                            '<td><select class="form-control new-compound-select" data-id="' + analysisId + '"></select></td>' +
                            '<td><button class="btn btn-success add-compound" data-id="' + analysisId + '">Add</button></td></tr>';

                        childTable += '</table>';

                        // Ricarica il contenuto del child row con il nuovo contenuto
                        row.child(childTable).show();

                        // Carica le opzioni dei composti nella tendina con Select2
                        $.ajax({
                            url: 'get_compounds_list.php',
                            type: 'GET',
                            success: function(data) {
                                var compoundsList = JSON.parse(data);
                                var select = row.child().find('.new-compound-select');

                                // Aggiungi un'opzione iniziale per indicare di selezionare un composto
                                select.append('<option value="" disabled selected>Select a compound...</option>');

                                // Popola il select con le opzioni
                                $.each(compoundsList, function(index, compound) {
                                    var option = new Option(compound.text, compound.id, false, false);
                                    select.append(option);
                                });

                                // Inizializza Select2 dopo aver popolato il select
                                select.select2({
                                    placeholder: "Select a compound...",
                                    width: 'resolve',
                                    allowClear: true
                                });
                            },
                            error: function() {
                                Swal.fire('Error', 'Error loading compounds list.', 'error');
                            }
                        });
                    },
                    error: function() {
                        Swal.fire('Error', 'Server communication error.', 'error');
                    }
                });
            }



            // Handle delete compound
            $('#analysisTable').on('click', '.delete-compound', function() {
                var compoundId = $(this).data('id');
                var analysisId = $(this).data('analysis-id');

                Swal.fire({
                    title: 'Are you sure?',
                    text: 'This will delete the compound.',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, delete it!',
                    cancelButtonText: 'Close Window'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: 'delete_compound.php',
                            type: 'POST',
                            data: {
                                analysis_id: analysisId, // Invia l'ID dell'analisi
                                compound_id: compoundId // Invia l'ID del composto
                            },
                            success: function(response) {
                                var jsonResponse = JSON.parse(response);
                                if (jsonResponse.success) {
                                    Swal.fire('Deleted!', 'The compound has been deleted.', 'success');
                                    table.ajax.reload(); // Reload DataTables
                                } else {
                                    Swal.fire('Error', jsonResponse.error || 'There was a problem deleting the compound.', 'error');
                                }
                            },
                            error: function() {
                                Swal.fire('Error', 'Server communication error.', 'error');
                            }
                        });

                    }
                });
            });

        });
    </script>
    <!-- plugin JS  -->
    <script src="../assets/js/popper.min.js"></script>
    <script src="../assets/js/bootstrap.min.js"></script>
    <script src="../assets/js/modernizr.min.js"></script>
    <script src="../assets/js/detect.js"></script>
    <script src="../assets/js/fastclick.js"></script>
    <script src="../assets/js/jquery.slimscroll.js"></script>
    <script src="../assets/js/jquery.blockUI.js"></script>
    <script src="../assets/js/waves.js"></script>
    <script src="../assets/js/jquery.nicescroll.js"></script>
    <script src="../assets/js/jquery.scrollTo.min.js"></script>
    <script src="../assets/js/common_helper.js"></script>

    <script src="../assets/plugins/chart.js/chart.min.js"></script>
    <script src="../assets/pages/dashboard.js"></script>

    <!-- App js -->
    <script src="../assets/js/app.js"></script>
    <script src="../assets/plugins/alertify/js/alertify.js"></script>


</body>

</html>