<?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['iddata_td'])) {
    $idtd = $_GET['iddata_td'];
}
if (isset($_GET['idtd'])) {
    $idtd = $_GET['idtd'];
}
if (isset($_POST['idtd'])) {
    $idtd = $_POST['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 LEFT JOIN logo_td ON data_td.manufacturerlogoid=logo_td.idlogo_Td LEFT JOIN qualcheck_td ON data_td.proddescription=qualcheck_td.idqualcheck_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();
$prodplace = $row['productionplace_same'];
$classshoes = $row['classificationshoes'];
$stmt->close();
$conn->close();
?>
<?php
$tdquery = new WA_MySQLi_RS("tdquery", $cmctrfdb, 1);
$tdquery->setQuery("SELECT * FROM `trf-details` LEFT JOIN modelarticle ON modelarticle.idmodelarticle=`trf-details`.model  WHERE `trf-details`.idtrfdetails='$idtrftd'");
$tdquery->execute();

$description = $tdquery->getColumnVal("sample_description");
$trfn = $tdquery->getColumnVal("trfnumber");
$trfrev  = $tdquery->getColumnVal("revtrf");
$trfnumb = $trfn . ' VER.' . $trfrev;
$photocover  = $tdquery->getColumnVal("photofilename");
$photoone  = $tdquery->getColumnVal("photoone");
$phototwo  = $tdquery->getColumnVal("phototwo");
$virusprot = $tdquery->getColumnVal("virusprotection");
?>
<?php //query contacts

$conn = new mysqli($servername, $username, $password, $dbname);


$kindcont = "headercertificate";
// Usa segnaposti per i parametri


$sqlcontact = "SELECT * FROM contacts LEFT JOIN countries ON countries.idcountries=contacts.country WHERE contacts.idtrf='$idtrftd' AND contacts.kindofcontacts='$kindcont'";

// Esecuzione della query
$resultcontact = $conn->query($sqlcontact);
$rowcontact = $resultcontact->fetch_assoc();
$companyname = $rowcontact["companyname"];
$address = $rowcontact["address"] . ' ' . $rowcontact["cap"] . ' ' . $rowcontact["city"];
$country = $rowcontact["namecountry"];
$phone = $rowcontact["telephone"];
$emailtd = $rowcontact["email"];
$vat = $rowcontact["piva"];
$mark = $tdquery->getColumnVal("registeredmark");
$contactperson = $rowcontact["contactname"] . ' ' . $rowcontact["contactsurname"];


?>
<?php
// Chemical agent
$conn = new mysqli($servername, $username, $password, $dbname);
$sqlchemical = "SELECT * FROM trfchemicalagent LEFT JOIN chemicalagent ON trfchemicalagent.idchemicalagent = chemicalagent.idchemicalagent WHERE trfchemicalagent.idtrf = '$idtrftd'";
$resultchemical = $conn->query($sqlchemical);
$chemicalAgents = []; // Array per memorizzare i risultati

if ($resultchemical && $resultchemical->num_rows > 0) {
    // Riempie l'array con i risultati della query
    while ($rowchemical = $resultchemical->fetch_assoc()) {
        $chemicalAgents[] = $rowchemical["name_chemicalagent"];
    }
}
$conn->close();
?>
<?php

// Protection cat add
$conn = new mysqli($servername, $username, $password, $dbname);
$sqlprotect = "SELECT * FROM trfaddrequirements LEFT JOIN additionalrequirements ON trfaddrequirements.idadditionalrequirements = additionalrequirements.idadditionalrequirements WHERE trfaddrequirements.idtrf = '$idtrftd'";
$resultprotect = $conn->query($sqlprotect);
$protectionAdd = []; // Array per memorizzare i risultati

if ($resultprotect && $resultprotect->num_rows > 0) {;
    // Riempie l'array con i risultati della query
    while ($rowprotect = $resultprotect->fetch_assoc()) {

        $protectionAdd[] = $rowprotect["name_additionalrequirements_it"];
    }
}
$conn->close();

?>

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

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

// Preparazione della query

$tdquerystd = "SELECT * FROM trfstandards 
          LEFT JOIN standards ON trfstandards.idstandards = standards.idstandards 
          LEFT JOIN protectioncategory ON protectioncategory.idprotectioncategory = trfstandards.idprotectioncategory 
          LEFT JOIN dpicategory ON dpicategory.iddpicategory = trfstandards.iddpicategory 
          WHERE trfstandards.idtrfdetails = '$idtrftd'";

// Esecuzione della query
$resultstd = $conn->query($tdquerystd);

if (!$resultstd) {
    die("Errore nell'esecuzione della query: " . $conn->error);
}

// Iterazione sui risultati


// Chiusura della connessione

?>


<?php
// query standards

$tdquerystd = new WA_MySQLi_RS("tdquerystd", $cmctrfdb, 1);
$tdquerystd->setQuery("SELECT * FROM trfstandards LEFT JOIN standards ON trfstandards.idstandards=standards.idstandards LEFT JOIN protectioncategory ON protectioncategory.idprotectioncategory=trfstandards.idprotectioncategory LEFT JOIN dpicategory ON dpicategory.iddpicategory=trfstandards.iddpicategory WHERE trfstandards.idtrfdetails='$idtrftd'");
$tdquerystd->execute();

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

    <!-- Inclusione Bootstrap CSS -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <!-- Inclusione Font Awesome per le icone -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">


    <!-- 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>
    <style>
        #documentPreview {
            width: 100%;
            overflow: auto;
            min-height: 800px;
            /* Per mantenere una dimensione simile all'iframe originale */
        }
    </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; ?> - TRF: <?php echo $trfnumb; ?></h4>
                            <p class="card-text text-muted "><?php echo $questionstarttd; ?></p>

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


                </div>

                <div id="documentPreview"></div>

                <script>
                    // Funzione per ottenere i parametri dalla pagina
                    function getParamsFromPage() {
                        let idtd = <?php echo json_encode($idtd); ?>;
                        let idtrftd = <?php echo json_encode($idtrftd); ?>;
                        return {
                            idtd,
                            idtrftd
                        };
                    }

                    // Funzione per caricare il contenuto dinamicamente
                    async function loadPreview() {
                        let params = getParamsFromPage();
                        let previewContainer = document.getElementById('documentPreview');
                        let baseURL = 'http://localhost/cmccopiaoriginale/public/techdossier_stepsummarypreview.php';
                        let url = `${baseURL}?idtd=${params.idtd}&idtrftd=${params.idtrftd}`;

                        try {
                            let response = await fetch(url);
                            if (!response.ok) {
                                throw new Error('Errore nel caricamento del contenuto');
                            }
                            let html = await response.text();
                            previewContainer.innerHTML = html;
                        } catch (error) {
                            previewContainer.innerHTML = '<p>Errore: impossibile caricare l\'anteprima. Contatta l\'assistenza.</p>';
                            console.error('Errore:', error);
                        }
                    }

                    // Carica il contenuto quando la pagina è pronta
                    document.addEventListener("DOMContentLoaded", function() {
                        loadPreview();
                    });
                </script>














                <br>
                <a href="declarationtd.php?idtd=<?php echo $idtd; ?>&idtrftd=<?php echo $idtrftd; ?>"><button type="button" class="btn btn-gradient-success waves-effect waves-light"><?php echo $proceed; ?></button></a>
                <?php if ((Auth::user()->hasRole('Admin')) || (Auth::user()->hasRole('CustomerService')) || (Auth::user()->hasRole('Superuser'))) : ?>
                    <a href="trfdetails.php?idtrf=<?php echo $idtrftd; ?>" target="_blank"><button type="button" class="btn btn-gradient-dark waves-effect waves-light">MODIFICA TRF</button></a>
                <?php endif; ?>
                <a href="techdossier_adddocument.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>


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