<?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">
    <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>
    <style>
        /* Custom styles here */
    </style>
</head>

<body class="fixed-left">

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

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

    <div id="ajax_preloader">
        <div id="status">
            <div class="spinner"></div>
        </div>
    </div>

    <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">Intervention necessary</h4>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-xl-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h5 class="header-title pb-3 mt-0">Records</h5>
                                        <div class="table-responsive">
                                            <table class="table table-striped table-custom">
                                                <thead>
                                                    <tr>
                                                        <th>ID</th>
                                                        <th>UUID</th>
                                                        <th>Lab ID</th>
                                                        <th>Received At</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    // Database connection
                                                    $conn = new mysqli($servername, $username, $password, $database);
                                                    if ($conn->connect_error) {
                                                        die("Connection failed: " . $conn->connect_error);
                                                    }

                                                    // Query for rows with processed = 2
                                                    $sql = "SELECT * FROM temp_json_queue WHERE processed = 2";
                                                    $result = $conn->query($sql);

                                                    if ($result->num_rows > 0) {
                                                        while ($row = $result->fetch_assoc()) {
                                                            echo "<tr>";
                                                            echo "<td>" . $row['id'] . "</td>";
                                                            echo "<td>" . $row['uuid'] . "</td>";
                                                            echo "<td>" . $row['lab_id'] . "</td>";
                                                            echo "<td>" . $row['received_at'] . "</td>";
                                                            echo "<td>
                                                                    <button class='btn btn-success btn-sm' onclick='handleImport(" . $row['id'] . ")'>Import</button>
                                                                    <button class='btn btn-danger btn-sm' onclick='deleteRow(" . $row['id'] . ")'><i class='bx bx-trash'></i></button>
                                                                  </td>";
                                                            echo "</tr>";
                                                        }
                                                    } else {
                                                        echo "<tr><td colspan='5'>No records found</td></tr>";
                                                    }

                                                    $conn->close();
                                                    ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

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

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

    <script> 

        function refresh_table(){ 
            // location reload in 2 seconds
            setTimeout(function(){
                location.reload();
            }, 2000);

        }

        function handleImport(id) {
            formdata = new FormData();
            formdata.append('id', id);
            $.ajax({
                url: 'importjson.php',
                type: 'POST',
                data: formdata,
                processData: false,
                contentType: false,
                beforeSend: function() {
                    $('#ajax_preloader').fadeIn();
                },
                error: function() {
                    $('#f_csv').val("");
                    $('#ajax_preloader').fadeOut();
                    showWarningAlert("Server Error");
                },
                success: function(data) {
                    $('#ajax_preloader').fadeOut();
                    if (data.code == "success") {
                        let arr_data = data;
                        let arr_analysisvoc = arr_data['arr_analysis_data'];
                        let arr_compundsvoc = arr_data['arr_compunds_data'];

                        tmp_analyvoc_idx = 0;
                        tmp_compundsvoc_idx = 0;
                        arr_total_analysisvoc = arr_analysisvoc;
                        arr_total_compundsvoc = arr_compundsvoc;
                        tmp_str_arr_compunds_kind_option = '';
                        tmp_str_arr_kind_option = '';

                        show_analysis_add_pop(id);
                    } else if (data.indexOf("none_define_column_error") > -1) {
                        $('#f_csv').val("");
                        showWarningPopup("The Associate Columns did not define yet!");
                    } else if (data.indexOf("invalid_excel_data_format_error") > -1) {
                        $('#f_csv').val("");
                        showWarningPopup("Excel data format is not valid!")
                    } else {
                        $('#f_csv').val("");
                        showWarningAlert("Server Error.")
                    }
                }
            })
        }

        function process_import(id) {
            formData = new FormData();
            formData.append('method', 'intervention');
            formData.append('id', id);
            $.ajax({
                url: '../apilogic/process_import.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                beforeSend: function() {
                    $('#ajax_preloader').fadeIn();
                },
                error: function() {
                    $('#ajax_preloader').fadeOut();
                    showWarningAlert("Server Error");
                },
                success: function(data) {
                    $('#ajax_preloader').fadeOut();
                    if (data.code == "success") {
                        showSuccessAlert("Successfully imported!");
                        swal.fire({
                            title: 'Successfully imported!',
                            text: 'The record has been imported successfully.',
                            icon: 'success',
                            showCancelButton: false,
                            confirmButtonText: 'OK',
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        showWarningAlert("Server Error.")
                    }
                }

            })
        }

        function show_analysis_add_pop(id) {
            if (tmp_analyvoc_idx < arr_total_analysisvoc.length) {
                show_analysis_add_popup(id,arr_total_analysisvoc[tmp_analyvoc_idx], function() {
                    tmp_analyvoc_idx++;
                    show_analysis_add_pop(id);
                })
            } else {
                show_compunds_add_pop(id);
            }
        }

        function show_compunds_add_pop(id) {
            if (tmp_compundsvoc_idx < arr_total_compundsvoc.length) {
                show_compunds_add_popup(arr_total_compundsvoc[tmp_compundsvoc_idx], function() {
                    tmp_compundsvoc_idx++;
                    show_compunds_add_pop(id);
                })
            } else {
                process_import(id);
                showSuccessAlert("Successfully added!");
            }
        }

        function show_analysis_add_popup(id,voc_info, callback) {
            let str_word = voc_info['word'];
            let arr_similary = voc_info['arr_similary'];

            let str_arr_option = '';
            for (let i = 0; i < arr_similary.length; i++) {
                str_arr_option += '<option value="' + arr_similary[i]['idanalysisvocabulary'] + '">' + arr_similary[i]['nameanalysisvoc'] + '</option>';
            }
            str_arr_option += tmp_str_arr_kind_option;

            let swal_html = `<div class="row">
                                                    <div class="col-md-12">
                                                        <select class="form-control ipt_type">
                                                        <option value="0">Add new</option>`;
            swal_html += str_arr_option;

            swal_html += `
                                                        </select>
                                                    </div>
                                                    <div class="col-md-12 flex_center div_input ` + (str_arr_option != "" ? "hidden" : "") + `" style="margin-top: 5px">
                                                        <label class="mg_none" style="min-width: 70px">Name</label>
                                                        <input class="form-control ipt_name ipt_val" ` + (str_arr_option != "" ? "" : "readonly") + ` placeholder="Please input name." value="` + str_word + `">
                                                    </div>
                                                    <div class="col-md-12 flex_center div_input ` + (str_arr_option != "" ? "hidden" : "") + `" style="margin-top: 5px">
                                                        <label class="mg_none" style="min-width: 70px">Kind</label>
                                                        <input class="form-control ipt_kind ipt_val" placeholder="Please input kind.">
                                                    </div>
                                                </div>`;
            Swal.fire({
                html: swal_html,
                title: 'Which analysis wants you to associate?<br><span>"' + str_word + '"</span>',
                showCancelButton: false,
                confirmButtonColor: '#3085d6',
                confirmButtonText: 'Confirm',
                allowOutsideClick: false,
                didOpen: () => {
                    $('.swal2-popup .ipt_type').select2();
                    $('.swal2-popup .ipt_type').bind("change", function() {
                        if ($(this).val() == 0) {
                            $('.div_input').removeClass("hidden");
                            $('.ipt_val').val("");
                            $('.swal2-popup .ipt_name').val(str_word);
                            $('.swal2-popup .ipt_name').attr("readonly", "readonly");
                        } else {
                            $('.div_input').addClass("hidden");
                        }
                    });

                    $('.swal2-popup .ipt_type').trigger("change");
                },
            }).then((result) => {
                let type = $('.swal2-popup .ipt_type').val();
                let str_name = $('.swal2-popup .ipt_name').val();
                let str_kind = $('.swal2-popup .ipt_kind').val();

                $.ajax({
                    url: 'add_analysis_voc.php',
                    type: 'POST',
                    data: {
                        type: type,
                        str_name: str_name,
                        str_kind: str_kind,
                    },
                    beforeSend: function() {
                        $('#ajax_preloader').fadeIn();
                    },
                    error: function() {
                        $('#ajax_preloader').fadeOut();
                        showWarningAlert("Server Error");
                    },
                    success: function(data) {
                        $('#ajax_preloader').fadeOut();
                        if (data.indexOf("success") > -1) {
                            if (type == 0) {
                                let inserted_info = JSON.parse(data)['info'];
                                tmp_str_arr_kind_option += '<option value="' + inserted_info['ref_id'] + '">' + inserted_info['name'] + '</option>';
                            }
                            showSuccessAlert("Successfully added!");
                            if (callback) {
                                callback();
                            }else{
                                process_import(id);
                            }
                        } else {
                            showWarningAlert("Server Error.")
                        }
                    }
                })
            });
        }


        function show_compunds_add_popup(voc_info, callback) {
            let str_word = voc_info['word'];
            let str_analysis_word = voc_info['anaysisword'];
            let arr_similary = voc_info['arr_similary'];

            let str_arr_option = '';
            for (let i = 0; i < arr_similary.length; i++) {
                str_arr_option += '<option value="' + arr_similary[i]['idcompoundsvocabulary'] + '">' + arr_similary[i]['namecompoundsvocabulary'] + '</option>';
            }
            str_arr_option += tmp_str_arr_compunds_kind_option;

            let swal_html = `<div class="row">
                                                    <div class="col-md-12">
                                                        <select class="form-control ipt_type">
                                                            <option value="0">Add new</option>`;
            swal_html += str_arr_option;

            swal_html += `
                                                        </select>
                                                    </div>
                                                    <div class="col-md-12 flex_center div_input ` + (str_arr_option != "" ? "hidden" : "") + `" style="margin-top: 5px">
                                                        <label class="mg_none" style="min-width: 70px">Name</label>
                                                        <input class="form-control ipt_name ipt_val" ` + (str_arr_option != "" ? "" : "readonly") + ` placeholder="Please input component name." value="` + str_word + `">
                                                    </div>
                                                    <div class="col-md-12 flex_center div_input ` + (str_arr_option != "" ? "hidden" : "") + `" style="margin-top: 5px">
                                                        <label class="mg_none" style="min-width: 70px">Cascompound</label>
                                                        <input class="form-control ipt_kind ipt_val" placeholder="Please input cascompound.">
                                                    </div>
                                                </div>`;
            Swal.fire({
                html: swal_html,
                title: 'Which component wants you to associate?<br><span>"' + str_word + '"</span>',
                showCancelButton: false,
                confirmButtonColor: '#3085d6',
                confirmButtonText: 'Confirm',
                allowOutsideClick: false,
                didOpen: () => {
                    $('.swal2-popup .ipt_type').select2();
                    $('.swal2-popup .ipt_type').bind("change", function() {
                        if ($(this).val() == 0) {
                            $('.div_input').removeClass("hidden");
                            $('.ipt_val').val("");
                            $('.swal2-popup .ipt_name').val(str_word);
                            $('.swal2-popup .ipt_name').attr("readonly", "readonly");
                        } else {
                            $('.div_input').addClass("hidden");
                        }
                    });

                    $('.swal2-popup .ipt_type').trigger("change");
                },
            }).then((result) => {
                let type = $('.swal2-popup .ipt_type').val();
                let str_name = $('.swal2-popup .ipt_name').val();
                let str_kind = $('.swal2-popup .ipt_kind').val();

                $.ajax({
                    url: 'add_compunds_voc.php',
                    type: 'POST',
                    data: {
                        type: type,
                        analysis_name: str_analysis_word,
                        str_name: str_name,
                        str_kind: str_kind,
                    },
                    beforeSend: function() {
                        $('#ajax_preloader').fadeIn();
                    },
                    error: function() {
                        $('#ajax_preloader').fadeOut();
                        showWarningAlert("Server Error");
                    },
                    success: function(data) {
                        $('#ajax_preloader').fadeOut();
                        if (data.indexOf("success") > -1) {
                            if (type == 0) {
                                let inserted_info = JSON.parse(data)['info'];
                                tmp_str_arr_compunds_kind_option += '<option value="' + inserted_info['ref_id'] + '">' + inserted_info['name'] + '</option>';
                            }
                            showSuccessAlert("Successfully added!");
                            if (callback) {
                                callback();
                            }else{
                                process_import(id);
                            }
                        } else {
                            showWarningAlert("Server Error.")
                        }
                    }
                })
            });
        }

        function deleteRow(id) {
            Swal.fire({
                title: 'Are you sure?',
                text: "This action cannot be undone!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'No, cancel!',
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'delete_json.php',
                        type: 'POST',
                        data: {
                            id: id
                        },
                        success: function(response) {
                            if (response.trim() == "success") {
                                Swal.fire('Deleted!', 'The record has been deleted.', 'success').then(() => {
                                    window.location.reload();
                                });
                            } else {
                                Swal.fire('Error!', 'There was a problem deleting the record.', 'error');
                            }
                        },

                        error: function() {
                            Swal.fire('Error!', 'Could not reach the server.', 'error');
                        }
                    });
                }
            });
        }

        $(document).ready(function() {
            $('#ajax_preloader').fadeOut();
        });
    </script>

    <script src="../assets/js/common_helper.js"></script>
    <script src="../assets/plugins/alertify/js/alertify.js"></script>

</body>

</html>