<?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($_GET['idtd'])) {
    $idtd = $_GET['idtd'];
}
if (isset($_POST['idtd'])) {
    $idtd = $_POST['idtd'];
}

if (isset($idtd)) {

    // 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();
    $rowtd = $result->fetch_assoc();
    $idcompany = $rowtd['idcompany'];
    $tdnumber = $rowtd['tdnumber'];
    $tdrev = $rowtd['td_rev'];
    $stmt->close();
    $conn->close();
}
?>
<?php
if (isset($_GET['idtrf'])) {
    $idtrftd = $_GET['idtrf'];
}


$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 . ' REV.' . $trfrev;
$trftdnumber = $trfn . 'TF';
$artntype = $tdquery->getColumnVal("idarticletype");
?>
<?php

// Connessione al database
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$cat3yes = 'N'; // Presumi che non ci siano dpin uguali a 3 e che artntype non sia 1

// Assumi che $artntype sia definita altrove nel codice
// $artntype = 1; // esempio di inizializzazione se non definita altrove

// Prepara e esegui la query
$query = "SELECT iddpicategory FROM trfstandards WHERE idtrfdetails = ?";
$stmt = $conn->prepare($query);
if (!$stmt) {
    die('MySQL prepare error: ' . $conn->error);
}

$stmt->bind_param("s", $idtrftd);
$stmt->execute();
$result = $stmt->get_result();

// Itera su tutti i record restituiti
while ($row = $result->fetch_assoc()) {
    $dpin = $row['iddpicategory'];

    if ($dpin == 3) {
        $cat3yes = 'Y';
        break; // Interrompi il ciclo se trovi un dpin pari a 3 e artntype è 1
    }
}

$stmt->close();
$conn->close();


?>




<?php
// Assumendo che $idcompany sia definito da qualche parte nel tuo script o in una sessione

if (isset($idtrftd) && $idcompany) {
    // Preparazione della query per verificare l'esistenza del record
    $checkQuery = new WA_MySQLi_RS("checkQuery", $cmctrfdb, 1);
    $checkQuery->setQuery("SELECT COUNT(*) AS recordCount FROM data_td WHERE idtrf = ? AND idcompany = ?");
    $checkQuery->bindParam("s", $idtrftd, "-1"); // 's' per string, '-1' indica un parametro
    $checkQuery->bindParam("s", $idcompany, "-1"); // Aggiungi il secondo parametro
    $checkQuery->execute();

    $recordExists = $checkQuery->getColumnVal("recordCount") > 0;

    if (!$recordExists) {;
        // Ottieni l'ultimo valore di tdnumber
        $lastTdNumberQuery = new WA_MySQLi_RS("lastTdNumberQuery", $cmctrfdb, 1);
        $lastTdNumberQuery->setQuery("SELECT tdnumber FROM data_td ORDER BY tdnumber DESC LIMIT 1");
        $lastTdNumberQuery->execute();
        $lastTdNumber = $lastTdNumberQuery->getColumnVal("tdnumber");

        // Controlla se lastTdNumber è null o non è un valore numerico
        if ($lastTdNumber === null || !is_numeric($lastTdNumber)) {
            // Se non ci sono record o il valore non è numerico, imposta newTdNumber a 1
            $newTdNumber = 1;
        } else {
            // Altrimenti, incrementa l'ultimo numero di TD trovato
            $newTdNumber = $lastTdNumber + 1;
        }


        // Esegui l'INSERT con il nuovo tdnumber
        $InsertQuery = new WA_MySQLi_Query($cmctrfdb);
        $InsertQuery->Action = "insert";
        $InsertQuery->Table = "data_td";
        $InsertQuery->bindColumn("idtrf", "i", $idtrftd, "WA_DEFAULT");
        $InsertQuery->bindColumn("idcompany", "i", $idcompany, "WA_DEFAULT");
        $InsertQuery->bindColumn("iduser", "i", $iduserlog, "WA_DEFAULT");
        $InsertQuery->bindColumn("tdnumber", "s", $trftdnumber, "WA_DEFAULT"); // Usa il nuovo tdnumber
        $InsertQuery->saveInSession("");
        $InsertQuery->execute();
        $InsertGoTo = "";

        $InsertQuery->redirect($InsertGoTo);

        $idtd = $cmctrfdb->insert_id; // Recupera l'ID dell'ultimo inserimento
        //echo $idtd;
        $tdnumber = $trftdnumber;
        //insert fill risk area
        $conn = new mysqli($servername, $username, $password, $dbname);
        $selectQuery = "SELECT * FROM riskarea_td";
        $result = $conn->query($selectQuery);



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

            // Prepara l'array con gli idriskarea_td che devono avere coveredby settato a 'coverone'
            $idsForCoverOne = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];

            // Controlla se idriskarea_td è uguale a 24 o è nell'elenco per 'coverone'
            if ($riskRow['idriskarea_td'] == 24 || in_array($riskRow['idriskarea_td'], $idsForCoverOne)) {
                $insertQuery = "INSERT INTO fillrisk_td (idriskarea_td, applicable, idcompany, iddata_td, idtrf, coveredby) VALUES (?, ?, ?, ?, ?, ?)";
                $stmt = $conn->prepare($insertQuery);

                // Imposta il valore di coveredby a 'covertwo' o 'coverone' a seconda del caso
                $coveredbyValue = ($riskRow['idriskarea_td'] == 24) ? 'covertwo' : 'coverone';

                $stmt->bind_param("iiiiis", $riskRow['idriskarea_td'], $applicableValue, $idcompany, $idtd, $idtrftd, $coveredbyValue);
            } else {
                // Altrimenti, usa la query di inserimento originale senza 'coveredby'
                $insertQuery = "INSERT INTO fillrisk_td (idriskarea_td, applicable, idcompany, iddata_td, idtrf) VALUES (?, ?, ?, ?, ?)";
                $stmt = $conn->prepare($insertQuery);

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

            $stmt->execute();
        }
    }
}

// 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();
$rowtd = $result->fetch_assoc();
$tdnumber = $rowtd['tdnumber'];
$tdrev = $rowtd['td_rev'];
$stmt->close();
$conn->close();

?>

<!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="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 src="https://media.ethicalads.io/media/client/ethicalads.min.js"></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">
    <!--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.addEventListener('DOMContentLoaded', function() {
            var select = document.getElementById('productionplace_same');
            var addButton = document.getElementById('addProductionPlaceBtn');
            var table = document.getElementById('productionPlaceTable'); // Riferimento alla tabella

            select.addEventListener('change', function() {
                // Mostra il bottone e la tabella se l'opzione "No" è selezionata
                if (this.value === 'N') {
                    addButton.style.display = '';
                    table.style.display = ''; // Mostra la tabella
                } else {
                    addButton.style.display = 'none';
                    table.style.display = 'none'; // Nasconde la tabella
                }
            });

            // Verifica lo stato iniziale
            if (select.value === 'N') {
                addButton.style.display = '';
                table.style.display = ''; // Mostra la tabella
            }
        });
    </script>
    <style>
        #qualcheckText img {
            width: auto !important;
            height: auto !important;
            max-width: none !important;
            max-height: none !important;
        }
    </style>
</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; ?> - TF: <?php echo $tdnumber; ?>-Rev.<?php echo $tdrev; ?></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 -->
                    <?php //query location place
                    // Assumendo che $idt sia già definito e sanificato per prevenire SQL Injection

                    $conn = new mysqli($servername, $username, $password, $dbname);
                    $query = "SELECT idcontactstd, companyName, address, city FROM contacts_td WHERE idtd = ?";
                    $stmt = $conn->prepare($query);
                    $stmt->bind_param("i", $idtd); // "i" indica che il parametro è un intero
                    $stmt->execute();
                    $result = $stmt->get_result();

                    $rows = [];
                    while ($row = $result->fetch_assoc()) {
                        $rows[] = $row;
                    }
                    $stmt->close();

                    ?>

                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-body">
                                <form action="techdossier_step2.php" method="post">
                                    <div class="alert alert-primary alert-dismissible fade show" role="alert">
                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close"></button>
                                        <?php echo $prodplace; ?>
                                    </div>
                                    <div class="form-material">
                                        <label class="my-3"><?php echo $prodplacemanufacturer; ?></label>
                                        <select class="form-control data-field" data-column="productionplace_same" id="productionplace_same" name="productionplace_same">
                                            <option value="Y" <?php echo (isset($rowtd['productionplace_same']) && $rowtd['productionplace_same'] == 'Y') ? 'selected' : ''; ?>><?php echo $yes; ?></option>
                                            <option value="N" <?php echo (isset($rowtd['productionplace_same']) && $rowtd['productionplace_same'] == 'N') ? 'selected' : ''; ?>><?php echo $no; ?></option>
                                        </select><br>
                                        <button type="button" id="addProductionPlaceBtn" class="btn btn-info waves-effect waves-primary" onclick="openProductionPlacePopup()"><?php echo $addprodplace; ?></button>
                                        <!-- Tabella che viene mostrata/nascosta insieme al bottone -->
                                        <br>
                                        <div id="productionPlaceTable" style="display: none;"> <!-- Inizialmente nascosta -->
                                            <table class="table">
                                                <thead>
                                                    <tr>
                                                        <th>CompanyName</th>
                                                        <th>Address</th>
                                                        <th>City</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($rows as $row) : ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($row['companyName']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['address']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['city']); ?></td>
                                                            <td>
                                                                <span class="deleteBtn" data-id="<?php echo $row['idcontactstd']; ?>" style="color: red; cursor: pointer;">
                                                                    <i class="fas fa-trash-alt"></i>
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                        <br><br>

                                        <div class="alert alert-primary alert-dismissible fade show" role="alert">
                                            <?php echo $datappe; ?>
                                        </div>
                                        <?php if ($artntype == 1) : ?>
                                            <label class="my-3"><?php echo $classificationshoes; ?></label>
                                            <select class="form-control data-field" required data-column="classificationshoes" id="classificationshoes" name="classificationshoes">
                                                <option value="" <?php echo empty($rowtd['classificationshoes']) ? 'selected' : ''; ?>>Seleziona/Select</option>
                                                <option value="classone" <?php echo (isset($rowtd['classificationshoes']) && $rowtd['classificationshoes'] == 'classone') ? 'selected' : ''; ?>><?php echo $classone; ?></option>
                                                <option value="classtwo" <?php echo (isset($rowtd['classificationshoes']) && $rowtd['classificationshoes'] == 'classtwo') ? 'selected' : ''; ?>><?php echo $classtwo; ?></option>
                                            </select>
                                        <?php endif; ?>




                                        <label class="my-3"><?php echo $destinationppe; ?></label>
                                        <input type="text" id="destinationuseppe" required name="destinationuseppe" class="form-control data-field" data-column="destinationuseppe" required placeholder="<?php echo $destinationppe; ?>" value="<?php echo isset($rowtd['destinationuseppe']) ? htmlspecialchars($rowtd['destinationuseppe'], ENT_QUOTES, 'UTF-8') : ''; ?>">

                                        <label class="my-3"><?php echo $workingprocess; ?></label>
                                        <input class="form-control data-field" required data-column="manufacutringprocess" id="manufacutringprocess" name="manufacutringprocess" required placeholder="<?php echo $workingprocess; ?>" value="<?php echo isset($rowtd['manufacutringprocess']) ? htmlspecialchars($rowtd['manufacutringprocess'], ENT_QUOTES, 'UTF-8') : ''; ?>">

                                        <label class="my-3"><?php echo $ageingppe; ?></label>
                                        <select class="form-control data-field" data-column="ppeageing" id="ppeageing" name="ppeageing">
                                            <option value="Y" <?php echo (isset($rowtd['ppeageing']) && $rowtd['ppeageing'] == 'Y') ? 'selected' : ''; ?>><?php echo $yes; ?></option>

                                        </select>

                                        <label class="my-3"><?php echo $obsoldate; ?> </label>
                                        <input type="text" class="form-control data-field" placeholder="<?php echo $obsoldate; ?>" data-column="obsolescencedeadline" id="obsolescencedeadline" required name="obsolescencedeadline" value="<?php echo isset($rowtd['obsolescencedeadline']) ? htmlspecialchars($rowtd['obsolescencedeadline'], ENT_QUOTES, 'UTF-8') : ''; ?>">
                                        <br>

                                        <label class="my-3"><?php echo $techapplied; ?></label>
                                        <input type="text" class="form-control data-field" placeholder="<?php echo $techapplied; ?>" data-column="techspecificationapplied" id="techspecificationapplied" required name="techspecificationapplied" value="<?php echo isset($rowtd['techspecificationapplied']) ? htmlspecialchars($rowtd['techspecificationapplied'], ENT_QUOTES, 'UTF-8') : ''; ?>">
                                        <br>

                                        <label class="my-3"><?php echo $corrtdcertified; ?></label>
                                        <input type="text" class="form-control data-field" placeholder="<?php echo $corrtdcertified; ?>" data-column="dpialreadycerttificate" id="dpialreadycerttificate" name="dpialreadycerttificate" value="<?php echo isset($rowtd['dpialreadycerttificate']) ? htmlspecialchars($rowtd['dpialreadycerttificate'], ENT_QUOTES, 'UTF-8') : ''; ?>">



                                        <label class="my-3">Eventuali note</label>
                                        <input type="text" class="form-control data-field" placeholder="Eventuali Note" data-column="dpinote" id="dpinote" name="dpinote" value="<?php echo isset($rowtd['dpinote']) ? htmlspecialchars($rowtd['dpinote'], ENT_QUOTES, 'UTF-8') : ''; ?>">
                                        <br>
                                        <div class="alert alert-primary alert-dismissible fade show" role="alert">
                                            <?php echo $ceexample; ?>
                                        </div>

                                        <label class="my-3"><?php echo $uploadExample; ?></label>
                                        <select class="form-control data-field" data-column="cemarkupload" id="cemarkUploadSelect" name="cemarkupload">
                                            <option value="N" <?php echo (isset($rowtd['cemarkupload']) && $rowtd['cemarkupload'] == 'N') ? 'selected' : ''; ?>>
                                                <?php echo ($_SESSION['langselect'] == 'en') ? 'No' : 'No'; ?>
                                            </option>
                                            <option value="Y" <?php echo (isset($rowtd['cemarkupload']) && $rowtd['cemarkupload'] == 'Y') ? 'selected' : ''; ?>>
                                                <?php echo ($_SESSION['langselect'] == 'en') ? 'Yes' : 'Sì'; ?>
                                            </option>
                                        </select>

                                        <div id="inputFieldsSection" <?php echo (isset($rowtd['cemarkupload']) && $rowtd['cemarkupload'] == 'N') ? '' : 'style="display: none;"'; ?>>
                                            <label class="my-3"><?php echo $positionmark; ?></label>
                                            <input type="text" class="form-control data-field" placeholder="<?php echo $positionmark; ?>" data-column="localisationppemarking" id="localisationppemarking" name="localisationppemarking" value="<?php echo isset($rowtd['localisationppemarking']) ? htmlspecialchars($rowtd['localisationppemarking'], ENT_QUOTES, 'UTF-8') : ''; ?>">

                                            <?php
                                            // Connessione al database
                                            $conn = new mysqli($servername, $username, $password, $dbname);
                                            if ($conn->connect_error) {
                                                die("Connection failed: " . $conn->connect_error);
                                            }

                                            // Query al database
                                            $query = "SELECT idlogo_td, descriptionlogo, filenamelogo FROM logo_td WHERE idcompany = ?";
                                            $stmt = $conn->prepare($query);
                                            $stmt->bind_param("i", $idcompany);
                                            $stmt->execute();
                                            $result = $stmt->get_result();

                                            // Inizia le opzioni con un'opzione di default che funge da prompt
                                            $options = "<option value=''>$selectLogo</option>";

                                            if ($result->num_rows > 0) {
                                                while ($row = $result->fetch_assoc()) {
                                                    $id = htmlspecialchars($row['idlogo_td'], ENT_QUOTES, 'UTF-8');
                                                    $description = htmlspecialchars($row['descriptionlogo'], ENT_QUOTES, 'UTF-8');
                                                    $filename = htmlspecialchars($row['filenamelogo'], ENT_QUOTES, 'UTF-8');
                                                    // Aggiunge ogni logo come opzione
                                                    $options .= "<option value='{$id}' data-filenamelogo='{$filename}'>{$description}</option>";
                                                }
                                            } else {
                                                // Aggiungi un'opzione se non ci sono loghi disponibili
                                                $options .= "<option value=''>$noLogoAvailable</option>";
                                            }
                                            $stmt->close();
                                            $conn->close();
                                            ?>

                                            <label class="my-3"><?php echo $manufacturerlogo; ?></label>
                                            <select class="form-control data-field" data-column="manufacturerlogoid" id="logoSelection" name="manufacturerlogoid">
                                                <?php echo $options; ?>
                                            </select><br>
                                            <a href="javascript:void(0);" onclick="openPopup()" style="font-size: small; text-decoration: underline; color: blue;"><?php echo $addLogo; ?></a>

                                            <img id="selectedLogo" src="" alt="Selected Logo" style="max-width: 100px; margin-top: 10px; display: none;">

                                            <script>
                                                document.getElementById('logoSelection').addEventListener('change', function() {
                                                    var selectedOption = this.options[this.selectedIndex];
                                                    var filename = selectedOption.getAttribute('data-filenamelogo');
                                                    if (filename) {
                                                        document.getElementById('selectedLogo').src = 'logos/' + filename; // Assicurati che il percorso sia corretto
                                                        document.getElementById('selectedLogo').style.display = 'block';
                                                    } else {
                                                        document.getElementById('selectedLogo').style.display = 'none';
                                                    }
                                                });
                                            </script>
                                            <br>

                                            <label class="my-3"><?php echo $measureex; ?></label>
                                            <input type="text" class="form-control data-field" placeholder="<?php echo $measureex; ?>" data-column="sizeexamplecemark" id="sizeexamplecemark" name="sizeexamplecemark" value="<?php echo isset($rowtd['sizeexamplecemark']) ? htmlspecialchars($rowtd['sizeexamplecemark'], ENT_QUOTES, 'UTF-8') : ''; ?>">

                                            <label class="my-3"><?php echo $monthyearprod; ?></label>
                                            <input type="month" class="form-control data-field" placeholder="<?php echo $monthyearprod; ?>" data-column="monthyearprod" id="monthyearprod" name="monthyearprod" value="<?php echo isset($rowtd['monthyearprod']) ? htmlspecialchars($rowtd['monthyearprod'], ENT_QUOTES, 'UTF-8') : ''; ?>">

                                            <label class="my-3"><?php echo $lotnumb; ?></label>
                                            <input type="text" class="form-control data-field" placeholder="<?php echo $lotnumb; ?>" data-column="serialbatchnumber" id="serialbatchnumber" name="serialbatchnumber" value="<?php echo isset($rowtd['serialbatchnumber']) ? htmlspecialchars($rowtd['serialbatchnumber'], ENT_QUOTES, 'UTF-8') : ''; ?>">

                                            <?php if ($cat3yes == 'Y') : ?>
                                                <label class="my-3">Numero Organismo Notificato scelto per la sorveglianza Modulo C2 o D</label>
                                                <input type="text" class="form-control data-field" placeholder="Inserisci un numero di quattro cifre" pattern="^\d{4}$" title="Inserisci un numero di quattro cifre" data-column="organismnumber" id="organismnumber" name="organismnumber" value="<?php echo isset($rowtd['organismnumber']) ? htmlspecialchars($rowtd['organismnumber'], ENT_QUOTES, 'UTF-8') : ''; ?>" oninput="validateFourDigits(this)">
                                            <?php endif; ?>

                                            <label class="my-3"><?php echo $standarduse; ?></label>
                                            <input type="text" class="form-control data-field" placeholder="<?php echo $standarduse; ?>" data-column="standarduse" id="standarduse" name="standarduse" value="<?php echo isset($rowtd['standarduse']) ? htmlspecialchars($rowtd['standarduse'], ENT_QUOTES, 'UTF-8') : ''; ?>">

                                            <label class="my-3"><?php echo $symbol; ?></label>
                                            <input type="text" class="form-control data-field" placeholder="<?php echo $symbol; ?>" data-column="symbolsaddreq" id="symbolsaddreq" name="symbolsaddreq" value="<?php echo isset($rowtd['symbolsaddreq']) ? htmlspecialchars($rowtd['symbolsaddreq'], ENT_QUOTES, 'UTF-8') : ''; ?>">
                                        </div>

                                        <script>
                                            function validateFourDigits(input) {
                                                // Rimuove qualsiasi carattere non numerico
                                                input.value = input.value.replace(/\D/g, '');
                                                // Controlla se l'input ha più di quattro cifre e lo tronca se necessario
                                                if (input.value.length > 4) {
                                                    input.value = input.value.slice(0, 4);
                                                }
                                            }
                                        </script>

                                        <div id="fileUploadSection" <?php echo isset($rowtd['cemarkupload']) && $rowtd['cemarkupload'] == 'Y' ? '' : 'style="display: none;"'; ?>>
                                            <form></form>
                                            <form action="upload_mark.php" method="post" id="uploadFormMark" name="uploadFormMark" enctype="multipart/form-data">
                                                <label class="my-3"><?php echo ($_SESSION['langselect'] == 'en') ? 'Upload the file:' : 'Carica il file:'; ?></label>
                                                <?php
                                                // Connessione al database
                                                $conn = new mysqli($servername, $username, $password, $dbname);
                                                $querytdfile = "SELECT idtdfileattached, filename_fileattached, description_fileattached FROM tdfileattached WHERE iddata_td = ? AND description_fileattached = 'CE mark example'";
                                                $stmt = $conn->prepare($querytdfile);
                                                $stmt->bind_param("i", $idtd);
                                                $stmt->execute();
                                                $resulttdfile = $stmt->get_result();

                                                $fileUploaded = $resulttdfile->num_rows > 0;
                                                ?>
                                                <input type="file" class="form-control-file" id="exampleCemarkFile" name="exampleCemarkFile">
                                                <input type="hidden" class="form-control-file" id="idtd" name="idtd" value="<?php echo $idtd; ?>">
                                                <input type="hidden" class="form-control-file" id="idtrftd" name="idtrftd" value="<?php echo $idtrftd; ?>">
                                                <!-- Aggiungi altri input o elementi HTML necessari per il caricamento del file -->
                                                <br>
                                                <button type="submit" id="uploadButtonmark1" class="btn btn-primary" <?php echo $fileUploaded ? 'disabled' : ''; ?>>
                                                    Carica
                                                </button>
                                                <span id="loadingSpinner" class="spinner-border spinner-border-sm" role="status" aria-hidden="true" style="display: none;"></span>

                                                <?php if ($fileUploaded): ?>
                                                    <small class="text-muted d-block mt-1">
                                                        (rimuovi l'immagine presente prima di metterne una nuova / remove the current image before uploading a new one)
                                                    </small>
                                                <?php endif; ?>
                                            </form><br><br>
                                            UPLOADED FILES
                                            <?php
                                            if ($fileUploaded) {
                                                // Inizia la tabella
                                                echo "<table class='table'>";
                                                echo "<thead><tr><th>" . ($_SESSION['langselect'] == 'en' ? 'Preview' : 'Anteprima') . "</th><th>" . ($_SESSION['langselect'] == 'en' ? 'File' : 'File') . "</th><th>" . ($_SESSION['langselect'] == 'en' ? 'Action' : 'Azione') . "</th></tr></thead>";
                                                echo "<tbody>";
                                                while ($rowtdfile = $resulttdfile->fetch_assoc()) {
                                                    $filePath = 'uploadtddocuments/' . htmlspecialchars($rowtdfile['filename_fileattached']);
                                                    $fileDescription = htmlspecialchars($rowtdfile['description_fileattached']);
                                                    $fileExtension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));

                                                    echo "<tr>";
                                                    // Colonna dell'anteprima
                                                    if (in_array($fileExtension, ['jpg', 'jpeg', 'png', 'gif'])) {
                                                        echo "<td><img src='$filePath' alt='$fileDescription' style='width: 100px; height: auto;'></td>";
                                                    } else {
                                                        echo "<td><a href='$filePath' target='_blank'>$fileDescription</a></td>";
                                                    }
                                                    // Colonna del file (solo link se non è un'immagine)
                                                    echo "<td><a href='$filePath' target='_blank'>$fileDescription</a></td>";
                                                    // Colonna dell'icona di cancellazione
                                                    echo "<td><button class='deleteFileBtn' style='color: red; background: none; border: none; cursor:pointer;' data-fileid='" . $rowtdfile['idtdfileattached'] . "' data-iddata='" . $idtd . "' data-idtrf='" . $idtrftd . "'><i class='fas fa-trash'></i></button></td>";
                                                    echo "</tr>";
                                                }
                                                echo "</tbody>";
                                                echo "</table>";
                                            } else {
                                                echo "Nessun file caricato.";
                                            }
                                            $stmt->close();
                                            ?>
                                        </div>

                                        <script>
                                            document.getElementById('uploadButtonmark').addEventListener('click', function(clickEvent) {
                                                var fileInput = document.getElementById('exampleCemarkFile');
                                                if (fileInput.files.length > 0) {
                                                    //this.disabled = true;
                                                    //fileInput.disabled = true;
                                                    document.getElementById('loadingSpinner').style.display = 'inline-block';

                                                    const domEvent = document.createEvent('Event');
                                                    domEvent.initEvent('submit', false, true);
                                                    clickEvent.target.closest('form').dispatchEvent(domEvent);

                                                    //document.getElementById('uploadFormMark').submit();
                                                } else {
                                                    Swal.fire({
                                                        title: 'Nessun file selezionato',
                                                        text: 'Per favore seleziona un file da caricare.',
                                                        icon: 'warning',
                                                        confirmButtonText: 'OK'
                                                    });
                                                }
                                            });

                                            document.getElementById('uploadFormMark').addEventListener('submit', function(event) {
                                                var fileInput = document.getElementById('exampleCemarkFile');
                                                if (fileInput.files.length > 0) {
                                                    //document.getElementById('uploadButtonmark').disabled = true;
                                                    //fileInput.disabled = true;
                                                    document.getElementById('loadingSpinner').style.display = 'inline-block';

                                                    document.getElementById('uploadFormMark').submit();
                                                } else {
                                                    event.preventDefault();
                                                    Swal.fire({
                                                        title: 'Nessun file selezionato',
                                                        text: 'Per favore seleziona un file da caricare.',
                                                        icon: 'warning',
                                                        confirmButtonText: 'OK'
                                                    });
                                                }
                                            });
                                        </script>
                                        <script>
                                            document.addEventListener('DOMContentLoaded', function() {
                                                document.querySelectorAll('.deleteFileBtn').forEach(button => {
                                                    button.addEventListener('click', function(event) {
                                                        event.preventDefault(); // Impedisce il comportamento predefinito
                                                        event.stopPropagation(); // Impedisce la propagazione dell'evento al form

                                                        const fileId = this.getAttribute('data-fileid');
                                                        const iddataTd = this.getAttribute('data-iddata');
                                                        const idtrf = this.getAttribute('data-idtrf');

                                                        Swal.fire({
                                                            title: 'Sei sicuro di voler cancellare questo file?',
                                                            icon: 'warning',
                                                            showCancelButton: true,
                                                            confirmButtonColor: '#3085d6',
                                                            cancelButtonColor: '#d33',
                                                            confirmButtonText: 'Sì, cancella!',
                                                            cancelButtonText: 'No, chiudi!'
                                                        }).then((result) => {
                                                            if (result.isConfirmed) {
                                                                window.location.href = 'delete_filetd.php?idfile=' + fileId + '&iddata_td=' + iddataTd + '&idtrf=' + idtrf;
                                                            }
                                                        });
                                                    });
                                                });
                                            });
                                        </script>
                                        <script>
                                            document.addEventListener('DOMContentLoaded', function() {
                                                var handleCemarkSelection = function() {
                                                    var selectedOption = document.getElementById('cemarkUploadSelect').value;
                                                    var inputFieldsSection = document.getElementById('inputFieldsSection');
                                                    var fileUploadSection = document.getElementById('fileUploadSection');

                                                    if (selectedOption === 'Y') {
                                                        inputFieldsSection.style.display = 'none';
                                                        fileUploadSection.style.display = 'block';
                                                    } else {
                                                        inputFieldsSection.style.display = 'block';
                                                        fileUploadSection.style.display = 'none';
                                                    }
                                                };

                                                // Imposta il listener per il cambio di selezione
                                                document.getElementById('cemarkUploadSelect').addEventListener('change', handleCemarkSelection);

                                                // Chiama la funzione handleCemarkSelection al caricamento per impostare la visibilità iniziale
                                                handleCemarkSelection();
                                            });
                                        </script>


                                        <br>
                                        <div class="alert alert-primary alert-dismissible fade show" role="alert">
                                            <?php echo $controllgaranty; ?>
                                        </div>

                                        <?php

                                        // Connessione al database
                                        $conn = new mysqli($servername, $username, $password, $dbname);

                                        // Controlla la connessione
                                        if ($conn->connect_error) {
                                            die("Connessione fallita: " . $conn->connect_error);
                                        }

                                        // Query al database
                                        $queryqual = "SELECT idqualcheck_td, descriptionqualcheck, qualchecktext FROM qualcheck_td WHERE idcompany = ?";
                                        $stmt = $conn->prepare($queryqual);

                                        if ($stmt) {
                                            $stmt->bind_param("i", $idcompany); // Assumi che $idcompany sia già definita e pulita
                                            $stmt->execute();
                                            $resultqual = $stmt->get_result();

                                            // Inizia le opzioni con un'opzione di default che funge da prompt
                                            $options = "<option value=''>$selectQualityControl </option>";

                                            if ($resultqual->num_rows > 0) {

                                                while ($row = $resultqual->fetch_assoc()) {

                                                    $id = htmlspecialchars($row['idqualcheck_td'], ENT_QUOTES, 'UTF-8');
                                                    $descriptionqualcheck = htmlspecialchars($row['descriptionqualcheck'], ENT_QUOTES, 'UTF-8');
                                                    $qualchecktext = htmlspecialchars($row['qualchecktext'], ENT_QUOTES, 'UTF-8');

                                                    // Controlla se l'ID corrente corrisponde a quello preselezionato
                                                    // Controlla se 'proddescription' non è nullo o vuoto e se l'ID corrente corrisponde a quello preselezionato
                                                    $selected = (!empty($rowtd['proddescription']) && $id == $rowtd['proddescription']) ? ' selected' : '';


                                                    // Aggiunge ogni elemento come opzione, includendo 'selected' se necessario
                                                    $options .= "<option value='{$id}'{$selected} data-qualchecktext='{$qualchecktext}'>{$descriptionqualcheck}</option>";
                                                }
                                            } else {
                                                // Aggiungi un'opzione se non ci sono elementi disponibili
                                                $options .= "<option value=''>Nessun controllo di qualità disponibile</option>";
                                            }
                                            $stmt->close();
                                        } else {
                                            echo "Errore durante la preparazione della query: " . $conn->error;
                                        }

                                        $conn->close();
                                        ?>

                                        <label class="my-3"><?php echo $productionControlDescription; ?></label>
                                        <select class="form-control data-field" data-column="proddescription" id="proddesc" name="proddescription">
                                            <?php echo $options; ?>
                                        </select><br>

                                        <div id="qualcheckText"></div>

                                        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
                                        <script>
                                            $(document).ready(function() {
                                                // Funzione per aggiornare il testo qualcheck
                                                function updateQualcheckText() {
                                                    var selectedText = $('#proddesc').find('option:selected').attr('data-qualchecktext');
                                                    $('#qualcheckText').html(selectedText || 'Seleziona un controllo di qualità per visualizzarne i dettagli.');
                                                }

                                                // Gestore per il cambiamento di selezione
                                                $('#proddesc').change(updateQualcheckText);

                                                // Chiamata iniziale per impostare il testo all'avvio
                                                updateQualcheckText();
                                            });
                                        </script>
                                        <br>
                                        <a href="javascript:void(0);" onclick="openPopup2()" style="font-size: small; text-decoration: underline; color: blue;"><?php echo $addControlMeans; ?></a><br>

                                        <br>





                                        <label class="my-3"><?php echo $packaginginfo; ?></label>
                                        <input type="text" class="form-control data-field" placeholder="<?php echo $packaginginfo; ?>" data-column="packaging" id="packaging" name="packaging" value="<?php echo isset($rowtd['packaging']) ? htmlspecialchars($rowtd['packaging'], ENT_QUOTES, 'UTF-8') : ''; ?>">
                                        <br>
                                        <div class="alert alert-primary alert-dismissible fade show" role="alert">
                                            <?php echo $uedeclaration; ?>
                                        </div>

                                        <label class="my-3"><?php echo $uedeclaration; ?></label>
                                        <select class="form-control data-field" data-column="declarconformity" id="declarconformity" name="declarconformity">
                                            <option value="" <?php echo empty($rowtd['declarconformity']) ? 'selected' : ''; ?>>Seleziona/Select</option>
                                            <option value="declarone" <?php echo (isset($rowtd['declarconformity']) && $rowtd['declarconformity'] == 'declarone') ? 'selected' : ''; ?>><?php echo $declarone; ?></option>
                                            <option value="declartwo" <?php echo (isset($rowtd['declarconformity']) && $rowtd['declarconformity'] == 'declartwo') ? 'selected' : ''; ?>><?php echo $declartwo; ?></option>
                                        </select>

                                        <label class="my-3" id="webaddressLabel"><?php echo $webaddress; ?></label>
                                        <input type="text" class="form-control data-field" placeholder="<?php echo $webaddress; ?>" data-column="webaddress" id="webaddress" name="webaddress" value="<?php echo isset($rowtd['webaddress']) ? htmlspecialchars($rowtd['webaddress'], ENT_QUOTES, 'UTF-8') : ''; ?>">

                                        <script>
                                            document.addEventListener('DOMContentLoaded', function() {
                                                var declarconformity = document.getElementById('declarconformity');
                                                var webaddressLabel = document.getElementById('webaddressLabel');
                                                var webaddress = document.getElementById('webaddress');

                                                // Nascondi o mostra l'input webaddress e la relativa label in base alla selezione dell'opzione declarconformity
                                                declarconformity.addEventListener('change', function() {
                                                    if (declarconformity.value === 'declarone') {
                                                        webaddress.style.display = 'none';
                                                        webaddressLabel.style.display = 'none';
                                                    } else {
                                                        webaddress.style.display = 'block';
                                                        webaddressLabel.style.display = 'block';
                                                    }
                                                });

                                                // Inizializzazione dello stato iniziale in base alla selezione iniziale
                                                if (declarconformity.value === 'declarone') {
                                                    webaddress.style.display = 'none';
                                                    webaddressLabel.style.display = 'none';
                                                } else {
                                                    webaddress.style.display = 'block';
                                                    webaddressLabel.style.display = 'block';
                                                }
                                            });
                                        </script>

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

                                        <input type="hidden" class="form-control data-field" value="<?php echo $tdnumbern; ?>" id="tdnumber" name="tdnumber">

                                        <input type="hidden" class="form-control data-field" 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>
                                        <button type="button" class="btn btn-dark waves-effect waves-light" onclick="history.back()"><?php echo $backstep; ?></button>
                                        <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>

                                    </div>
                                </form>


                                <script>
                                    ClassicEditor
                                        .create(document.querySelector('#editor'))
                                        .catch(error => {
                                            console.error(error);
                                        });
                                </script>
                                <script>
                                    document.addEventListener('DOMContentLoaded', function() {
                                        var select = document.getElementById('productionplace_same');
                                        var addButton = document.getElementById('addProductionPlaceBtn');
                                        var table = document.getElementById('productionPlaceTable'); // Riferimento alla tabella

                                        function toggleButtonAndTable() {
                                            // Mostra il bottone e la tabella se l'opzione "No" è selezionata
                                            if (select.value === 'N') {
                                                addButton.style.display = 'block'; // Modifica qui per assicurarti che sia visibile
                                                table.style.display = 'block'; // Mostra la tabella
                                            } else {
                                                addButton.style.display = 'none'; // Nasconde il bottone
                                                table.style.display = 'none'; // Nasconde la tabella
                                            }
                                        }

                                        select.addEventListener('change', toggleButtonAndTable);

                                        // Chiamata alla funzione per verificare lo stato iniziale
                                        toggleButtonAndTable();
                                    });
                                </script>
                                <script>
                                    document.addEventListener('DOMContentLoaded', function() {
                                        document.querySelectorAll('.deleteBtn').forEach(span => {
                                            span.addEventListener('click', function() {
                                                const id = this.getAttribute('data-id');
                                                console.log("ID da cancellare:", id); // Aggiunto per il debug
                                                if (confirm('Sei sicuro di voler cancellare questa riga?')) {
                                                    // Invio richiesta AJAX per cancellare la riga
                                                    fetch('delete_row.php', {
                                                            method: 'POST',
                                                            headers: {
                                                                'Content-Type': 'application/x-www-form-urlencoded',
                                                            },
                                                            body: 'id=' + id
                                                        })
                                                        .then(response => {
                                                            // Stampa la risposta in console per il debug
                                                            console.log('Risposta dal server:', response);

                                                            // Parse della risposta JSON
                                                            return response.json();
                                                        })
                                                        .then(data => {
                                                            // Stampa i dati JSON in console per il debug
                                                            console.log('Dati JSON:', data);

                                                            // Gestione dei dati JSON
                                                            if (data.success) {
                                                                this.closest('tr').remove();
                                                                setTimeout(function() {
                                                                    location.reload(); // Aggiorna la pagina dopo un breve ritardo
                                                                }, 500); // Ritardo di 500 millisecondi
                                                            } else {
                                                                alert('Errore nella cancellazione');
                                                            }
                                                        })
                                                        .catch(error => console.error('Errore:', error));
                                                }
                                            });
                                        });
                                    });
                                </script>


                                <script>
                                    function openProductionPlacePopup() {
                                        // Ottieni il valore di $idtd
                                        var idtd = <?php echo $idtd; ?>;
                                        // Costruisci l'URL includendo $idtd come query string
                                        var url = "production-place.php?idtd=" + idtd;
                                        // Apri il popup con l'URL costruito
                                        var popupWindow = window.open(url, "Popup", "width=900,height=650,scrollbars=yes,resizable=yes");
                                    }
                                </script>
                                <script>
                                    function openPopup() {
                                        var idcompany = '<?php echo $idcompany; ?>';
                                        var popupUrl = 'logopopup.php?idcompany=' + encodeURIComponent(idcompany);
                                        var popupWidth = 800;
                                        var popupHeight = 700;
                                        var popupLeft = (screen.width - popupWidth) / 2;
                                        var popupTop = (screen.height - popupHeight) / 2;
                                        var popupOptions = 'width=' + popupWidth + ',height=' + popupHeight + ',top=' + popupTop + ',left=' + popupLeft;
                                        window.open(popupUrl, 'Aggiungi Logo', popupOptions);
                                    }
                                </script>
                                <script>
                                    function openPopup2() {
                                        var idcompany = '<?php echo $idcompany; ?>';
                                        var popupUrl = 'qualcheck.php?idcompany=' + encodeURIComponent(idcompany);
                                        var popupWidth = 1000;
                                        var popupHeight = 700;
                                        var popupLeft = (screen.width - popupWidth) / 2;
                                        var popupTop = (screen.height - popupHeight) / 2;
                                        var popupOptions = 'width=' + popupWidth + ',height=' + popupHeight + ',top=' + popupTop + ',left=' + popupLeft;
                                        window.open(popupUrl, 'Aggiungi Logo', popupOptions);
                                    }
                                </script>

                                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
                                <script>
                                    function updateSelectDropdown() {
                                        $.ajax({
                                            url: 'getLogoOptions.php', // Questo script PHP restituisce le nuove opzioni della tendina
                                            type: 'GET',
                                            data: {
                                                idcompany: '<?= $idcompany ?>'
                                            }, // Passa eventuali parametri necessari
                                            success: function(data) {
                                                $('#logoSelection').html(data); // Aggiorna il contenuto della tendina
                                            }
                                        });
                                    }
                                </script>
                                <script>
                                    document.addEventListener('DOMContentLoaded', function() {
                                        document.querySelectorAll('.data-field').forEach(input => {
                                            input.addEventListener('blur', function() {
                                                const column = this.getAttribute('data-column');
                                                const value = this.value;
                                                const idtd = '<?php echo $idtd; ?>'; // ID del record da aggiornare

                                                fetch('update_data_td.php', {
                                                        method: 'POST',
                                                        headers: {
                                                            'Content-Type': 'application/x-www-form-urlencoded',
                                                        },
                                                        body: `column=${column}&value=${encodeURIComponent(value)}&idtd=${idtd}`
                                                    })
                                                    .then(response => response.json())
                                                    .then(data => {
                                                        if (data.success) {
                                                            // Cambia il colore di sfondo in verde, poi ritorna al colore originale dopo 2 secondi
                                                            this.style.backgroundColor = '#d4edda';
                                                            setTimeout(() => {
                                                                this.style.backgroundColor = '';
                                                            }, 2000);
                                                        } else {
                                                            alert(data.message);
                                                        }
                                                    })
                                                    .catch(error => {
                                                        console.error('Errore:', error);
                                                        alert('Si è verificato un errore');
                                                    });
                                            });
                                        });
                                    });
                                </script>


                            </div>
                        </div><!--end card-body-->
                    </div><!--end card-->
                </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>