<?php
if (function_exists('opcache_invalidate')) {
    opcache_invalidate(__FILE__, true);
}

//You shall use the following exact namespaces no 
//matter in whathever directory you upload your 
//phpmailer files.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

ob_start();
include('include/headscript.php'); ?>
<?php
if (isset($companyData["logoimage"]) && !empty($companyData["logoimage"])) {
    $companylogo = $companyData["logoimage"];
    $_SESSION['companylogo'] = $companylogo;
}
// pickup the get variable
if (isset($_POST["idtrf"])) {
    $idtrf = $_POST["idtrf"];
}
if (isset($_GET["idtrf"])) {
    $idtrf = $_GET["idtrf"];
}

if (isset($_GET["idtrftd"])) {
    $idtrftd = $_GET["idtrftd"];
}
if (isset($_POST["idtrftd"])) {
    $idtrftd = $_GET["idtrftd"];
}
if (isset($_GET["idtd"])) {
    $idtd = $_GET["idtd"];
}
if (isset($_POST["idtd"])) {
    $idtd = $_POST["idtd"];
}
if (isset($_POST["tokensignatureon"])) {
    $tokensignatureon = $_POST["tokensignatureon"];
}
if (isset($_POST["clientname"])) {
    $clientname = $_POST["clientname"];
}
if (isset($_POST["datetrf"])) {
    $datetrf = $_POST["datetrf"];
}
if (isset($_POST["sndrpt"])) {
    $sndrpt = $_POST["sndrpt"];
} else {
    $sndrpt = "N";
}
if (isset($_POST["adminconfirm"])) {
    $adminconfirm = $_POST["adminconfirm"];
} else {
    $adminconfirm = "N";
}


?>
<?php
$tokenid = $user->present()->signaturecode;
if ($tokenid != $tokensignatureon) {
    header("Location: declaration.php?idtrf=$idtrf&tokenresult=ko");
} else {
    // update trf details`
    if (isset($_POST["formdeclaration"])) {
        if ($sndrpt == 'N') {
            $UpdateQuery = new WA_MySQLi_Query($cmctrfdb);
            $UpdateQuery->Action = "update";
            $UpdateQuery->Table = "data_td";
            $UpdateQuery->bindColumn("signnametd", "s", "$clientname", "WA_DEFAULT");
            $UpdateQuery->bindColumn("signedontd", "s", "$datetrf", "WA_DEFAULT");
            $UpdateQuery->bindColumn("statustd", "s", "Signed", "WA_DEFAULT");
            $UpdateQuery->addFilter("iddata_td", "=", "i", "" . ($idtd)  . "");
            $UpdateQuery->execute();
            $UpdateGoTo = "";
            if (function_exists("rel2abs")) $UpdateGoTo = $UpdateGoTo ? rel2abs($UpdateGoTo, dirname(__FILE__)) : "";
            $UpdateQuery->redirect($UpdateGoTo);
        }
    }

?>
    <?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");
    $appformn = $trfnumberfinal->getColumnVal("trfnumber");
    $ntrfmail = $trfnumberfinal->getColumnVal("trfnumber");;
    $revnumb = $trfnumberfinal->getColumnVal("revtrf");
    ?>
    <?php $idcert = $trfnumberfinal->getColumnVal("idcertification") ?>
    <?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'];
    $tdnumber = $row['tdnumber'];
    $tdrev = $row['td_rev'];
    $trfmod = $row['trfmod'];
    $stmt->close();
    $conn->close();
    ?>
    <?php
    $certname = new WA_MySQLi_RS("certname", $cmctrfdb, 1);
    $certname->setQuery("SELECT * FROM certificationtype WHERE certificationtype.idcertificationtype='$idcert'");
    $certname->execute(); ?>
    <?php
    $chemicalagentlist = new WA_MySQLi_RS("chemicalagentlist", $cmctrfdb, 0);
    $chemicalagentlist->setQuery("SELECT * FROM chemicalagent ORDER BY chemicalagent.name_chemicalagent");
    $chemicalagentlist->execute();

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

    <head>
        <meta charset="utf-8" />
        <title>TRF <?php echo $ownercompanyname; ?> </title>
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta content="<?php echo $ownercompanyname; ?> 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" />
        <!-- submit form with button -->
        <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 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/leftsidenav2.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/appformtd.php'); ?>
                                    </div><!--end media-->
                                </div><!--end card-body-->
                            </div><!--end card-->
                            <div class="progress mb-4">
                                <div class="progress-bar" role="progressbar" style="width: 100%;" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">100%</div>
                            </div>
                            <!-- card for optional TRF -->
                        <?php //pdf creation

                        include('tf_pdfcreation.php');

                        if ($trfmod == 'Y') {

                            // Esegui la chiamata cURL per previewtrf.php
                            $url = $linkglobalpublic . "previewtrf.php?idtrf=" . urlencode($idtrf);

                            // Recupera i cookie di sessione
                            $cookies = '';
                            foreach ($_COOKIE as $key => $value) {
                                $cookies .= $key . '=' . $value . '; ';
                            }

                            $ch = curl_init($url);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_TIMEOUT, 15); // Timeout leggermente più lungo
                            curl_setopt($ch, CURLOPT_HEADER, 0);
                            curl_setopt($ch, CURLOPT_COOKIE, $cookies); // Invia i cookie di sessione

                            // Aggiungi gestione degli errori cURL
                            $response = curl_exec($ch);
                            if (curl_errno($ch)) {
                                $error_msg = curl_error($ch);
                                error_log("cURL error: " . $error_msg, 3, "../logfile.log"); // Sostituisci con il percorso del tuo file di log
                            } else {
                                // Registra la risposta per debug
                                error_log("cURL response: " . $response, 3, "../logfile.log"); // Sostituisci con il percorso del tuo file di log
                            }
                            curl_close($ch);
                        }


                        $checkpdffiles = new WA_MySQLi_RS("checkpdffiles", $cmctrfdb, 1);
                        $checkpdffiles->setQuery("SELECT * FROM `data_td` WHERE data_td.iddata_td='$idtd'");
                        $checkpdffiles->execute();
                        $path = 'tdpdf';
                        $filename1 = $checkpdffiles->getColumnVal("pdffilenametd");
                        $file1 = $path . "/" . $filename1;
                        //Now include the following following files based 
                        //on the correct file path. Third file is required only if you want to enable SMTP.
                        require 'phpmailer/src/Exception.php';
                        require 'phpmailer/src/PHPMailer.php';
                        require 'phpmailer/src/SMTP.php';
                        //mail to client
                        $mail = new PHPMailer(true);
                        try {
                            $mail->isSMTP();                                      // Set mailer to use SMTP
                            $mail->Host = $mailhost;  // Specify main and backup server
                            $mail->SMTPAuth = true;                               // Enable SMTP authentication
                            $mail->Username = $mailusername;                            // SMTP username
                            $mail->Password = $mailpassword;                           // SMTP password
                            $mail->SMTPSecure = $mailmethod;                            // Enable encryption, 'ssl' also accepted
                            $mail->Port       = $mailport;
                            $mmessage = "mailtf";
                            include('include/mailhtml.php');
                            // Email body content 
                            //$trfnmbmail = $appformn . 'r' . $revnumb;
                            $htmlContent = $mailmessage1;
                            $mail->From = $fromaddresssmail;
                            $mail->FromName = 'CIMAC Technical File System';
                            $mail->addAddress($emailuser);  // Add a recipient
                            $mail->addAttachment($file1);         // Add attachments
                            // Optional name                               
                            $mail->Subject = "Technical File:" . $tdnumber;
                            $mail->Body    = $htmlContent;
                            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
                            if ($adminconfirm == 'N') {
                                $mail->send();
                            }
                            // echo 'Message has been sent';
                        } catch (Exception $e) {
                            echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
                        }

                        // Second mail to customer service
                        $mail_cs = new PHPMailer(true);
                        try {
                            $mail_cs->isSMTP();
                            $mail_cs->Host = $mailhost;
                            $mail_cs->SMTPAuth = true;
                            $mail_cs->Username = $mailusername;
                            $mail_cs->Password = $mailpassword;
                            $mail_cs->SMTPSecure = $mailmethod;
                            $mail_cs->Port = $mailport;
                            $mail_cs->From = $fromaddresssmail;
                            $mail_cs->FromName = 'CIMAC Technical File System';
                            $mail_cs->addAddress('d.dondena@cimac.it');
                            $mail_cs->addAddress('c.boscaino@cimac.it');
                            $mail_cs->addAddress('a.boscaino@cimac.it');
                            $mail_cs->Subject = "Nuovo Fascicolo Tecnico Inserito: $tdnumber da $companyname";
                            $mail_cs->Body = "Buongiorno,\n\nla presente mail per segnalare l'inserimento di un nuovo fascicolo tecnico da parte dell'azienda " . $companyname . ". Fascicolo tecnico numero " . $tdnumber . ".";
                            $mail_cs->AltBody = "Buongiorno,\n\nla presente mail per segnalare l'inserimento di un nuovo fascicolo tecnico da parte dell'azienda " . $companyname . ". Fascicolo tecnico numero " . $tdnumber . ".";
                            if ($adminconfirm == 'N') {
                                $mail_cs->send();
                            }
                        } catch (Exception $e) {
                            echo "Customer service message could not be sent. Mailer Error: {$mail_cs->ErrorInfo}";
                        }
                    }
                        ?>
                        <div class="card">
                            <div class="card-body">
                                <h4 class="mt-0 header-title"><?php echo $sendtdtitle; ?></h4>
                                <br><br>
                                <p><?php echo $companyname; ?> <?php echo $sendtdsentence; ?></p><br>
                            </div><!--end card-body-->
                        </div><!--end card-->
                        </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>
    </body>

    </html>