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

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

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

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



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

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

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

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

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

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

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

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

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



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

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

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

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


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

$description = $tdquery->getColumnVal("sample_description");
$trfn = $tdquery->getColumnVal("trfnumber");
$trfrev  = $tdquery->getColumnVal("revtrf");
$trfnumb = $trfn . ' VER.' . $trfrev;
?>
<?php

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

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

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

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

    <!-- DataTables -->

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

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


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

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


    <!-- submit form with button -->


    <script 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>
        .is-invalid {
            border-color: #dc3545;
            /* Colore rosso per l'evidenziazione */
            background-color: #fff3f4;
            /* Sfondo leggermente rosato per maggiore visibilità */
        }
    </style>


    </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 class="card">


                    <!-- card for show requirements -->


                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-body">
                                <form method="post" action="fillrisk.php">

                                    <table class="table mb-0">
                                        <thead class="thead-light">
                                            <tr>
                                                <th><?php echo $requirementnumbertd; ?></th>
                                                <th><?php echo $requirementnametd; ?></th>
                                                <th><?php echo $applicabletd; ?></th>
                                                <th><?php echo $covertbytd; ?></th>
                                            </tr>
                                        </thead>

                                        <?php

                                        $riskquery = new WA_MySQLi_RS("riskquery", $cmctrfdb, 0);
                                        $riskquery->setQuery("SELECT * FROM fillrisk_td LEFT JOIN riskarea_td ON riskarea_td.idriskarea_td=fillrisk_td.idriskarea_td WHERE fillrisk_td.iddata_td='$idtd' ORDER BY fillrisk_td.idfillrisk_td");
                                        $riskquery->execute();



                                        ?>
                                        <tbody>
                                            <?php while (!$riskquery->atEnd()) { ?>
                                                <tr>
                                                    <th scope="row"><?php echo $riskquery->getColumnVal("risknumber"); ?></th>
                                                    <td><?php echo ($_SESSION['langselect'] == 'en') ? $riskquery->getColumnVal("riskname_en") : $riskquery->getColumnVal("riskname_it"); ?></td>
                                                    <td>
                                                        <div class="custom-control custom-checkbox">
                                                            <input type="checkbox" class="custom-control-input" id="customCheck<?php echo $riskquery->getColumnVal("risknumber"); ?>" <?php if ($riskquery->getColumnVal("applicable") == "1") echo 'checked'; ?>>
                                                            <label class="custom-control-label" for="customCheck<?php echo $riskquery->getColumnVal("risknumber"); ?>"></label>
                                                        </div>
                                                    </td>
                                                    <?php $coveredbyValue = $riskquery->getColumnVal("coveredby"); ?>
                                                    <td style="width: 40%;">
                                                        <div class="col-sm-24">
                                                            <select class="form-control data-field" data-column="coveredby" id="coveredby<?php echo $riskquery->getColumnVal("risknumber"); ?>" name="coveredby">
                                                                <option value="default" <?php echo ($coveredbyValue === '' || $coveredbyValue === null) ? 'selected' : ''; ?>><?php echo ($_SESSION['langselect'] == 'en') ? 'Select' : 'Seleziona'; ?></option>
                                                                <option value="coverone" <?php echo ($coveredbyValue == 'coverone') ? 'selected' : ''; ?>><?php echo $coverone; ?></option>
                                                                <option value="covertwo" <?php echo ($coveredbyValue == 'covertwo') ? 'selected' : ''; ?>><?php echo $covertwo; ?></option>
                                                                <option value="coverthree" <?php echo ($coveredbyValue == 'coverthree') ? 'selected' : ''; ?>><?php echo $coverthree; ?></option>
                                                            </select>
                                                        </div>
                                                    </td>
                                                    <input class="form-control" type="hidden" value="<?php echo $riskquery->getColumnVal("idfillrisk_td"); ?>" name="fillrisktd<?php echo $riskquery->getColumnVal("idfillrisk_td"); ?>">
                                                </tr>
                                                <?php $riskquery->moveNext(); ?>
                                            <?php } ?>






                                            <?php $riskquery->moveFirst(); // Se hai bisogno di riutilizzare i risultati 
                                            ?>
                                        </tbody>
                                    </table>
                                    <br>

                                </form>
                                <form action="techdossier_step3.php" method="post" id="myForm">

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

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

                                </form>
                                <script>
                                    ClassicEditor
                                        .create(document.querySelector('#editor'))
                                        .catch(error => {
                                            console.error(error);
                                        });
                                </script>
                                <script>
                                    $(document).ready(function() {
                                        $('.custom-control-input, .form-control').change(function() {
                                            var row = $(this).closest('tr'); // Trova la riga della tabella
                                            var idFillRiskTd = row.find('input[type="hidden"]').val(); // Ottiene l'idfillrisk_td
                                            var field, value;

                                            if ($(this).hasClass('custom-control-input')) {
                                                // Checkbox per 'applicable'
                                                field = 'applicable';
                                                value = $(this).is(':checked') ? 1 : 0;
                                            } else if ($(this).attr('name').startsWith('coveredby')) {
                                                // Campo di testo per 'coveredby'
                                                field = 'coveredby';
                                                value = $(this).val();
                                            }

                                            if (field && value !== undefined) {
                                                updateFillRiskTd(idFillRiskTd, field, value, $(this));
                                            }
                                        });

                                        function updateFillRiskTd(id, field, value, element) {
                                            $.ajax({
                                                url: 'fillrisk.php',
                                                type: 'POST',
                                                data: {
                                                    id: id,
                                                    field: field,
                                                    value: value
                                                },
                                                success: function(response) {
                                                    element.css('background-color', '#d4edda');
                                                    setTimeout(function() {
                                                        element.css('background-color', '');
                                                    }, 2000);
                                                }
                                            });
                                        }
                                    });
                                </script>
                                <script>
                                    $(document).ready(function() {
                                        // Aggiorna lo stato 'required' dei select basato sullo stato del checkbox corrispondente
                                        function updateSelectRequiredState(checkbox) {
                                            var selectId = 'coveredby' + checkbox.attr('id').replace('customCheck', '');
                                            var selectElement = $('#' + selectId);
                                            selectElement.prop('required', checkbox.is(':checked'));
                                        }

                                        // Inizializza e aggiorna lo stato required dei select in base ai checkbox al caricamento della pagina
                                        $('.custom-control-input').each(function() {
                                            updateSelectRequiredState($(this));
                                            $(this).change(function() {
                                                updateSelectRequiredState($(this));
                                            });
                                        });

                                        // Gestisce la sottomissione del form specifico
                                        $('#myForm').on('submit', function(event) {
                                            var isFormValid = true;

                                            // Verifica se tutti i select obbligatori sono stati compilati correttamente
                                            $(this).find('.form-control[data-column="coveredby"]').each(function() {
                                                if ($(this).prop('required') && $(this).val() === 'default') {
                                                    isFormValid = false;
                                                    $(this).css('border-color', 'red'); // Fornisce un feedback visivo
                                                } else {
                                                    $(this).css('border-color', ''); // Reset del feedback visivo
                                                }
                                            });

                                            // Se il form non è valido, impedisce la sottomissione e mostra un messaggio
                                            if (!isFormValid) {
                                                event.preventDefault(); // Blocca la sottomissione del form
                                                alert('Per favore, completa tutti i campi obbligatori correttamente.');
                                            }
                                        });
                                    });
                                </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 -->

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('myForm').addEventListener('submit', function(event) {
                let isValid = true;

                // Rimuovi l'evidenziazione da tutti i campi select prima di iniziare la verifica
                document.querySelectorAll('.form-control.data-field').forEach(function(select) {
                    select.classList.remove('is-invalid');
                });

                document.querySelectorAll('.custom-control-input').forEach(function(checkbox) {
                    if (checkbox.checked) {
                        const selectId = 'coveredby' + checkbox.id.replace('customCheck', '');
                        const select = document.getElementById(selectId);
                        if (select && select.value === 'default') {
                            isValid = false;
                            select.classList.add('is-invalid'); // Aggiungi la classe per evidenziare il campo non valido
                        }
                    }
                });

                if (!isValid) {
                    event.preventDefault(); // Impedisci la sottomissione del form
                    alert('Per favore, seleziona una voce della tendina per ogni checkbox selezionato prima di procedere!');
                }
            });
        });
    </script>



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