<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once('../Connections/cmctrfdb.php'); ?>
<?php require_once('../webassist/mysqli/rsobj.php'); ?>
<?php require_once('../webassist/mysqli/queryobj.php'); ?>
<?php

// include('include/headscript.php'); 
?>

<?php  //insert query
if (isset($_POST['adduser'])) {
    if (isset($_POST['first_name'])) {
        $first_name = $_POST['first_name'];
    }
    if (isset($_POST['last_name'])) {
        $last_name = $_POST['last_name'];
    }
    if (isset($_POST['emailuser'])) {
        $emailuser = $_POST['emailuser'];
    }
    if (isset($_POST['datein'])) {
        $datein = $_POST['datein'];
    }
    if (isset($_POST['language'])) {
        $langid = $_POST['language'];
    }
    if (isset($_POST['company_name'])) {
        $company_name = $_POST['company_name'];
    }
    if (isset($_POST['vat_number'])) {
        $vat_number = $_POST['vat_number'];
    }
    if (isset($_POST['terms_accepted'])) {
        $terms_accepted = $_POST['terms_accepted'];
    }
    if (isset($_POST['privacy_accepted'])) {
        $privacy_accepted = $_POST['privacy_accepted'];
    }

    $checkmail = new WA_MySQLi_RS("checkmail", $cmctrfdb, 0);
    $checkmail->setQuery("SELECT * FROM auth_users WHERE auth_users.email='$emailuser'");
    $checkmail->execute();
    if (!empty($checkmail->getColumnVal("id"))) {
        $varmailrepeat = 'Y'; ?>

<?php
    } else {

        $mysqli = new mysqli($hostname_cmctrfdb, $username_cmctrfdb, $password_cmctrfdb, $database_cmctrfdb);

        $query = "INSERT INTO auth_users (email, first_name, last_name, password, role_id, status, email_verified_at, created_at, updated_at, langid, termuseaccepted, privacyaccepted, company_name, vat_number) VALUES ('$emailuser', '$first_name', '$last_name', '12345!AA', '2', 'Active', '$datein', '$datein', '$datein', '$langid', '$datein', '$datein', '$company_name', '$vat_number')";

        // Esegui la query
        $mysqli->query($query);
        $inserttrue = 'Y';
        // Chiudi la connessione al database
        $mysqli->close();

        //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 = "smtp.office365.com";  // Specify main and backup server
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            $mail->Username = "noreply@cimac.it";                            // SMTP username
            $mail->Password = "Fol42937";                           // SMTP password
            $mail->SMTPSecure = "tls";                            // Enable encryption, 'ssl' also accepted
            $mail->Port       = 587;

            $mmessage = "mailnewuser";
            include('include/mailnewuser.php');
            // Email body content 
            $htmlContent = $mailmessage1;

            $mail->From = $fromaddresssmail;
            $mail->FromName = 'CIMAC Application Form System';
            $mail->addAddress($emailuser);  // Add a recipient

            $mail->Subject = "Creazione Nuovo Utente";
            $mail->Body    = $htmlContent;
            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

            $mail->send();
        } catch (Exception $e) {
            echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
        }

        // mail to Marco for new user
        $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;

            // Email body content 
            $mail->From = $fromaddresssmail;
            $mail->FromName = 'CIMAC Application Form System';
            $mail->addBCC('m.piccolini@cimac.it');  // Add a recipient 
            $mail->addBCC($csmail);  // Add a recipient 
            $mail->addBCC($csmail3);
            $mail->addBCC('info@acscreativesolutions.com');

            $mail->Subject = 'Nuovo Utente';
            $mail->Body    = "Ciao! E' stato inserito un nuovo Utente $emailuser ";
            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

            $mail->send();
        } catch (Exception $e) {
            echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>CIMAC Application Form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta content="Premium Multipurpose Admin & Dashboard Template" name="description" />
    <meta content="" name="author" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

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

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


</head>

<body class="account-body accountbg">

    <!-- Log In page -->
    <div class="container-fluid">
        <div class="row vh-100 ">
            <div class="col-12 align-self-center">
                <div class="auth-pagea">
                    <div class="card auth-card shadow-lg" style="max-width: 800px; width: 100%; margin: 0 auto;">

                        <div class="card-body">
                            <div class="px-3">
                                <div>
                                    <a href="https://www.cimac.it/modulo_certificazione/public/login" class="logo logo-admin"><img src="assets/img/cimac-logo.png" height="55" alt="logo" class="auth-logo"></a>
                                </div><!--end auth-logo-box-->

                                <div class="text-center auth-logo-text">
                                    <h4 class="mt-0 mb-3 mt-5">REGISTRAZIONE PIATTAFORMA PPEASY<br>REGISTRATION PPEASY PLATFORM</h4>

                                </div> <!--end auth-logo-text-->

                                <?php if (isset($varmailrepeat)) { ?>
                                    <div class="alert icon-custom-alert alert-outline-pink b-round fade show" role="alert">
                                        <i class="mdi mdi-alert-outline alert-icon"></i>
                                        <div class="alert-text">
                                            <strong>Email già presente nel database.
                                        </div>

                                        <div class="alert-close">
                                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                <span aria-hidden="true"><i class="mdi mdi-close text-danger"></i></span>
                                            </button>
                                        </div>
                                    </div><?php } ?>

                                <?php if (isset($inserttrue)) { ?>
                                    <div class="alert icon-custom-alert alert-outline-success alert-success-shadow" role="alert">
                                        <i class="mdi mdi-check-all alert-icon"></i>
                                        <div class="alert-text">
                                            <strong>Ben fatto!</strong> Utente creato con successo.
                                        </div>

                                    </div>
                                    <p>Presto riceverai una mail per impostare la tua prima password e poi potrai procedere con l'uso del portale!</p><br>
                                    <p>Soon you will receive an email in order to setup your first password and then you can start to use the portal!</p><br>
                                <?php } ?>
                                <?php if (!isset($inserttrue)) { ?>
                                    <form class="form-horizontal auth-form my-4" action="auth-creation.php" method="post" name="usernew" onsubmit="return validateForm();">
                                        <?php $nowtime = date("Y-m-d G:i:s"); ?>
                                        <div class="form-group">
                                            <label for="useremail">Nome/Name</label>
                                            <div class="input-group mb-3">
                                                <span class="auth-form-icon">
                                                    <i class="dripicons-user"></i>
                                                </span>
                                                <input type="text" class="form-control" id="first_name" name="first_name" placeholder="Nome/Name" required>
                                            </div>
                                        </div><!--end form-group-->

                                        <div class="form-group">
                                            <label for="useremail">Cognome / Surname</label>
                                            <div class="input-group mb-3">
                                                <span class="auth-form-icon">
                                                    <i class="dripicons-user"></i>
                                                </span>
                                                <input type="text" class="form-control" id="last_name" name="last_name" placeholder="Cognome / Surname" required>
                                            </div>
                                        </div><!--end form-group-->

                                        <div class="form-group">
                                            <label for="useremail">Email</label>
                                            <div class="input-group mb-3">
                                                <span class="auth-form-icon">
                                                    <i class="dripicons-mail"></i>
                                                </span>
                                                <input type="email" class="form-control" id="emailuser" name="emailuser" placeholder="Email" required>
                                            </div>
                                        </div><!--end form-group-->

                                        <div class="form-group">
                                            <label for="useremail">Ragione sociale azienda / Company Name</label>
                                            <div class="input-group mb-3">
                                                <span class="auth-form-icon">
                                                    <i class="dripicons-briefcase"></i>
                                                </span>
                                                <input type="text" class="form-control" id="company_name" name="company_name" placeholder="Ragione sociale azienda / Company Name" required>
                                            </div>
                                        </div><!--end form-group-->

                                        <div class="form-group">
                                            <label for="useremail">P.IVA azienda / Vat Number or ID Tax Number</label>
                                            <div class="input-group mb-3">
                                                <span class="auth-form-icon">
                                                    <i class="dripicons-id"></i>
                                                </span>
                                                <input type="text" class="form-control" id="vat_number" name="vat_number" placeholder="P.IVA azienda / Vat Number or ID Tax Number" required>
                                            </div>
                                        </div><!--end form-group-->

                                        <div class="form-row">

                                            <div class="col-md-8 mb-8">
                                                <label for="exampleFormControlSelect1">Lingua / Language</label>
                                                <select class="form-control" id="language" name="language" required>
                                                    <option value="1">Italiano</option>
                                                    <option value="2">English</option>
                                                </select>
                                            </div>

                                            <input type="hidden" id="status" name="status" value="Active">
                                            <input type="hidden" id="role_id" name="role_id" value="2">
                                            <input type="hidden" id="adduser" name="adduser" value="Y">
                                            <input type="hidden" id="datein" name="datein" value="<?php echo $nowtime; ?>">
                                        </div>

                                        <div class="form-group row mt-4">
                                            <div class="col-sm-12">
                                                <div class="custom-control custom-switch switch-success">
                                                    <input type="checkbox" class="custom-control-input" id="terms_accepted" name="terms_accepted" onchange="checkAcceptance()">
                                                    <label class="custom-control-label" for="terms_accepted">Registrandoti accetti i termini e le condizioni d’uso della piattaforma PPEASY <a href="terminiecondizioni.php" target="_blank"><u>qui presenti</u></a> / By registering you agree to <a href="termsandconditions.php" target="_blank"><u>these terms and conditions</u></a> of use of the PPEASY platform </label>
                                                </div>
                                                <div class="custom-control custom-switch switch-success">
                                                    <input type="checkbox" class="custom-control-input" id="privacy_accepted" name="privacy_accepted" onchange="checkAcceptance()">
                                                    <label class="custom-control-label" for="privacy_accepted">Dichiaro di aver letto e compreso l’informativa sui dati personali <a href="informativappeasy.php" target="_blank"><u>qui presente</u></a>. / I declare that I have read and understood the information on <a href="informativappeasy_eng.php" target="_blank"><u>personal data herein</u></a>.</label>
                                                </div>
                                            </div><!--end col-->
                                        </div><!--end form-group-->

                                        <div class="form-group mb-0 row">
                                            <div class="col-12 mt-2">
                                                <button class="btn btn-round btn-block" type="submit" id="registerButton" disabled style="background-color: #f5f5f5; color: #333333;">Registrati / Register <i class="fas fa-sign-in-alt ml-1"></i></button>
                                            </div><!--end col-->
                                        </div> <!--end form-group-->
                                    </form><?php } ?><!--end form-->
                            </div><!--end /div-->

                            <div class="m-3 text-center text-muted">
                                <p class="">Hai già un account? / Already have an account ? <a href="login" class="text-primary ml-2">Log in</a></p>
                                <br>
                                <p> <a href="regolamentoprivacy.php" target="_blank">Privacy Policy ITA</a> / <a href="privacydoc.php" target="_blank">Privacy Policy ENG</a> - <a href="cookie-policy-it.php" target="_blank">Cookie Policy ITA</a> / <a href="cookie-policy-en.php" target="_blank">Cookie Policy ENG</a> </p>
                            </div>
                        </div><!--end card-body-->
                    </div><!--end card-->
                </div><!--end auth-card-->
            </div><!--end col-->
        </div><!--end row-->
    </div><!--end container-->

    <!-- End Log In page -->

    <!-- jQuery  -->
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/jquery-ui.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>

    <!-- App js -->
    <script src="../assets/js/app.js"></script>

    <script>
        function validateForm() {
            var termsAccepted = document.getElementById("terms_accepted").checked;
            var privacyAccepted = document.getElementById("privacy_accepted").checked;
            if (!termsAccepted || !privacyAccepted) {
                alert("Devi accettare i Termini di Uso e la Privacy Policy per registrarti / You must accept the Terms of Use and Privacy Policy to register.");
                return false;
            }
            return true;
        }

        function checkAcceptance() {
            var termsAccepted = document.getElementById("terms_accepted").checked;
            var privacyAccepted = document.getElementById("privacy_accepted").checked;
            var registerButton = document.getElementById("registerButton");
            if (termsAccepted && privacyAccepted) {
                registerButton.disabled = false;
                registerButton.className = "btn btn-gradient-primary btn-round btn-block waves-effect waves-light";
                registerButton.style.backgroundColor = "";
                registerButton.style.color = "";
            } else {
                registerButton.disabled = true;
                registerButton.className = "btn btn-round btn-block";
                registerButton.style.backgroundColor = "#f5f5f5";
                registerButton.style.color = "#333333";
            }
        }

        // Initial check on page load
        window.onload = checkAcceptance;
    </script>

    <!-- Cookie Banner -->
    <div id="cookie-banner" style="position: fixed; bottom: 0; width: 100%; background: #333; color: #fff; padding: 15px; text-align: center; z-index: 1000; font-family: Arial, sans-serif;">
        <div id="cookie-text">
            <p>
                Questo sito utilizza esclusivamente cookie tecnici per garantire funzionalità essenziali (come login e sicurezza).
                <a href="cookie-policy-it.php" target="_blank" style="color: #fff; text-decoration: underline; margin-left: 5px;">Scopri di più</a>
            </p>
            <p>
                This site uses only technical cookies to ensure essential features (such as login and security).
                <a href="cookie-policy-en.php" target="_blank" style="color: #fff; text-decoration: underline; margin-left: 5px;">Learn more</a>
            </p>
        </div>

        <div>
            <button onclick="closeBanner()" style="background: #28a745; color: #fff; border: none; padding: 8px 16px; margin: 5px; cursor: pointer;">OK</button>
        </div>
    </div>

    <script>
        function closeBanner() {
            document.getElementById('cookie-banner').style.display = 'none';
            localStorage.setItem('cookiesAcknowledged', 'true');
        }

        // Nasconde il banner se l'utente ha già chiuso
        window.onload = function() {
            if (localStorage.getItem('cookiesAcknowledged')) {
                document.getElementById('cookie-banner').style.display = 'none';
            }
        };
    </script>


</body>

</html>