<?php

$tt_page_info = array(
  'Page_Info' =>   array(
    'Title' => 'Register',
    'Description' => '',
    'Keyword' => '',
  ),
  'Social_og' => array(
    'Image' => '',
    'Type' => 'website',
    'URL' => 'register/',
  ),
);

$errors = array();
// Register Pages
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $mahamudfutureit_key = md5(randomString().time());
    // Initialize an array to store validation errors


    // Check if CSRF token is valid
    $csrf_token = $_POST['csrf_token'] ?? '';
    if (!verifyCSRFToken($csrf_token)) {
      $errors[] = 'আবার চেষ্টা করুণ  !';
    } else {

      // Validate name fields (remove special characters and check length)
      $acc_name_bn = $_POST['UserName'] ?? '';

      // Remove special characters from the names (allowing Bangla characters and spaces)
      $acc_name_bn = htmlentities($acc_name_bn, ENT_QUOTES, 'utf-8');

      // Check if the names are greater than 3 characters
      if (strlen($acc_name_bn) < 3) {
        $errors[] = 'সঠিক নাম (বাংলা) ব্যবহার করুণ  !';
      }

      // Validate name fields (remove special characters and check length)
      $acc_name_en = $_POST['UserNameEN'] ?? '';

      // Remove special characters from the names (allowing Bangla characters and spaces)
      $acc_name_en = htmlentities($acc_name_en, ENT_QUOTES, 'utf-8');

      // Check if the names are greater than 3 characters
      if (strlen($acc_name_en) < 3) {
        $errors[] = 'সঠিক নাম (English) ব্যবহার করুণ  !';
      }


       // Validate email
      $acc_email = $_POST['UserEmail'] ?? '';
      if (!filter_var($acc_email, FILTER_VALIDATE_EMAIL) || !preg_match("/^[a-zA-Z0-9._%+-]+@(gmail\.com|yahoo\.com|outlook\.com|hotmail\.com|icloud\.com)$/", $acc_email)) {
        $errors[] = 'সঠিক ইমেইল ব্যবহার করুণ  !';
      }else {
         if (getSingleValue('tt_accounts', 'UserEmail',  $acc_email, 'UserID') != false) {
           $errors[] = 'এই ইমেইল গ্রহণযোগ্য নয়  !';
         }
      }

      // Validate phone number (minimum 11 numeric digits)
      $acc_mobile = $_POST['UserMobile'] ?? '';
      if (!preg_match("/^0[1][3-9][0-9]{8}$/", $acc_mobile)) {
          $errors[] = 'প্রধান মোবাইল নাম্বারটি গ্রহণযোগ্য নয়! বাংলাদেশের মোবাইল নাম্বার ব্যবহার করুণ ।';
      } else {
          if (getSingleValue('tt_accounts', 'UserMobile', $acc_mobile, 'UserID') != false) {
              $errors[] = 'প্রধান মোবাইল নাম্বার গ্রহণযোগ্য নয়!';
          }
      }

      // passwordInput
      $acc_pwd = $_POST['password'] ?? '';
      if ($acc_pwd =='') {
        $errors[] = 'সঠিক ভাবে পাসওয়ার্ড প্রদান করুন';
      }

      // If Verification Method off , default varified account
      if ($advancenews['REG_OTP_METHODE'] == 'OFF') {
        $verification_status = 'Verified';
        $user_profile = 'active';
      }else {
        $verification_status = 'Unverified';
        $user_profile = 'deactive';
      }


      // If there are no errors, proceed with inserting data into the database
      if (empty($errors)) {
          $post_form_data = array(
            'UserName' => $acc_name_bn,
            'UserNameEN' => $acc_name_en,
            'UserEmail' => $acc_email,
            'UserMobile' => $acc_mobile,
            'UserPassword' => password_hash($acc_pwd, PASSWORD_BCRYPT),
            'UserLoginKey' => $mahamudfutureit_key,
            'AccountStatus' => 'active',
            'UserProfile' => $user_profile,
            'PostAbility' => 'none',
            'UpdateProfile' => 'active',
            'PostPublish' => 'Manually',
            'CommentAbility' => 'none',
            'FirstVerificationStatus' => $verification_status,
            'JoinDate' => $the_time,
          );

          // Insert data into the database
          $insert_now = InsertData('tt_accounts', $post_form_data);

          if ($insert_now) {
              setcookie("lsp_cpa", $mahamudfutureit_key, time() + (86400 * 7), "/");

              header("Location:".$tt_site_domain."account/");
              exit;
          } else {
            $errors[] =  'আবার চেষ্টা করুণ  !';
          }

          // Regenerate the token to avoid reuse
          unset($_SESSION['csrf_token']);
      }
    }
}
require_once('./header.php'); // Include Footer
?>
<section id="join_mahamudfutureit" class="pt-4 pb-4">
    <div class="container">
        <div class="row">
            <section class="col-md-6 align-self-center">
              <div class="w300 text-center">
                  <img width="230" src="<?php echo $advancenews['Website_Logo'] ?>" alt="<?php echo $advancenews['Website_title'] ?>">
                  <h6 class="mt-3"><?php echo $advancenews['Login_stitle'] ?></h6><h6> <?php echo $advancenews['Website_Description'] ?> </h6>
              </div>
            </section>
            <section class="col-md-6 align-self-center">
                <section class="login-page">
                    <div class="attraiit-card card p-2  p-md-4 ml-auto mr-auto border-0">
                        <h4 class="text-center">রেজিস্ট্রেশন করুণ</h4>
                        <p class="text-center fw-bold"><?php echo $advancenews['Register_title'] ?></p>
                        <?php
                        if ($advancenews['New_register_status'] != 'active') {
                          ?>
                          <div class="alert alert-warning text-center">
                            নিবন্ধন প্রক্রিয়া সাময়িক বন্ধ রয়েছে !
                          </div>
                          <?php
                        }else {
                          ?>
                          <form action="" method="post" class="needs-validation <?php if (isset($_POST['requestJoin'])) { echo 'was-validated'; } ?>" novalidate>
                             <?php
                             if (!empty($errors)) {
                               // If there are errors, display them
                               foreach ($errors as $error) {
                                   ?>
                                   <div class="alert alert-danger" role="alert">
                                     <?php echo $error ?>
                                   </div>
                                   <?php
                               }
                             }
                             ?>
                             <div class="row">
                               <div class="col-md-6">
                                 <div class="form-floating mb-3">
                                     <input autocomplete="off" name="UserName" type="text" class="form-control rounded-0" id="u-name" value="<?php echo (isset($acc_name_bn) ? $acc_name_bn : '') ?>" placeholder="নাম"   required>
                                     <label for="u-name">আপনার নাম (বাংলায়)</label>
                                     <div class="invalid-feedback">
                                       আপনার সম্পুর্ন নাম লিখুন !
                                     </div>
                                 </div>
                               </div>
                                 <div class="col-md-6">
                                   <div class="form-floating mb-3">
                                       <input pattern="[A-Za-z ]{3,35}" autocomplete="off" name="UserNameEN" type="text" class="form-control rounded-0" id="ue-name"  value="<?php echo (isset($acc_name_en) ? $acc_name_en : '') ?>" placeholder="Your Name"   required>
                                       <label for="ue-name">আপনার নাম (ইংরেজি অক্ষরে)</label>
                                       <div class="invalid-feedback">
                                         ইংরেজি অক্ষরে আপনার সম্পুর্ন নাম লিখুন !
                                       </div>
                                   </div>
                                 </div>
                                 <div class="col-md-6">
                                   <div class="form-floating mb-3">
                                       <input pattern="^[a-zA-Z0-9._%+-]+@(gmail\.com|yahoo\.com|outlook\.com|hotmail\.com|icloud\.com)$" name="UserEmail" type="email" class="form-control rounded-0" id="uMail" placeholder="ইমেইল"  value="<?php echo (isset($acc_email) ? $acc_email : '') ?>" required>
                                       <label for="uMail">ইমেইল </label>
                                       <div id="inEmail" class="invalid-feedback">
                                         সঠিক ইমেইল ঠিকানা লিখুন !
                                       </div>
                                   </div>
                                 </div>
                                 <div class="col-md-6">
                                   <div class="form-floating mb-3">
                                       <input autocomplete="off" name="UserMobile" type="text" inputmode="numeric"  pattern="^0[1][3-9][0-9]{8}$" class="rounded-0 form-control in-valid" id="uMobile" value="<?php echo (isset($acc_mobile) ? $acc_mobile : '') ?>" placeholder="মোবাইল নাম্বার" value=""  required>
                                       <label for="uMobile">মোবাইল নাম্বার</label>
                                       <div id="inMobile" class="invalid-feedback">
                                         ১১ সংখ্যায় বাংলাদেশের মোবাইল নাম্বার নাম্বার লিখুন !
                                       </div>
                                   </div>
                                 </div>
                             </div>



                             <div class="form-floating mb-3">
                                 <input class="form-control rounded-0 "  autocomplete="off" name="password" type="password" id="passwordInput" placeholder="********" minlength="8" maxlength="32" required>
                                 <label for="password">পাসওয়ার্ড</label>
                                 <span class="pwd_icon" id="togglePassword" style="cursor: pointer;">
                                     <i class="bi bi-eye"></i>
                                 </span>
                                 <div class="invalid-feedback">
                                     ৮ থেকে ৩২ ডিজিটের পাসওয়ার্ড লিখুন!
                                 </div>
                             </div>

                              <div class="form-check">
                                  <input class="form-check-input" type="checkbox" value="" id="defaultCheck1" required>
                                  <label class="form-check-label" for="defaultCheck1">
                                      আমি স্বীকার করছি উপরের সকল তথ্য সঠিক। ওয়েবসাইট ব্যহারের সকল নীতিমালা মেনে চলতে অঙ্গীকারবদ্ধ ।
                                  </label>
                              </div>
                              <div class="d-grid gap-2 mt-3">
                                   <button class="btn btn-primary" value="<?php echo time() ?>" name="requestJoin" type="submit">নিবন্ধন আবেদন করুণ </button>
                              </div>
                              <div class="mt-2 text-center">
                                  অ্যাকাউন্ট থাকলে <a href="<?php echo $site_domain;?>login"> <u>লগইন করুণ</u> </a> ।
                              </div>
                              <?php echo csrfField() ?>
                          </form>
                          <?php
                        }
                        ?>
                    </div>
                </section>
            </section>
        </div>
    </div>
</section>
<script>
    const passwordInput = document.getElementById('passwordInput');
    const togglePassword = document.getElementById('togglePassword');
    togglePassword.addEventListener('click', function () {
        const isPassword = passwordInput.type === 'password';
        passwordInput.type = isPassword ? 'text' : 'password';
        const icon = togglePassword.querySelector('i');
        icon.classList.toggle('bi-eye');
        icon.classList.toggle('bi-eye-slash');
    });
</script>
<?php
require_once('./footer.php'); // Include Footer
?>
