<?php
include('include/headscript.php'); ?>
<?php
include('languages/' . $_SESSION['langselect'] . '/tdgen.php');
// pickup the get variable
if (isset($_POST["idtd"])) {
    $idtd = $_POST["idtd"];
}
if (isset($_GET["idtd"])) {
    $idtd = $_GET["idtd"];
}

if (isset($_GET["tokenresult"])) {
    $tokenresult = $_GET["tokenresult"];
}
if (isset($_POST["idtrftd"])) {
    $idtrf = $_POST["idtrftd"];
}
if (isset($_GET["idtrftd"])) {
    $idtrf = $_GET["idtrftd"];
}


if (isset($_POST["contactsendmail"])) {
    $contactsendmail = $_POST["contactsendmail"];
}
if (isset($_POST["emailsendmail"])) {
    $emailsendmail = $_POST["emailsendmail"];
}
?>
<?php
$trfnumberfinal = new WA_MySQLi_RS("trfnumberfinal", $cmctrfdb, 1);
$trfnumberfinal->setQuery("SELECT * FROM `trf-details` WHERE `trf-details`.idtrfdetails='$idtrf'");
$trfnumberfinal->execute();
$idcertn = $trfnumberfinal->getColumnVal("idcertification");
$idarticletype = $trfnumberfinal->getColumnVal("idarticletype");
$pdfdomanda = $trfnumberfinal->getColumnVal("pdffilename");
?>
<?php $idcert = $trfnumberfinal->getColumnVal("idcertification") ?>
<?php
$certname = new WA_MySQLi_RS("certname", $cmctrfdb, 1);
$certname->setQuery("SELECT * FROM certificationtype WHERE certificationtype.idcertificationtype='$idcert'");
$certname->execute(); ?>
<?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();
$statustd = $row['statustd'];
$idtrftd = $row['idtrf'];
$trfmod = $row['trfmod'];
$stmt->close();
$conn->close();
?>
<?php

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

// Verifica se la connessione ha avuto successo
if ($conn->connect_error) {
    die("Connessione fallita: " . $conn->connect_error);
}

// Query per ottenere la data più recente dalla tabella identificationparts
$sqlmaxdate = "SELECT MAX(cmcreportdate_identificationparts) AS max_date FROM identificationparts WHERE idtrfdetails = ?";
$stmt = $conn->prepare($sqlmaxdate);


// Verifica se la query è stata preparata correttamente
if ($stmt === false) {
    die("Errore nella preparazione della query: " . $conn->error);
}

// Bind dei parametri e esecuzione della query
$stmt->bind_param("i", $idtrftd);
$stmt->execute();

// Ottieni il risultato della query
$result = $stmt->get_result();

// Verifica se ci sono righe restituite
if ($result->num_rows > 0) {
    // Ottieni la riga risultante
    $row = $result->fetch_assoc();

    // Ottieni la data più recente
    $max_date = $row["max_date"];

    // Verifica se la data più recente è NULL
    if ($max_date === NULL) {
        // Imposta la data attuale
        $max_date = date("Y-m-d");
    }

    // Fai qualcosa con la data più recente, ad esempio stampala a schermo

} else {
    // Se non ci sono righe restituite, impostare la data attuale
    $max_date = date("Y-m-d");

    // Fai qualcosa con la data attuale, ad esempio stampala a schermo

}

// Chiudi la connessione
$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">

    <!--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" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">

    <!-- submit form with button -->
    <style>
        /* Loader CSS */
        .loader {
            border: 16px solid #f3f3f3;
            /* Light grey */
            border-top: 16px solid #3498db;
            /* Blue */
            border-radius: 50%;
            width: 120px;
            height: 120px;
            animation: spin 2s linear infinite;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        /* Fullscreen overlay */
        .overlay {
            position: fixed;
            display: none;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            /* Black background with opacity */
            z-index: 9999;
            /* Specify a stack order in case you're using a different order for other elements */
        }

        .overlay .loader {
            display: block;
            /* Ensure the loader is visible within the overlay */
        }
    </style>


    <style>
        input:invalid {
            border-color: #ff0000;
            background-color: #fff7e6;
        }

        input:focus {
            background: yellow;
        }

        input:valid {
            border-color: #66ff33;
            background-color: #eeffe6;
        }

        select:invalid {
            border-color: #ff0000;
            background-color: #fff7e6;
        }

        select:focus {
            background-color: yellow;
        }

        select:valid {
            border-color: #66ff33;
            background-color: #eeffe6;
        }
    </style>
    <style>
        body {
            font-family: arial;
        }

        .hide {
            display: none;
        }

        p {
            font-weight: bold;
        }
    </style>
    <script>
        function formSubmit() {
            document.forms["myForm"].submit();
        }
    </script>
    <script>
        function formSubmit() {
            document.getElementById("myFormpdf").submit(); // Assicurati che 'myForm' sia l'ID del tuo form
        }
    </script>
    <script>
        function show1() {
            document.getElementById('div1').style.display = 'none';
        }

        function show2() {
            document.getElementById('div1').style.display = 'block';
        }

        function show3() {
            document.getElementById('div3').style.display = 'none';
        }

        function show4() {
            document.getElementById('div3').style.display = 'block';
        }

        function show5() {
            document.getElementById('div5').style.display = 'none';
        }

        function show6() {
            document.getElementById('div5').style.display = 'block';
        }
    </script>
</head>

<body>

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

    <!-- Left Sidenav -->
    <?php include('include/leftsidenavnocheckstep.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 $titlewb; ?></h4>
                        </div><!--end page-title-box-->
                    </div><!--end col-->
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="media">

                                    <?php include('include/appform.php'); ?>
                                </div><!--end media-->

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


                        <!-- card for optional TRF -->

                        <!-- TO SIGN -->

                        <div class="card">
                            <div class="card-body">
                                <?php if ((Auth::user()->hasRole('Admin')) || (Auth::user()->hasRole('Superuser')) || (Auth::user()->hasRole('CustomerService')) || (Auth::user()->hasRole('Certification'))) : ?>

                                    <h4 class="mt-0 header-title">Invia in Firma</h4>
                                    <p class="text-muted mb-3">Invio in firma del dossier Tecnico</p>



                                    <div class="overlay">
                                        <div class="loader"></div>
                                    </div>

                                    <form action="sendtdtoreview.php" method="post" name="myForm" id="myForm" class="form-parsley">

                                        <!-- New Radio Button for Modifying TRF -->
                                        <div class="form-group row">
                                            <label class="col-sm-1 col-form-label text-right">TRF Modificato?</label>
                                            <div class="col-sm-5 d-flex align-items-center">
                                                <div class="form-check form-check-inline">
                                                    <input class="form-check-input" type="radio" id="modifytrf_yes" name="modifytrf" value="Y" required>
                                                    <label class="form-check-label" for="modifytrf_yes">Sì</label>
                                                </div>
                                                <div class="form-check form-check-inline">
                                                    <input class="form-check-input" type="radio" id="modifytrf_no" name="modifytrf" value="N" required>
                                                    <label class="form-check-label" for="modifytrf_no">No</label>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-group row">
                                            <label for="example-date-input" class="col-sm-1 col-form-label text-right"><?php echo $datettitle; ?></label>
                                            <div class="col-sm-3">
                                                <?php $todaydate = date("Y-m-d"); ?>
                                                <input class="form-control" type="date" id="datetrf" name="datetrf" value="<?php echo $todaydate; ?>" id="example-date-input">
                                            </div>
                                        </div>



                                        <div class="form-group row">
                                            <div class="col-sm-2">
                                                <input type="hidden" id="idtd" name="idtd" value="<?php echo $idtd; ?>">
                                                <input type="hidden" id="idtrf" name="idtrf" value="<?php echo $idtrf; ?>">
                                                <input type="hidden" id="formreview" name="formreview" value="OK">
                                                <input type="hidden" id="review" name="review" value="Sign">
                                            </div>
                                        </div>

                                        <button class="btn btn-gradient-success waves-effect waves-light" type="submit" id="btnreview"><?php echo $modtitle; ?></button>
                                    </form>
                                    <script>
                                        document.getElementById('myForm').addEventListener('submit', function() {
                                            document.querySelector('.overlay').style.display = 'block';
                                        });
                                    </script>



                            </div><!--end card-body-->
                        </div>
                    <?php endif; ?>
                    <?php if (!Auth::user()->hasRole('Certification')) : ?>
                        <!-- TO REVIEW -->

                        <div class="card">
                            <div class="card-body">
                                <h4 class="mt-0 header-title"><?php echo $toreview; ?></h4>
                                <p class="text-muted mb-3"><?php echo $toreviewhelp; ?></p>





                                <form action="sendtdtoreview.php" method="post" name="myForm" class="form-parsley">

                                    <div class="form-group row">
                                        <label for="example-date-input" class="col-sm-1 col-form-label text-right"><?php echo $datettitle; ?></label>
                                        <div class="col-sm-3">
                                            <?php $todaydate = date("Y-m-d");
                                            ?>
                                            <input class="form-control" type="date" id="datetrf" name="datetrf" value="<?php echo $todaydate; ?>" id="example-date-input">
                                        </div>

                                    </div>
                                    <div class="form-group row">


                                        <div class="col-sm-2">
                                            <input hidden id="idtd" name="idtd" value="<?php echo $idtd; ?>">
                                            <input hidden id="idtrf" name="idtrf" value="<?php echo $idtrf; ?>">
                                            <input hidden id="formreview" name="formreview" value="OK">
                                            <input hidden id="review" name="review" value="Revision">

                                        </div>

                                    </div>
                                    <button class="btn btn-gradient-success waves-effect waves-light" type="submit" id="btnreview"><?php echo $modtitle; ?></button><!-- o <a href="sendtrftosign.php"><button class="btn btn-gradient-warning waves-effect waves-light" type="button" id="btnConfirm"><?php echo $sendtosign; ?></button></a> -->
                                </form>

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

                    </div>
                </div>


                <div class="card">
                    <div class="card-body">
                        <h3 class="mt-0 header-title">
                            <?= $_SESSION['langselect'] === 'en'
                                ? 'SIGN THE TECHNICAL FILE'
                                : 'FIRMA IL TECHNICAL FILE' ?>
                        </h3>

                        <h4 class="mt-0 header-title"><?php echo $declarationtitle; ?></h4>
                        <p class="text-muted mb-3"><?php echo $declarationtitle_help; ?></p>

                        <p><?php echo $companyname; ?> <?php echo $companydeclarationtd; ?></p><br>
                        <p><?php echo $declarationtdsent1; ?></p><br>
                        <p><?php echo $declarationtdsent2; ?></p><br>

                        <?php if ($trfmod == 'Y') { ?>
                            La domanda di certificazione è stata modificata, pertanto firmando il File Tecnico, firmerai anche la domanda modificata <br>
                            PREVIEW Domanda modificata
                            <a href="pdf/<?php echo $pdfdomanda; ?>" target="_blank" style="color: red; display: inline-block; margin-left: 5px;">
                                <i class="fas fa-file-pdf" aria-hidden="true"></i>
                            </a>
                            <br><br>
                        <?php } ?>


                        <?php if (isset($tokenresult)) { ?>
                            <div class="alert icon-custom-alert alert-outline-danger alert-danger-shadow" role="alert">
                                <i class="mdi mdi-alert-outline alert-icon"></i>
                                <div class="alert-text">
                                    <strong><?php echo $uncorrecttokentitle;
                                            ?></strong>.
                                </div>
                            </div>


                        <?php } ?>
                        <?php
                        /*$image = "uploadimages/".$trfnumberfinal->getColumnVal("photofilename");
                                        $img_info = getimagesize($image);
                                        if ($img_info[2] <> IMG_JPEG) {
                                    ?>
                                        <div class="alert icon-custom-alert alert-outline-danger alert-danger-shadow" role="alert">
                                            
                                            <i class="mdi mdi-alert-outline alert-icon"></i>
                                    
                                            <div class="alert-text">
                                                
                                                <strong>Attention: Attached image is not a JPEG/JPG file. <?php echo $image;?></strong>
                                    
                                            </div>                                            
                                
                                        </div>
                                    <?php }*/ ?>


                        <form action="sendtd.php" method="post" name="myFormpdf" id="myFormpdf" class="form-parsley">


                            <div class="form-group row">
                                <label for="example-date-input" class="col-sm-1 col-form-label text-right"><?php echo $datettitle; ?></label>
                                <div class="col-sm-3">
                                    <?php $todaydate = date("Y-m-d");
                                    ?>
                                    <input class="form-control" type="date" id="datetrf" name="datetrf" value="<?php echo $todaydate; ?>" id="example-date-input">
                                </div>
                                <label for="example-text-input" class="col-sm-2 col-form-label text-right"><?php echo $signedbytitle; ?></label>
                                <div class="col-sm-3">
                                    <input class="form-control" type="text" value="<?php echo $nameuser; ?>" id="clientname" name="clientname" readonly>
                                </div>
                            </div>
                            <div class="form-group row">

                                <label for="example-text-input" class="col-sm-4 col-form-label text-right"><?php echo $inserttokensign; ?></label>
                                <div class="col-sm-2">
                                    <input name="tokensignatureon" type="text" required class="form-control" id="tokensignatureon" value="" size="6">
                                    <input hidden id="idtrf" name="idtrf" value="<?php echo $idtrf; ?>">
                                    <input hidden id="idtd" name="idtd" value="<?php echo $idtd; ?>">
                                    <input hidden id="formdeclaration" name="formdeclaration" value="OK">

                                </div>

                            </div>

                            <br>
                            <p><a href="signaturetok.php" target="_blank"><?php echo $tokenwhere; ?></a></p>
                            <p><?php echo $firmdeclaration; ?></p><br>
                            <p><?php echo $notokenneeded; ?></p>
                            <p><?php echo $sentforsignview; ?></p>
                            <!-- <button class="btn btn-gradient-success waves-effect waves-light" type="submit">Conferma</button> -->
                            <div id="cont_wait" style="display:none;">

                                <div class="alert icon-custom-alert alert-outline-warning alert-danger-shadow" role="alert">
                                    <!-- <i class="mdi mdi-alert-outline alert-icon"></i> -->
                                    <div class="alert-text">
                                        <strong>Attenzione:</strong> Inserimento Application Form in corso, Attendi!
                                    </div>
                                </div>
                            </div>
                            <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>
                            <?php if (Auth::user()->hasRole('Admin')) : ?>
                                <label>
                                    <input type="radio" name="adminconfirm" value="N" checked> Invio con Mail
                                </label>
                                <label>
                                    <input type="radio" name="adminconfirm" value="Y"> Invio senza Mail
                                </label>
                            <?php endif; ?>
                            <button class="btn btn-gradient-success waves-effect waves-light" type="button" id="btnConfirm"><?php echo $modtitle; ?></button><!-- o <a href="sendtrftosign.php"><button class="btn btn-gradient-warning waves-effect waves-light" type="button" id="btnConfirm"><?php echo $sendtosign; ?></button></a> -->
                        </form>

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




                </div><!--end card-->
            <?php endif; ?>



            </div><!--end col-->
        </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/jquery.min.js"></script>
    <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>
    <script type="text/javascript">
        /* PROGRESS STARTS AT 95% */
        let progress = 95;
        $(document).ready(function() {
            $('#btnConfirm').on('click', function() {
                if ($('#tokensignatureon').val() == '') {
                    formSubmit();
                } else {
                    $('.alert-outline-danger').hide();
                    /* SHOW PLEASE WAIT WARNING */
                    $('#cont_wait').css('display', 'block');
                }
                /* DISABLE CONFIRM BUTTON */
                $(this).prop('disabled', true);

                /* ANIMATE PROGRESS BAR */
                setInterval(progressBar, 1000);
            });
        });

        function progressBar() {
            /* ITERATE PERCENTAGE */
            progress += 1;
            /* UPDATE PROGRESS PERCENTAGE */
            $('.progress-bar').text(progress + '%');
            /* UPDATE PROGRESS BAR IMG */
            $('.progress-bar').css('width', progress + '%');
            if (progress == 98) {
                /* SUBMIT FORM */
                formSubmit();
            }

        }
    </script>

</body>

</html>