<?php 
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;

     
    require 'vendor/autoload.php';

    include 'includes/connection.php';
    $msg = "";

    if (isset($_POST['submit'])) {
        $name = mysqli_real_escape_string($conn, $_POST['FullName']);
        $email = mysqli_real_escape_string($conn, $_POST['Email']);
        $user_type = mysqli_real_escape_string($conn, $_POST['user_type']);
        $terms = mysqli_real_escape_string($conn, $_POST['terms']);
        $Role = mysqli_real_escape_string($conn, $_POST['Role']);
        $password = mysqli_real_escape_string($conn, md5($_POST['PasswordHash']));
        $confirm_password = mysqli_real_escape_string($conn, md5($_POST['confirm-password']));
        $code = mysqli_real_escape_string($conn, md5(rand()));
        $added_by = 'admin'; // Or fetch dynamically if needed
 
        if (mysqli_num_rows(mysqli_query($conn, "SELECT * FROM student_soes WHERE student_email_id='{$email}'")) > 0) {
            $msg = "<div class='alert alert-danger'>{$email} - This email address has been already exists.</div>";
        } else {
            if ($password === $confirm_password) {
                $sql = "INSERT INTO student_soes (student_name, student_email_id, user_type, terms, Role, PasswordHash, code, student_added_by) 
                        VALUES ('{$name}', '{$email}', '{$user_type}', '{$terms}', '{$Role}', '{$password}', '{$code}', '{$added_by}')";
                $result = mysqli_query($conn, $sql);

                if ($result) {
                    echo "<div style='display: none;'>"; 
                    $mail = new PHPMailer(true);

                    try {
                        //Server settings
                        $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
                        $mail->isSMTP();                                            //Send using SMTP
                        $mail->Host       = 'mail.cybercode.co.tz';                     //Set the SMTP server to send through
                        $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
                        $mail->Username   = 'support@cybercode.co.tz';            //SMTP username
                        $mail->Password   = 'CYBER@support@2024';                   //SMTP password
                        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;            //Enable implicit TLS encryption
                        $mail->Port       = 587;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

                        //Recipients
                        $mail->setFrom('support@cybercode.co.tz');
                        $mail->addAddress($email);

                        //Content
                        $mail->isHTML(true);                                  //Set email format to HTML
                        $mail->Subject = 'Cybercode Academy';
                        $mail->Body    = '
                        Dear '.$name.'<br>
                        Thank you for registering with Cybercode Academy! Before you can access your account, please verify your email address, then login to the portal <br><br>
                        Verify Your Email<br>
                        Click the link below to confirm your email address:<br>
                        <b><a href="https://cybercode.co.tz/orbital/index.php?verification='.$code.'"> Verify My Email Address </a> </b><br><br>
                        
                        
                        Best regards <br>
                        The Cybercode Academy Team ';

                        $mail->send();
                        echo 'Message has been sent';
                    } catch (Exception $e) {
                        echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
                    }
                    echo "</div>";
                    $msg = "<div class='alert alert-info'>We've send a verification link on your email address.</div>";
                } else {
                    $msg = "<div class='alert alert-danger'>Something wrong went.</div>";
                }
            } else {
                $msg = "<div class='alert alert-danger'>Password and Confirm Password do not match</div>";
            }
        }
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <title>Cybercode| Cybersecurity Traininings and resources</title>  
  <link href="assets/img/logo_3.jpg" rel="icon">
  <link href="assets/img/logo_3.jpg" rel="apple-touch-icon">  
  <link rel="stylesheet" href="stp_con/fontawesome-free/css/all.min.css"> 
  <link rel="stylesheet" href="stp_con/icheck-bootstrap/icheck-bootstrap.min.css"> 
  <link rel="stylesheet" href="assets/css/adminlte.min.css">
   <style>
    body {  
      background-image: url('assets/img/back.png'); /* replace with your image */
      background-size: cover;
      background-position: center;
      position: relative; 
      margin: 0px auto; 
    }
    .whatsapp-button {
      position: fixed;
      bottom: 20px;
      right: 20px; 
      color: white;
      border: none;
      border-radius: 50px;
      padding: 12px 24px;
      font-size: 16px;
      font-weight: bold;
      cursor: pointer;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
      z-index: 999;
    }
</style>
</head>
<body class="hold-transition register-page">
<div class="register-box">
   <div class="card card-widget widget-user card-info card-outline">
      <!-- Add the bg color to the header using any of the bg-* classes -->
      <div class="widget-user-header text-white"
           style="background: url('assets/img/cyber1.jpg') center center;">
        <h3 class="widget-user-username text-right">Cybercode Academy</h3>
        <h5 class="widget-user-desc text-right">Register</h5>
      </div> 
      <div class="widget-user-image">
        <img class="img-circle" src="assets/img/icon.png" alt="User Avatar">
     </div>  
     <br>
    <div class="card-body register-card-body">
      <p class="login-box-msg">Register a new membership</p>
       <?php echo $msg; ?>
      <form action="" method="post" id="quickForm">
        <div class="input-group mb-3">
          <input type="text" name="FullName" class="form-control" placeholder="Full name" required>
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-user"></span>
            </div>
          </div>
        </div>
        <input type="hidden" name="Role" value="Training">
        <div class="input-group mb-3">
          <input type="email" name="Email" class="form-control" id="exampleInputEmail1" placeholder="Email" required>
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-envelope"></span>
            </div>
          </div>
        </div>
        <div class="mb-3">
         <select name="user_type" id="user_type" class="form-control" required> 
           <!--<option value="Professional">Cybersecurity Professional</option>-->
            <option value="Digital">Digital User</option>
              
            
        </select>
        </div>
        <div class="input-group mb-3">
          <input type="password" name="PasswordHash" class="form-control" id="exampleInputPassword1" placeholder="Password" required>
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-lock"></span>
            </div>
          </div>
        </div>
        <div class="input-group mb-3">
          <input type="password" name="confirm-password" class="form-control" placeholder="Retype password" required>
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-lock"></span>
            </div>
          </div>
        </div> 
        <div class="row">
          <div class="col-8"> 
           <div class="icheck-primary">
              <input type="checkbox" name="terms" id="agreeTerms" value="agree">
              <label for="agreeTerms">
               I agree to the <a href="https://academy.cybercode.co.tz/terms.php">terms</a>
              </label>
            </div>
          </div>
          <!-- /.col -->
          <div class="col-4">
            <button type="submit" name="submit" class="btn btn-primary btn-block">Register</button>
          </div>
          <!-- /.col -->
        </div>
      </form> 
      <br>
      I already have a membership <a href="index.php" class="text-center">Sign in</a>
       <hr>
        <center><span style="font-size: 18px;">&copy;</span><?php echo date('Y'); ?></center>
        <button class="whatsapp-button btn-info" onclick="contactViaWhatsApp()">Contact Us</button>
  </div> 
</div> 
<script src="stp_con/jquery/jquery.min.js"></script> 
<script src="stp_con/bootstrap/js/bootstrap.bundle.min.js"></script> 
<script src="stp_con/jquery-validation/jquery.validate.min.js"></script>
<script src="stp_con/jquery-validation/additional-methods.min.js"></script> 
<script src="assets/js/adminlte.min.js"></script>
</body>
<script>
$(function () { 
  $('#quickForm').validate({
    rules: {
      email: {
        required: true,
        email: true,
      },
      password: {
        required: true,
        minlength: 5
      },
      terms: {
        required: true
      },
    },
    messages: {
      email: {
        required: "Please enter a email address",
        email: "Please enter a valid email address"
      },
      password: {
        required: "Please provide a password",
        minlength: "Your password must be at least 5 characters long"
      },
      terms: "Please accept our terms"
    },
    errorElement: 'span',
    errorPlacement: function (error, element) {
      error.addClass('invalid-feedback');
      element.closest('.form-group').append(error);
    },
    highlight: function (element, errorClass, validClass) {
      $(element).addClass('is-invalid');
    },
    unhighlight: function (element, errorClass, validClass) {
      $(element).removeClass('is-invalid');
    }
  });
});
</script>
<script>
  function contactViaWhatsApp() {
    // Replace with your actual WhatsApp number, format: 255xxxxxxxxx (no + or 0)
    const phoneNumber = '255757660790';
    const message = 'Hello, I would like to contact you!';
    const url = `https://api.whatsapp.com/send/?phone=${phoneNumber}&text=Hello%2C+I+would+like+to+contact+you%21&type=phone_number&app_absent=0`;
    window.open(url, '_blank');
  }
</script>
</html>
