<?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>
</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">
                                    <h4 class="page-title">Preferred Analyses</h4>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-xl-12">
                                <div class="card">
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-bordered table-custom">
                                                <thead>
                                                    <tr>
                                                        <th>ID</th>
                                                        <th>Analysis Name</th>
                                                        <th>Category</th>
                                                        <th>Test Method</th>
                                                        <th>Severity</th>
                                                        <th>Legal</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    $conn = new mysqli($servername, $username, $password, $database);
                                                    $query = "
            SELECT 
                av.idanalysisvocabulary, 
                av.nameanalysisvoc, 
                av.category_analysis, 
                av.testmethod_name, 
                COALESCE(asv.severity, '') AS severity, 
                COALESCE(asv.is_legal, 'N') AS is_legal 
            FROM analysisvocabulary av
            LEFT JOIN analysis_severity asv 
            ON av.idanalysisvocabulary = asv.idanalysisvocabulary
            WHERE av.preferred = 'Y'
        ";
                                                    $result = $conn->query($query);
                                                    if ($result->num_rows > 0) {
                                                        while ($row = $result->fetch_assoc()) {
                                                            $severity = $row['severity'];
                                                            $is_legal = $row['is_legal'];
                                                            echo "<tr>";
                                                            echo "<td>{$row['idanalysisvocabulary']}</td>";
                                                            echo "<td>{$row['nameanalysisvoc']}</td>";
                                                            echo "<td>{$row['category_analysis']}</td>";
                                                            echo "<td>{$row['testmethod_name']}</td>";
                                                            echo "<td>
                        <input type='number' class='form-control form-control-sm severity-input' 
                               value='{$severity}' 
                               data-id='{$row['idanalysisvocabulary']}'
                               min='1' max='10'>
                      </td>";
                                                            echo "<td>
                        <select class='form-select form-select-sm legal-select' 
                                data-id='{$row['idanalysisvocabulary']}'>
                            <option value='Y' " . ($is_legal === 'Y' ? 'selected' : '') . ">Yes</option>
                            <option value='N' " . ($is_legal === 'N' ? 'selected' : '') . ">No</option>
                        </select>
                      </td>";
                                                            echo "<td>
                        <button class='btn btn-success btn-sm save-btn' 
                                data-id='{$row['idanalysisvocabulary']}'>Save</button>
                      </td>";
                                                            echo "</tr>";
                                                        }
                                                    } else {
                                                        echo "<tr><td colspan='7' class='text-center'>No data available</td></tr>";
                                                    }
                                                    ?>
                                                </tbody>
                                            </table>



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

                    </div>
                </div>

            </div>
            <?php include('../include/footer.php'); ?>
        </div>
        <!-- End Right content here -->

    </div>
    <!-- END wrapper -->
    <script>
        $(document).on('click', '.save-btn', function() {
            const id = $(this).data('id');
            const severity = $(this).closest('tr').find('.severity-input').val();
            const isLegal = $(this).closest('tr').find('.legal-select').val();

            // Validazione del campo severity lato client
            if (severity < 1 || severity > 10 || isNaN(severity)) {
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Input',
                    text: 'Severity must be a number between 1 and 10.',
                });
                return;
            }

            // Invio dati tramite AJAX
            $.ajax({
                url: 'update_analysis.php',
                type: 'POST',
                data: {
                    id: id,
                    severity: severity,
                    is_legal: isLegal
                },
                success: function(response) {
                    // Debug del valore ricevuto
                    console.log('Response:', response.trim());
                    if (response.trim() === 'success') {
                        Swal.fire({
                            icon: 'success',
                            title: 'Updated',
                            text: 'The analysis has been updated successfully.',
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.trim(),
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to connect to the server.',
                    });
                }
            });
        });
    </script>




    <script src="../assets/js/popper.min.js"></script>
    <script src="../assets/js/bootstrap.min.js"></script>
    <script src="../assets/js/jquery.blockUI.js"></script>
    <script src="../assets/js/waves.js"></script>
    <script src="../assets/js/app.js"></script>
</body>

</html>