<?php
include('includes/config.php');

// Process form at TOP - store results for later display
$reg_result = '';
$reg_type = '';
$redirect_url = '';

if (isset($_POST['reg']) && $_POST['reg'] == "ahkweb") {
  $name = mysqli_real_escape_string($conn, $_POST['name']);
  $mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
  $email = mysqli_real_escape_string($conn, $_POST['email']);
  $password = mysqli_real_escape_string($conn, $_POST['password']);
  $cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']);

  // Validation
  if (empty($name) || empty($mobile) || empty($email) || empty($password) || empty($cpassword)) {
    $reg_result = 'Please Fill All Data';
    $reg_type = 'error';
  } elseif (strlen($mobile) < 10 || strlen($mobile) > 12) {
    $reg_result = 'Invalid Mobile Number!';
    $reg_type = 'error';
  } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $reg_result = 'Invalid Email Address!';
    $reg_type = 'error';
  } elseif (strlen($password) < 6) {
    $reg_result = 'Password must be at least 6 characters!';
    $reg_type = 'error';
  } elseif ($password != $cpassword) {
    $reg_result = 'Confirm Password Not Match!';
    $reg_type = 'error';
  } elseif ($mobile == "ADMIN" || $email == "ADMIN") {
    $reg_result = 'Invalid Input!';
    $reg_type = 'error';
  } else {
    // Check if already exists
    $checksql = mysqli_query($conn, "SELECT * FROM usertable WHERE emailid='$email' OR phone='$mobile'");
    if (mysqli_num_rows($checksql) > 0) {
      $reg_result = 'Your email or phone already exists!';
      $reg_type = 'error';
      $redirect_url = 'general-public.php';
    } else {
      // Create account
      $fpassword = password_hash($cpassword, PASSWORD_DEFAULT);
      $sql = "INSERT INTO `usertable` (`phone`, `emailid`, `name`, `password`, `city`, `state`, `userid`, `status`, `profilepic`, `createdby`, `joineddate`, `joinedtime`, `usertype`, `walletamount`,`otp`) VALUES ('$mobile', '$email', '$name', '$fpassword', '', '', '$mobile', 'verified', '', NULL, '', '', 'OPERATER', '0','')";
      $res = mysqli_query($conn, $sql);
      
      if ($res) {
        $reg_result = 'Register Successfully! You can Login';
        $reg_type = 'success';
        $redirect_url = 'general-public.php';
      } else {
        $reg_result = 'Internal Server Error, Please Try Again Later!';
        $reg_type = 'error';
      }
    }
  }
}

// Already logged in? Redirect to dashboard
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
    header("Location: crs/index.php");
    exit();
}
?>

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

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title> <?php echo $ahkweb['name']; ?> | Registration </title>

  <!-- Google Font: Source Sans Pro -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="./crs/plugins/fontawesome-free/css/all.min.css">
  <!-- icheck bootstrap -->
  <link rel="stylesheet" href="./crs/plugins/icheck-bootstrap/icheck-bootstrap.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="./crs/dist/css/adminlte.min.css">
</head>

<body class="hold-transition register-page">
  <div class="register-box">
    <div class="register-logo">
      <a href="index.php"><b>General Public Sign Up</a>
    </div>

    <div class="card">
      <div class="card-body register-card-body">
        <p class="login-box-msg">Register as a New Member</p>

        <form action="" method="POST">
          <div class="input-group mb-3">
            <input type="text" name="name" class="form-control" placeholder="Full name">
            <div class="input-group-append">
              <div class="input-group-text">
                <span class="fas fa-user"></span>
              </div>
            </div>
          </div>
          <div class="input-group mb-3">
            <input type="text" class="form-control" name="mobile" placeholder="Mobile Number">
            <div class="input-group-append">
              <div class="input-group-text">
                <span class="fas fa-phone"></span>
              </div>
            </div>
          </div>
          <div class="input-group mb-3">
            <input type="email" class="form-control" name="email" placeholder="Email">
            <div class="input-group-append">
              <div class="input-group-text">
                <span class="fas fa-envelope"></span>
              </div>
            </div>
          </div>
          <div class="input-group mb-3">
            <input type="password" class="form-control" name="password" placeholder="Password">
            <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" class="form-control" name="cpassword" placeholder="Retype password">
            <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="hidden" name="reg" value="ahkweb">
               
                <input type="checkbox" id="agreeTerms" name="terms" value="agree">
                <label for="agreeTerms">
                  I agree to the <a href="#">terms</a>
                </label>
              </div>
            </div>
            <!-- /.col -->
            <div class="col-4">
              <button type="submit" class="btn btn-primary btn-block">Sign Up</button>
            </div>
            <!-- /.col -->
          </div>
        </form>

  

        <a href="general-public" class="text-center">Click to login</a>
      </div>
      <!-- /.form-box -->
    </div><!-- /.card -->
  </div>
  <!-- /.register-box -->

  <!-- jQuery -->
  <script src="./crs/plugins/jquery/jquery.min.js"></script>
  <!-- Bootstrap 4 -->
  <script src="./crs/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
  <!-- AdminLTE App -->
  <script src="./crs/dist/js/adminlte.min.js"></script>
  <!-- SweetAlert2 -->
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  
  <?php if(!empty($reg_result)): ?>
  <script>
    $(function(){
      Swal.fire({
        icon: '<?php echo $reg_type; ?>',
        title: '<?php echo ($reg_type == "success") ? "Success!" : "Oops!"; ?>',
        text: '<?php echo $reg_result; ?>',
        confirmButtonColor: '<?php echo ($reg_type == "success") ? "#28a745" : "#dc3545"; ?>'
      })<?php if(!empty($redirect_url)): ?>.then(function(){
        window.location.href = '<?php echo $redirect_url; ?>';
      })<?php endif; ?>;
    });
  </script>
  <?php endif; ?>
</body>

</html>