<?php require_once '../Connections/cmctrfdb.php'; ?>
<?php require_once '../webassist/mysqli/rsobj.php'; ?>
<?php
include 'include/headscript.php';
include('languages/' . $_SESSION['langselect'] . '/tdgen.php');
?>
<?php if (isset($_GET['idtrftd'])) {
    $idtrftd = $_GET['idtrftd'];
}
if (isset($_POST['idtrftd'])) {
    $idtrftd = $_POST['idtrftd'];
}
if (isset($_POST['iddata_td'])) {
    $idtd = $_POST['iddata_td'];
}
if (isset($_GET['idtd'])) {
    $idtd = $_GET['idtd'];
}
?>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Preparazione di un array per contenere i valori sanificati
    $sanitizedPost = [];
    $errors = [];

    // Lista dei campi da sanificare e controllare se sono piene
    $fields = [
        'productionplace_same',
        'classificationshoes',
        'destinationuseppe',
        'manufacutringprocess',
        'ppeageing',
        'obsolescencedeadline',
        'localisationppemarking',
        'manufacturerlogoid',
        'sizeexamplecemark',
        'monthyearprod',
        'serialbatchnumber',
        'standarduse',
        'symbolsaddreq',
        'proddescription',
        'packaging',
        'declarconformity',
        'webaddress'
    ];

    foreach ($fields as $field) {
        if (!empty($_POST[$field])) {
            // Utilizzo FILTER_SANITIZE_STRING per rimuovere i tag e sanificare il testo
            $sanitizedPost[$field] = filter_input(INPUT_POST, $field, FILTER_SANITIZE_STRING);
        }
    }

    // Controllo se ci sono stati errori
    if (count($errors) === 0) {
        // Tutti i campi sono stati compilati e sanificati
        // Qui puoi procedere con l'elaborazione dei dati
        // Ad esempio, stampare i valori o salvarli in un database
        foreach ($sanitizedPost as $key => $value) {
        }
    } else {
        // Ci sono stati errori, ad esempio alcuni campi potrebbero essere vuoti
        // Puoi gestire gli errori qui, ad esempio stampandoli
        foreach ($errors as $key => $message) {
            echo "Errore nel campo $key: $message<br>";
        }
    }
}
?>
<?php
// *: update data_td
// Assicurati che la richiesta sia di tipo POST e che l'ID sia stato fornito

$conn = mysqli_connect($servername, $username, $password, $dbname);



if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($idtrftd)) {
    // Preparazione della parte iniziale della query di aggiornamento
    $updateQuery = "UPDATE data_td SET ";
    $updateParts = [];
    $queryParams = [];

    // Iterazione sui campi sanificati per costruire la query di aggiornamento
    foreach ($sanitizedPost as $key => $value) {
        // Escludi idtrftd dalla parte di aggiornamento della query
        if ($key !== 'idtrftd') {
            $updateParts[] = "$key = ?";
            $queryParams[] = $value;
        }
    }

    // Controllo se ci sono campi da aggiornare
    if (count($updateParts) > 0) {
        $updateQuery .= join(', ', $updateParts) . " WHERE idtrf = ?";
        $queryParams[] = $idtrftd; // Aggiungi l'ID alla fine dei parametri della query

        // Preparazione della query
        $stmt = $conn->prepare($updateQuery);

        // Costruzione del tipo di parametri (stringhe, in questo caso)
        $types = str_repeat('s', count($queryParams));

        // Aggiunta dei parametri alla statement
        $stmt->bind_param($types, ...$queryParams);

        // Esecuzione della query
        if ($stmt->execute()) {
        }

        // Chiusura dello statement
        $stmt->close();
    }
}
?>
<?php // insert risktd
/*
$conn = new mysqli($servername, $username, $password, $dbname);
$checkQuery = "SELECT COUNT(*) as count FROM fillrisk_td WHERE iddata_td = ?";
$stmt = $conn->prepare($checkQuery);
$stmt->bind_param("i", $idtd);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($row['count'] == 0) {
    // Non ci sono record, quindi procedi con l'inserimento dei dati da riskarea_td

    // Prendi tutti i record da riskarea_td
    $selectQuery = "SELECT * FROM riskarea_td";
    $result = $conn->query($selectQuery);



    while ($riskRow = $result->fetch_assoc()) {
        // Prepara l'insert per ogni riga trovata in riskarea_td

        $insertQuery = "INSERT INTO fillrisk_td (idriskarea_td, applicable, idcompany, iddata_td, idtrf) VALUES (?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($insertQuery);

        // Converte il valore 'Y'/'N' della colonna default in un intero (1/0)
        $applicableValue = ($riskRow['default'] == 'Y') ? 1 : 0;

        $stmt->bind_param("iiiii", $riskRow['idriskarea_td'], $applicableValue, $idcompany, $idtd, $idtrftd);
        $stmt->execute();
    }
}


// Chiudi lo statement e la connessione se non ti servono più
$stmt->close();
$conn->close();
*/
?>

<?php
// query data_td
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM data_td WHERE iddata_td = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $idtd); // "i" indica che l'id è un intero
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$stmt->close();
$conn->close();
?>
<?php
$tdquery = new WA_MySQLi_RS("tdquery", $cmctrfdb, 1);
$tdquery->setQuery("SELECT * FROM `trf-details` WHERE `trf-details`.idtrfdetails='$idtrftd'");
$tdquery->execute();

$description = $tdquery->getColumnVal("sample_description");
$trfn = $tdquery->getColumnVal("trfnumber");
$trfrev  = $tdquery->getColumnVal("revtrf");
$trfnumb = $trfn . ' VER.' . $trfrev;
$idart = $tdquery->getColumnVal("idarticletype");
?>
<?php
// parts
$conn = new mysqli($servername, $username, $password, $dbname);
$partquerylist = "SELECT * FROM partsname WHERE partsname.idarticle=?";
$partqueryliststmd = $conn->prepare($partquerylist);
$partqueryliststmd->bind_param("i", $idart);
$partqueryliststmd->execute();
$resultpartquery = $partqueryliststmd->get_result();
// Copia i risultati in un array
$partRows = [];
while ($row = $resultpartquery->fetch_assoc()) {
    // Aggiungi partsnameeng con fallback a partsnameita se non esiste
    $row['partsnameeng'] = isset($row['partsnameeng']) ? $row['partsnameeng'] : $row['partsnameita'];
    $partRows[] = $row;
}
$partqueryliststmd->close();
$conn->close();

// Aggiungi l'opzione specifica in base a $idart
switch ($idart) {
    case 1:
        $partRows[] = [
            'partsnumber' => '99',
            'partsnameita' => 'Calzatura completa',
            'partsnameeng' => 'Complete Footwear'
        ];
        break;
    case 2:
        $partRows[] = [
            'partsnumber' => '99',
            'partsnameita' => 'Guanto Completo',
            'partsnameeng' => 'Complete Glove'
        ];
        break;
    case 3:
        $partRows[] = [
            'partsnumber' => '99',
            'partsnameita' => 'Semimaschera completa',
            'partsnameeng' => 'Complete Half-Mask'
        ];
        break;
    case 4:
        $partRows[] = [
            'partsnumber' => '99',
            'partsnameita' => 'Indumento completo',
            'partsnameeng' => 'Complete Garment'
        ];
        break;
}
?>


<?php

$archivetrflist = new WA_MySQLi_RS("archivetrflist", $cmctrfdb, 0);
$archivetrflist->setQuery("SELECT * FROM `trf-details` LEFT JOIN auth_users ON `trf-details`.iduser=auth_users.id LEFT JOIN article_type ON `trf-details`.idarticletype=article_type.idarticletype LEFT JOIN certificationtype ON certificationtype.idcertificationtype=`trf-details`.idcertification WHERE `trf-details`.idcompany='$idcompany'  AND `trf-details`.signedon <>'' ORDER BY `trf-details`.trfnumber");
$archivetrflist->execute(); ?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title><?php echo $titlepage; ?> </title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta content="CIMAC TRF Portal" name="description" />
    <meta content="" name="author" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <!-- App favicon -->
    <link rel="shortcut icon" href="../images/favicon.ico">

    <!-- DataTables -->

    <link rel="shortcut icon" type="image/png" href="/media/images/favicon.png">
    <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="http://www.datatables.net/rss.xml">
    <link rel="stylesheet" type="text/css" href="/media/css/site-examples.css?_=8f7cff5ee7757412879aedf3efbfaee01">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.3.2/css/buttons.dataTables.min.css">
    <style type="text/css" class="init">

    </style>
    <script type="text/javascript" src="/media/js/site.js?_=1d5abd169416a09a2b389885211721dd" data-domain="datatables.net" data-api="https://plausible.sprymedia.co.uk/api/event"></script>
    <script src="https://media.ethicalads.io/media/client/ethicalads.min.js"></script>
    <script type="text/javascript" src="/media/js/dynamic.php?comments-page=extensions%2Fbuttons%2Fexamples%2Finitialisation%2Fexport.html" async></script>
    <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/2.3.2/js/dataTables.buttons.min.js"></script>
    <script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
    <script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
    <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/2.3.2/js/buttons.html5.min.js"></script>
    <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/2.3.2/js/buttons.print.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.ckeditor.com/ckeditor5/34.1.0/classic/ckeditor.js"></script>


    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-RqEzHvnvS1k5K5wzgp5yoWY5U6TD5EoXyj9iikETmdcy1G6dbCVa+ZmzBm7VWzmj8Ov7VwtA9x9X7VWjG8SRFg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <!--Form Wizard-->
    <link href="../plugins/jquery-steps/jquery.steps.css" rel="stylesheet" type="text/css">

    <!-- App css -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/jquery-ui.min.css" rel="stylesheet">
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/metisMenu.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/app.min.css" rel="stylesheet" type="text/css" />


    <!-- submit form with button -->
    <script>
        function formSubmit() {
            document.forms["myForm"].submit();
        }
    </script>
    </script>
    <script type="text/javascript" class="init">
        $(document).ready(function() {
            var table = $('#example').DataTable({
                pageLength: 20,
                order: [
                    [0, 'desc']
                ],

                dom: 'Bfrtip',
                buttons: [
                    'copy', 'csv', 'excel', 'pdf'
                ]


            });

            $('a.toggle-vis').on('click', function(e) {
                e.preventDefault();

                // Get the column API object
                var column = table.column($(this).attr('data-column'));

                // Toggle the visibility
                column.visible(!column.visible());
            });

        });
    </script>

    <script type="text/javascript" class="init">
        $(document).ready(function() {
            var table = $('#readytrf').DataTable({
                pageLength: 20,
                order: [
                    [0, 'desc']
                ],

                dom: 'Bfrtip',
                buttons: [
                    'copy', 'csv', 'excel', 'pdf'
                ]


            });

            $('a.toggle-vis').on('click', function(e) {
                e.preventDefault();

                // Get the column API object
                var column = table.column($(this).attr('data-column'));

                // Toggle the visibility
                column.visible(!column.visible());
            });

        });
    </script>
    <script>
        document.getElementById('clonetrfalert').addEventListener('click', function(e) {
            e.preventDefault();
            if (confirm("Sei sicuro di voler andare al link clonetrf.php?")) {
                window.location.href = e.target.parentNode.href;
            }
        });
    </script>

</head>

<body>

    <!-- Top Bar Start -->



    <!-- Top Bar Start -->
    <?php include 'include/topbar.php'; ?>
    <!-- Top Bar End -->


    <!-- Left Sidenav -->
    <?php include 'include/leftsidenav.php'; ?>
    <!-- end left-sidenav-->

    <div class="page-wrapper">
        <!-- Page Content-->
        <div class="page-content">

            <div class="container-fluid">
                <!-- Page-Title -->
                <div class="row">
                    <div class="col-sm-12">
                        <div class="page-title-box">
                            <div class="float-right">
                                <ol class="breadcrumb">
                                    <li class="breadcrumb-item"><a href="javascript:void(0);">TRF</a></li>
                                    <li class="breadcrumb-item active">Starter</li>
                                </ol>
                            </div>
                            <h4 class="page-title"><?php echo $techdossier; ?></h4>
                        </div><!--end page-title-box-->
                    </div><!--end col-->
                </div>


                <!-- COMPLETE TRF -->
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card card-body">
                            <h4 class="card-title mt-0"><?php echo $articletd; ?> <?php echo $description; ?> - TRF: <?php echo $trfnumb; ?></h4>
                            <p class="card-text text-muted "><?php echo $questionstarttd; ?></p>

                        </div><!--end card-->
                    </div><!--end col-->


                </div>
                <div class="card">


                    <!-- card for show requirements -->


                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-body">
                                <?php
                                $canEdit = Auth::user()->hasRole('Admin') || Auth::user()->hasRole('CustomerService') || Auth::user()->hasRole('Superuser') || Auth::user()->hasRole('Certification');
                                ?>
                                <form method="post" action="fillparts.php">

                                    <table class="table mb-0">
                                        <thead class="thead-light">
                                            <tr>

                                                <?php if ($canEdit) : ?>
                                                    <th>List</th>
                                                <?php endif; ?>
                                                <th>N.</th>
                                                <th><?php echo $descriptionpart; ?></th>
                                                <th><?php echo $articlepart; ?></th>
                                                <th><?php echo $colorpart; ?></th>
                                                <th><?php echo $descriptionpartlist; ?></th>
                                                <th><?php echo $nrep; ?></th>
                                                <th><?php echo $daterep; ?></th>
                                            </tr>
                                        </thead>

                                        <?php
                                        $partsquery = new WA_MySQLi_RS("partsquery", $cmctrfdb, 0);
                                        $partsquery->setQuery("SELECT * FROM identificationparts WHERE identificationparts.idtrfdetails='$idtrftd'");
                                        $partsquery->execute();
                                        ?>
                                        <tbody>


                                            <?php while (!$partsquery->atEnd()) { ?>
                                                <tr>
                                                    <!-- Usa la variabile $canEdit per controllare l'attributo readonly -->
                                                    <!-- Campo a tendina aggiuntivo per gli utenti autorizzati -->
                                                    <?php if ($canEdit) : ?>
                                                        <td>
                                                            <select class="form-control parts-dropdown" id="listparts_<?php echo $partsquery->getColumnVal("ididentificationparts"); ?>" name="listparts" style="width: 115px;">
                                                                <option value=""><?php echo ($_SESSION['langselect'] == 'en') ? 'Select' : 'Seleziona'; ?></option>
                                                                <?php foreach ($partRows as $row) { ?>
                                                                    <option value="<?php echo $row['partsnumber']; ?>" data-partsnameita="<?php echo htmlspecialchars($row['partsnameita'], ENT_QUOTES, 'UTF-8'); ?>" data-partsnameeng="<?php echo htmlspecialchars($row['partsnameeng'], ENT_QUOTES, 'UTF-8'); ?>">
                                                                        <?php echo $row['partsnumber'] . ' - ' . ($_SESSION['langselect'] == 'en' ? $row['partsnameeng'] : $row['partsnameita']); ?>
                                                                    </option>
                                                                <?php } ?>
                                                            </select>
                                                        </td>
                                                    <?php endif; ?>
                                                    <td scope="row">
                                                        <input class="form-control" style="width: 50px;" type="text" id="partsidnumber" value="<?php echo $partsquery->getColumnVal("partsidnumber"); ?>" name="partsidnumber" <?php echo !$canEdit ? 'readonly' : ''; ?>>
                                                    </td>
                                                    <td>
                                                        <input class="form-control" type="text" id="description_identificationparts" value="<?php echo $partsquery->getColumnVal("description_identificationparts"); ?>" name="description_identificationparts" <?php echo !$canEdit ? 'readonly' : ''; ?>>
                                                    </td>

                                                    <td>
                                                        <input class="form-control" type="text" value="<?php echo $partsquery->getColumnVal("article_identificationparts"); ?>" name="article_identificationparts" <?php echo !$canEdit ? 'readonly' : ''; ?>>
                                                    </td>
                                                    <td>
                                                        <input class="form-control" type="text" value="<?php echo $partsquery->getColumnVal("color_identificationparts"); ?>" name="color_identificationparts" <?php echo !$canEdit ? 'readonly' : ''; ?>>
                                                    </td>
                                                    <td>
                                                        <input class="form-control" type="text" value="<?php echo $partsquery->getColumnVal("material_identificationparts"); ?>" name="material_identificationparts" <?php echo !$canEdit ? 'readonly' : ''; ?>>
                                                    </td>
                                                    <!-- Gli input modificabili rimangono come prima -->
                                                    <td>
                                                        <input class="form-control" type="text" value="<?php echo $partsquery->getColumnVal("cmcreportnumber_identificationparts"); ?>" name="cmcreportnumber_identificationparts">
                                                    </td>
                                                    <td>
                                                        <input class="form-control" type="date" value="<?php echo $partsquery->getColumnVal("cmcreportdate_identificationparts"); ?>" name="cmcreportdate_identificationparts">
                                                    </td>

                                                    <input type="hidden" value="<?php echo $partsquery->getColumnVal("ididentificationparts"); ?>" name="ididentificationparts">
                                                </tr>
                                                <?php $partsquery->moveNext(); ?>
                                            <?php } ?>
                                            <?php $partsquery->moveFirst(); // Se hai bisogno di riutilizzare i risultati 
                                            ?>

                                        </tbody>

                                    </table>
                                    <br>
                                    <?php if ($canEdit) : ?>
                                        <button id="addPart" class="btn btn-primary"><?php echo $addPart; ?></button>

                                    <?php endif; ?>
                                </form>


                                <script>
                                    document.addEventListener('DOMContentLoaded', function() {
                                        // Seleziona tutte le tendine usando la classe comune
                                        const listPartsDropdowns = document.querySelectorAll('.parts-dropdown');

                                        // Imposta gli event listener su ciascuna tendina
                                        listPartsDropdowns.forEach(dropdown => {
                                            dropdown.addEventListener('change', function() {
                                                // Ottieni il valore selezionato e i valori data-partsnameita e data-partsnameeng dell'opzione selezionata
                                                const partsnumber = this.value;
                                                const partsnameita = this.options[this.selectedIndex].getAttribute('data-partsnameita');
                                                const partsnameeng = this.options[this.selectedIndex].getAttribute('data-partsnameeng');

                                                // Trova gli input vicini. Qui assumiamo che gli input siano sempre nelle celle consecutive.
                                                // Modifica questa logica se la struttura della tua tabella è diversa.
                                                const row = this.closest('tr');
                                                const partsidnumberInput = row.querySelector('input[name="partsidnumber"]');
                                                const descriptionInput = row.querySelector('input[name="description_identificationparts"]');

                                                // Aggiorna i valori degli input
                                                if (partsidnumberInput) partsidnumberInput.value = partsnumber;
                                                if (descriptionInput) descriptionInput.value = <?php echo ($_SESSION['langselect'] == 'en') ? 'partsnameeng' : 'partsnameita'; ?>;
                                            });
                                        });
                                    });
                                </script>


                                <script>
                                    ClassicEditor
                                        .create(document.querySelector('#editor'))
                                        .catch(error => {
                                            console.error(error);
                                        });
                                </script>
                                <script>
                                    document.addEventListener('DOMContentLoaded', function() {
                                        const inputs = document.querySelectorAll('.form-control');
                                        inputs.forEach(input => {
                                            input.addEventListener('change', function() {
                                                const row = this.closest('tr');
                                                const ididentificationparts = row.querySelector('input[type="hidden"]').value;
                                                const data = {
                                                    ididentificationparts: ididentificationparts,
                                                    partsidnumber: row.querySelector('input[name="partsidnumber"]').value,
                                                    description_identificationparts: row.querySelector('input[name="description_identificationparts"]').value,
                                                    article_identificationparts: row.querySelector('input[name="article_identificationparts"]').value,
                                                    color_identificationparts: row.querySelector('input[name="color_identificationparts"]').value,
                                                    material_identificationparts: row.querySelector('input[name="material_identificationparts"]').value,
                                                    cmcreportnumber_identificationparts: row.querySelector('input[name="cmcreportnumber_identificationparts"]').value,
                                                    cmcreportdate_identificationparts: row.querySelector('input[name="cmcreportdate_identificationparts"]').value
                                                };

                                                fetch('fillparts.php', {
                                                        method: 'POST',
                                                        headers: {
                                                            'Content-Type': 'application/x-www-form-urlencoded',
                                                        },
                                                        body: new URLSearchParams(data)
                                                    })
                                                    .then(response => response.json())
                                                    .then(data => {
                                                        if (data.success) {
                                                            this.style.backgroundColor = '#d4edda'; // Verde per successo
                                                            setTimeout(() => {
                                                                this.style.backgroundColor = '';
                                                            }, 2000); // Resetta colore dopo 2 secondi
                                                        } else {
                                                            alert(data.message || 'Errore nell\'aggiornamento dei dati.');
                                                        }
                                                    })
                                                    .catch(error => {
                                                        console.error('Errore:', error);
                                                    });
                                            });
                                        });
                                    });
                                </script>
                                <script>
                                    document.getElementById('addPart').addEventListener('click', function() {
                                        fetch('add_part.php', {
                                                method: 'POST',
                                                headers: {
                                                    'Content-Type': 'application/x-www-form-urlencoded',
                                                },
                                                body: new URLSearchParams({
                                                    'idcompany': '<?php echo $idcompany; ?>',
                                                    'idart': '<?php echo $idart; ?>',
                                                    'idtrftd': '<?php echo $idtrftd; ?>',
                                                    'iduserlogin': '<?php echo $iduserlogin; ?>'
                                                })
                                            })
                                            .then(response => response.json())
                                            .then(data => {
                                                if (data.success) {
                                                    alert(data.message);
                                                    location.reload(); // Ricarica la pagina per mostrare la nuova riga, oppure aggiungila dinamicamente con JS
                                                } else {
                                                    alert(data.message);
                                                }
                                            })
                                            .catch(error => {
                                                console.error('Errore:', error);
                                            });
                                    });
                                </script>




                            </div>
                        </div><!--end card-body-->
                    </div><!--end card-->
                </div>
                <?php if ($idart == 2) : ?>
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card card-body">
                                <h4 class="card-title mt-0"><?php echo ($_SESSION['langselect'] == 'en') ? 'Chemical Agents' : 'Agenti Chimici'; ?></h4>
                                <p class="card-text text-muted"><?php echo ($_SESSION['langselect'] == 'en') ? 'Update the levels and degradation percentage for chemical agents below' : 'Aggiorna di seguito i livelli e percentuale di degradazione per agenti chimici'; ?></p>

                                <table class="table mb-0">
                                    <thead class="thead-light">
                                        <tr>
                                            <th><?php echo ($_SESSION['langselect'] == 'en') ? 'Chemical Agent' : 'Agente Chimico'; ?></th>
                                            <th><?php echo ($_SESSION['langselect'] == 'en') ? 'Level' : 'Livello'; ?></th>
                                            <th><?php echo ($_SESSION['langselect'] == 'en') ? 'Percentage Degradation' : 'Degradazione percentuale'; ?></th>
                                        </tr>
                                    </thead>
                                    <?php
                                    $chemquery = new WA_MySQLi_RS("chemquery", $cmctrfdb, 0);
                                    $chemquery->setQuery("SELECT * FROM trfchemicalagent LEFT JOIN chemicalagent ON trfchemicalagent.idchemicalagent=chemicalagent.idchemicalagent WHERE trfchemicalagent.idtrf='$idtrftd'");
                                    $chemquery->execute();
                                    ?>
                                    <tbody>
                                        <?php while (!$chemquery->atEnd()) { ?>
                                            <tr>
                                                <td scope="row">
                                                    <?php echo $chemquery->getColumnVal("name_chemicalagent"); ?>
                                                </td>
                                                <td>
                                                    <select class="form-control" id="level_<?php echo $chemquery->getColumnVal("idtrfchemicalagent"); ?>" name="level" data-id="<?php echo $chemquery->getColumnVal("idtrfchemicalagent"); ?>" onchange="updateField(this)">
                                                        <?php
                                                        $selectedLevel = $chemquery->getColumnVal("level");
                                                        for ($i = 1; $i <= 6; $i++) {
                                                            $selected = ($i == $selectedLevel) ? "selected" : "";
                                                            echo "<option value='$i' $selected>$i</option>";
                                                        }
                                                        ?>
                                                    </select>
                                                </td>
                                                <td>
                                                    <input class="form-control" type="text" value="<?php echo $chemquery->getColumnVal("degradationpercentage"); ?>" id="degradationpercentage_<?php echo $chemquery->getColumnVal("idtrfchemicalagent"); ?>" name="degradationpercentage" maxlength="6" data-id="<?php echo $chemquery->getColumnVal("idtrfchemicalagent"); ?>" onblur="updateField(this)">
                                                </td>
                                                <input type="hidden" value="<?php echo $chemquery->getColumnVal("idtrfchemicalagent"); ?>" name="idtrfchemicalagent">
                                            </tr>
                                            <?php $chemquery->moveNext(); ?>
                                        <?php } ?>
                                        <?php $chemquery->moveFirst(); // Se hai bisogno di riutilizzare i risultati 
                                        ?>
                                    </tbody>
                                </table>
                            </div><!--end card-->
                        </div><!--end col-->
                    </div>

                    <script>
                        function updateField(element) {
                            var fieldName = element.name;
                            var fieldValue = element.value;
                            var id = element.getAttribute('data-id');

                            var xhr = new XMLHttpRequest();
                            xhr.open("POST", "update_field.php", true);
                            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                            xhr.onreadystatechange = function() {
                                if (xhr.readyState === 4 && xhr.status === 200) {
                                    element.style.backgroundColor = "lightgreen";
                                    setTimeout(function() {
                                        element.style.backgroundColor = "";
                                    }, 2000);
                                }
                            };
                            xhr.send("id=" + id + "&field=" + fieldName + "&value=" + fieldValue);
                        }
                    </script>


                <?php endif; ?>
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card card-body">
                            <form action="techdossier_adddocument.php" method="post">

                                <input type="hidden" class="form-control" value="<?php echo $idtrftd; ?>" id="idtrftd" name="idtrftd">

                                <input type="hidden" class="form-control" value="<?php echo $idtd; ?>" id="iddata_td" name="iddata_td">
                                <br>
                                <button class="btn btn-gradient-success waves-effect waves-light" type="submit"><?php echo $proceed; ?></button>
                                <a href="techdossier_step2.php?idtd=<?php echo $idtd; ?>&idtrftd=<?php echo $idtrftd; ?>"><button type="button" class="btn btn-dark waves-effect waves-light" onclick="history.back()"><?php echo $backstep; ?></button></a>
                                <a href="techdossier_stepsummarypreview.php?idtd=<?php echo $idtd; ?>&idtrftd=<?php echo $idtrftd; ?>" target='_blank'><button type="button" class="btn btn-dark waves-effect waves-light">Preview</button></a>

                            </form>
                        </div><!--end card-->
                    </div><!--end col-->
                </div>





            </div>
        </div>
        <!-- end page title end breadcrumb -->


    </div><!-- container -->
    <!-- footer start -->
    <?php include 'include/footer.php'; ?>
    </footer><!--end footer-->
    </div>
    <!-- end page content -->
    </div>
    <!-- end page-wrapper -->



    <!-- jQuery  -->

    <script src="assets/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/metismenu.min.js"></script>
    <script src="assets/js/waves.js"></script>
    <script src="assets/js/feather.min.js"></script>
    <script src="assets/js/jquery.slimscroll.min.js"></script>
    <script src="assets/js/jquery-ui.min.js"></script>




    <script src="../plugins/jquery-steps/jquery.steps.min.js"></script>
    <script src="assets/pages/jquery.form-wizard.init.js"></script>

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

</body>

</html>