<?php
//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;

include('include/headscript.php'); ?>
<?php
// pickup the get variable
if (isset($_POST["idtrf"])) {
    $idtrf = $_POST["idtrf"];
}
if (isset($_GET["idtrf"])) {
    $idtrf = $_GET["idtrf"];
}
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";
}
if (isset($_GET["codestep"])) {
    $code = $_GET["codestep"];
    $InsertQuery = new WA_MySQLi_Query($cmctrfdb);
    $InsertQuery->Action = "insert";
    $InsertQuery->Table = "wheretrfstep";
    $InsertQuery->bindColumn("idtrf", "i", "$idtrf", "WA_DEFAULT");
    $InsertQuery->bindColumn("code", "i", "$code", "WA_DEFAULT");
    $InsertQuery->saveInSession("");
    $InsertQuery->execute();
    $InsertGoTo = "";
    $InsertQuery->redirect($InsertGoTo);
}

?>
<?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 = "`trf-details`";
            $UpdateQuery->bindColumn("signedon", "s", "$datetrf", "WA_DEFAULT");
            $UpdateQuery->bindColumn("revcs", "s", "N", "WA_DEFAULT");
            $UpdateQuery->addFilter("idtrfdetails", "=", "i", "" . ($idtrf)  . "");
            $UpdateQuery->execute();
            $UpdateGoTo = "";
            if (function_exists("rel2abs")) $UpdateGoTo = $UpdateGoTo ? rel2abs($UpdateGoTo, dirname(__FILE__)) : "";
            $UpdateQuery->redirect($UpdateGoTo);
        } else {
            $UpdateQuery = new WA_MySQLi_Query($cmctrfdb);
            $UpdateQuery->Action = "update";
            $UpdateQuery->Table = "`trf-details`";
            $UpdateQuery->bindColumn("signedonsecondcert", "s", "$datetrf", "WA_DEFAULT");
            $UpdateQuery->bindColumn("revcs", "s", "N", "WA_DEFAULT");
            $UpdateQuery->addFilter("idtrfdetails", "=", "i", "" . ($idtrf)  . "");
            $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
    $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><?php echo $titlepage; ?></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);"><?php echo $titlepage; ?></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-->
                            <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('pdf-creation.php');

                        //if ($idcertificate==1 or $idcertificate==3 or $idcertificate==4) 
                        //{
                        //include('pdf-creation2.php'); }
                        // attachment

                        $checkpdffiles = new WA_MySQLi_RS("checkpdffiles", $cmctrfdb, 1);
                        $checkpdffiles->setQuery("SELECT * FROM `trf-details` WHERE `trf-details`.idtrfdetails='$idtrf'");
                        $checkpdffiles->execute();
                        $path = 'pdf';
                        $filename1 = $checkpdffiles->getColumnVal("pdffilename");
                        $file1 = $path . "/" . $filename1;
                        if (!empty($checkpdffiles->getColumnVal("pdffilename2"))) {
                            $filename2 = $checkpdffiles->getColumnVal("pdffilename2");
                            $file2 = $path . "/" . $filename2;
                        }
                        //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 = "mailtrf";
                            include('include/mailhtml.php');
                            // Email body content 
                            $trfnmbmail = $appformn . 'r' . $revnumb;
                            $htmlContent = $mailmessage1;
                            $mail->From = $fromaddresssmail;
                            $mail->FromName = 'CIMAC Application Form System';
                            $mail->addAddress($emailuser);  // Add a recipient
                            $mail->addAttachment($file1);         // Add attachments
                            if (!empty($checkpdffiles->getColumnVal("pdffilename2"))) {
                                $mail->addAttachment($file2);
                            }  // Optional name                               
                            $mail->Subject = $appformn . 'r' . $revnumb;
                            $mail->Body    = $htmlContent;
                            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
                            error_log("Attempting to send email to: $emailuser with idtrf: $idtrf");
                            if ($adminconfirm == 'N') {
                                $mail->send();
                                error_log("Email sent successfully to: $emailuser with idtrf: $idtrf");
                            }
                            // echo 'Message has been sent';
                        } catch (Exception $e) {
                            echo "Message could not be sent CL. Mailer Error: {$mail->ErrorInfo}";
                        }
                        // mail to CS

                        $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 = "mailtrf";
                            // Email body content 
                            $htmlContent = $mailmessage1;
                            $mail->From = $fromaddresssmail;
                            $mail->FromName = 'CIMAC Application Form System';
                            if (!empty($csmail)) {
                                $mail->addAddress($csmail);  // Aggiunge il destinatario solo se non è vuoto
                            }
                            if (!empty($csmail2)) {
                                $mail->addAddress($csmail2);
                            }
                            if (!empty($csmail3)) {
                                $mail->addAddress($csmail3);
                            }
                            if (!empty($csmailccn)) {
                                $mail->addBCC($csmailccn);
                            }

                            $mail->Subject = $appformn . 'r' . $revnumb;;
                            $mail->Body    = "Ciao! E' stato inserito un nuovo ETRF N. $trfnmbmail ";
                            $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 CS. Mailer Error: {$mail->ErrorInfo}";
                        }
                        // mail REV to CS
                        // if rev is > 0
                        if ($revnumb > 0) {
                            //query to see the previous CS in charge
                            $revnumberprev = $revnumb - 1;
                            $trfprevrev = new WA_MySQLi_RS("trfprevrev", $cmctrfdb, 1);
                            $trfprevrev->setQuery("SELECT * FROM `trf-details` LEFT JOIN company ON `trf-details`.idcompany=company.idcompany WHERE `trf-details`.trfnumber='$ntrfmail' AND `trf-details`.revtrf='$revnumberprev'");
                            $trfprevrev->execute();
                            $csinchargeprev = $trfprevrev->getColumnVal("csincharge");
                            if ($csinchargeprev == 'ddondena') {
                                $mailincharge = 'd.dondena@cimac.it';
                            } elseif ($csinchargeprev == 'cboscaino') {
                                $mailincharge = 'c.boscaino@cimac.it';
                            } elseif ($csinchargeprev == 'aboscaino') {
                                $mailincharge = 'a.boscaino@cimac.it';
                            } elseif ($csinchargeprev == 'solocla') {
                                $mailincharge = 'info@acscreativesolutions.com';
                            } else {
                                $mailincharge = 'd.dondena@cimac.it';
                            }

                            // Define array with all CS mails
                            $csmailall = array($csmail, $csmail3);
                            // Extract the recipient that matches $mailincharge
                            $recipientTo = $mailincharge;
                            $recipientsCC = array_diff($csmailall, array($recipientTo));
                            $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 = "mailtrf";
                                // Email body content
                                $htmlContent = $mailmessage1;
                                $mail->From = $fromaddresssmail;
                                $mail->FromName = 'CIMAC Application Form System';
                                $mail->addAddress($recipientTo); // Add the recipient in "To" field
                                foreach ($recipientsCC as $ccRecipient) {
                                    $mail->addCC($ccRecipient); // Add recipients in "CC" field
                                }
                                $companynamemail = $trfprevrev->getColumnVal("companyname_company");
                                $descart = $trfprevrev->getColumnVal("sample_description");
                                $mail->Subject = $appformn . 'r' . $revnumb;
                                if ($_SESSION['langselect'] == 'it') {
                                    // Imposta il testo in italiano
                                    $mail->Body = "Ciao $csinchargeprev! <br> È stato inserito un nuovo ETRF N. $trfnmbmail.<br><br>" .
                                        "Ragione Sociale = $companynamemail<br><br>" .
                                        "Descrizione articolo $descart.<br>";
                                } else if ($_SESSION['langselect'] == 'en') {
                                    // Imposta il testo in inglese
                                    $mail->Body = "Hi $csinchargeprev! <br> A new ETRF No. $trfnmbmail has been submitted.<br><br>" .
                                        "Company Name = $companynamemail<br><br>" .
                                        "Item Description $descart.<br>";
                                } else {
                                    // Imposta un valore di default o gestisci l'errore
                                    $mail->Body = "Language setting is not recognized.";
                                }

                                $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}";
                            }
                        }
                        // exit();
                        /*
//$filename = $filepathname;
  $path = 'pdf';
   $file1 = $path . "/" . $filename1;
   $file2 = $path . "/" . $filename2;
// Recipient 
$to = $emailuser; 
// Sender 
$from = $fromaddresssmail; 
$fromName = 'CIMAC Application Form System';  
// Email subject 
$subject = $appformn;
// Attachment file 
$file = $file1; 
$mmessage="mailtrf";
include('include/mailhtml.php');
// Email body content 
$htmlContent = $mailmessage1; 
// Header for sender info 
$headers = "From: $fromName"." <".$from.">"; 
// Boundary  
$semi_rand = md5(time());  
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";  
// Headers for attachment  
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 
// Multipart boundary  
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" . 
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";  
// Preparing attachment 
if(!empty($file) > 0){ 
    if(is_file($file)){ 
        $message .= "--{$mime_boundary}\n"; 
        $fp =    @fopen($file,"rb"); 
        $data =  @fread($fp,filesize($file)); 
        @fclose($fp); 
        $data = chunk_split(base64_encode($data)); 
        $message .= "Content-Type: application/octet-stream; name=\"".basename($file)."\"\n" .  
        "Content-Description: ".basename($file)."\n" . 
        "Content-Disposition: attachment;\n" . " filename=\"".basename($file)."\"; size=".filesize($file).";\n" .  
        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; 
    } 
} 
$message .= "--{$mime_boundary}--"; 
$returnpath = "-f" . $from; 
// Send email 
$mail = @mail($to, $subject, $message, $headers, $returnpath);  
*/
                    }
                        ?>
                        <div class="card">
                            <div class="card-body">
                                <h4 class="mt-0 header-title"><?php echo $sendtitle; ?></h4>
                                <br><br>
                                <p><?php echo $companyname; ?> <?php echo $sendsentence; ?></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>