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

    <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-xl-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h5 class="header-title pb-3 mt-0">Compounds Management</h5>
                                        <div class="table-responsive">
                                            <table id="compoundsTable" class="table table-striped table-custom">
                                                <thead>
                                                    <tr>
                                                        <th>ID</th>
                                                        <th>Compound Name</th>
                                                        <th>CAS</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody></tbody>
                                            </table>
                                        </div>
                                    </div>
                                </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">

                                        </div><!--end table-responsive-->
                                        <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 compoundsTable = $('#compoundsTable').DataTable({
                processing: true,
                serverSide: true,
                pageLength: 100,
                ajax: {
                    url: 'get_compounds_data.php',
                    type: 'POST'
                },
                columns: [{
                        data: 'idcompoundsvocabulary'
                    },
                    {
                        data: 'namecompoundsvocabulary',
                        render: function(data, type, row) {
                            return '<span class="editable-compound-field" data-id="' + row.idcompoundsvocabulary + '" data-field="namecompoundsvocabulary">' + data + '</span>';
                        }
                    },
                    {
                        data: 'cascompoundvocabulary',
                        render: function(data, type, row) {
                            return '<span class="editable-compound-field" data-id="' + row.idcompoundsvocabulary + '" data-field="cascompoundvocabulary">' + data + '</span>';
                        }
                    },
                    {
                        data: null,
                        className: 'dt-center',
                        render: function(data, type, row) {
                            return '<button class="btn btn-sm btn-primary show-compound-synonyms" data-id="' + row.idcompoundsvocabulary + '">Show Synonyms</button>';
                        }
                    }
                ]
            });

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

                var input = '<input type="text" class="form-control edit-compound-field" value="' + currentValue + '" data-id="' + id + '" data-field="' + field + '">';
                span.replaceWith(input);
            });

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

                $.ajax({
                    url: 'update_compounds.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-compound-field" data-id="' + id + '" data-field="' + field + '">' + value + '</span>');
                            input.replaceWith(newText);
                            Swal.fire('Success', 'The compound has been updated successfully!', 'success');
                        } else {
                            Swal.fire('Error', jsonResponse.error || 'There was a problem updating the compound.', 'error');
                        }
                    },
                    error: function() {
                        Swal.fire('Error', 'Server communication error.', 'error');
                    }
                });
            });

            // Show compound synonyms and allow editing or adding new ones
            $('#compoundsTable').on('click', '.show-compound-synonyms', function() {
                var tr = $(this).closest('tr');
                var row = compoundsTable.row(tr);
                var compoundId = $(this).data('id');

                if (row.child.isShown()) {
                    row.child.hide();
                    tr.removeClass('shown');
                } else {
                    $.ajax({
                        url: 'get_compound_synonyms.php',
                        type: 'POST',
                        data: {
                            id: compoundId
                        },
                        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.idcompoundsvocabulary + '</td>' +
                                    '<td><span class="editable-compound-synonym-field" data-id="' + synonym.idcompoundsvocabulary + '" data-field="namecompoundsvocabulary">' + synonym.namecompoundsvocabulary + '</span></td>' +
                                    '<td><button class="btn btn-danger delete-compound-synonym" data-id="' + synonym.idcompoundsvocabulary + '">Delete</button></td></tr>';
                            });

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

                            childTable += '</table>';

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

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

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

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

                if (newSynonym) {
                    $.ajax({
                        url: 'add_compound_synonym.php',
                        type: 'POST',
                        data: {
                            refid: compoundId,
                            name: newSynonym
                        },
                        success: function(response) {
                            var jsonResponse = JSON.parse(response);
                            if (jsonResponse.success) {
                                Swal.fire('Success', 'New synonym has been added successfully!', 'success');
                                compoundsTable.ajax.reload();
                            } 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');
                }
            });
        });
    </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>