<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "auth/config.php";
include 'auth/function.php';
include_once 'includes/subscription_lib.php';
include_once 'includes/notify_lib.php';
include_once 'includes/white_label_lib.php';
block_if_white_label_domain($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"/>
<title>Register | <?php echo $site_settings['brand_name']; ?></title>
<link rel="icon" type="image/x-icon" href="common/img/favicon.png"/>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Inter',sans-serif;min-height:100vh;background:linear-gradient(135deg,#0f0c29,#302b63,#24243e);display:flex;align-items:flex-start;justify-content:center;padding:40px 20px;position:relative;overflow-x:hidden;overflow-y:auto}
.blob{position:fixed;border-radius:50%;filter:blur(80px);opacity:.25;pointer-events:none}
.b1{width:500px;height:500px;background:#6c63ff;top:-100px;left:-100px;animation:blobMove 12s ease-in-out infinite alternate}
.b2{width:400px;height:400px;background:#ff6584;bottom:-80px;right:-80px;animation:blobMove 10s ease-in-out infinite alternate-reverse}
.b3{width:300px;height:300px;background:#43e97b;top:50%;left:50%;transform:translate(-50%,-50%);animation:blobMove 8s ease-in-out infinite alternate}
@keyframes blobMove{0%{transform:scale(1) translate(0,0)}100%{transform:scale(1.15) translate(30px,20px)}}
.card{background:rgba(255,255,255,.06);backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.12);border-radius:24px;padding:40px 36px;width:100%;max-width:460px;position:relative;z-index:1;box-shadow:0 30px 80px rgba(0,0,0,.4)}
.logo-wrap{text-align:center;margin-bottom:28px}
.logo-wrap img{max-height:50px;object-fit:contain;filter:drop-shadow(0 4px 12px rgba(108,99,255,.4))}
.brand-name{font-size:22px;font-weight:800;color:#fff;text-align:center;margin-bottom:6px}
.brand-sub{font-size:13px;color:rgba(255,255,255,.45);text-align:center;margin-bottom:28px}
.fg{margin-bottom:18px}
.fg label{display:block;font-size:12px;font-weight:600;color:rgba(255,255,255,.6);margin-bottom:7px;text-transform:uppercase;letter-spacing:.5px}
.input-wrap{position:relative}
.input-wrap i{position:absolute;left:14px;top:50%;transform:translateY(-50%);color:rgba(255,255,255,.3);font-size:14px;pointer-events:none}
.input-wrap input{width:100%;background:rgba(255,255,255,.07);border:1.5px solid rgba(255,255,255,.1);border-radius:12px;padding:13px 44px 13px 42px;font-size:14px;color:#fff;outline:none;transition:.3s;font-family:'Inter',sans-serif;box-sizing:border-box}
.input-wrap input::placeholder{color:rgba(255,255,255,.2)}
.input-wrap input:focus{border-color:#6c63ff;background:rgba(108,99,255,.12);box-shadow:0 0 0 4px rgba(108,99,255,.15)}
.eye-btn{position:absolute;right:8px;top:50%;transform:translateY(-50%);width:28px;height:28px;display:flex;align-items:center;justify-content:center;background:none;border:none;cursor:pointer;color:rgba(255,255,255,.35);font-size:14px;padding:0;border-radius:6px}
.eye-btn:hover{color:#fff;background:rgba(255,255,255,.08)}
.terms{display:flex;align-items:flex-start;gap:10px;margin:20px 0}
.terms input{width:16px;height:16px;accent-color:#6c63ff;flex-shrink:0;margin-top:2px;cursor:pointer}
.terms label{font-size:12.5px;color:rgba(255,255,255,.45);line-height:1.5;cursor:pointer}
.terms label a{color:#6c63ff;text-decoration:none}
.btn-reg{width:100%;padding:14px;background:linear-gradient(135deg,#6c63ff,#e040fb);border:none;border-radius:12px;font-size:15px;font-weight:700;color:#fff;cursor:pointer;transition:.3s;font-family:'Inter',sans-serif;position:relative;overflow:hidden;letter-spacing:.3px}
.btn-reg:hover{transform:translateY(-2px);box-shadow:0 10px 30px rgba(108,99,255,.4)}
.btn-reg:active{transform:translateY(0)}
.login-link{text-align:center;font-size:13px;color:rgba(255,255,255,.4);margin-top:20px}
.login-link a{color:#6c63ff;text-decoration:none;font-weight:600}
.badges{display:flex;justify-content:center;gap:18px;margin-top:18px;flex-wrap:wrap}
.badge-item{display:flex;align-items:center;gap:5px;font-size:11px;color:rgba(255,255,255,.25)}
.badge-item i{color:#43e97b;font-size:12px}
</style>
</head>
<body>
<div class="blob b1"></div>
<div class="blob b2"></div>
<div class="blob b3"></div>

<?php
include "auth/config.php";
if (isset($_POST['create'])) {
    $mobile = trim($_POST['mobile']);
    $name = trim($_POST['name']);
    $password = $_POST['password'];

    $checkMobile = mysqli_query($conn, "SELECT id FROM users WHERE mobile='$mobile'");
    if (mysqli_num_rows($checkMobile) > 0) {
        echo '<script>Swal.fire({title:"Mobile Already Exists",text:"Please use a different mobile number.",icon:"error",background:"#14141f",color:"#fff"});</script>';
    } else {
        $pass = password_hash($password, PASSWORD_BCRYPT);
        $key = md5(rand(00000000,99999999));
        $today = date("Y-m-d", strtotime("+3 days"));
        function generateRandomInstanceId($l=16){$c='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';$s='I';for($i=1;$i<$l-6;$i++)$s.=$c[rand(0,strlen($c)-1)];$t=time();$s.=rand(100,900).substr(strval($t),-6);return $s;}
        $instanceId = generateRandomInstanceId();
        $email = trim($_POST['email']);
        $company = $name;
        $register = "INSERT INTO `users`(`name`,`mobile`,`role`,`password`,`email`,`company`,`pin`,`pan`,`aadhaar`,`location`,`user_token`,`expiry`,`instance_id`,`requires_plan`) VALUES ('$name','$mobile','User','$pass','$email','$company','000000','NOPAN000','000000000000','India','$key','$today','$instanceId','Yes')";
        $result = mysqli_query($conn, $register);
        $new_user_id = mysqli_insert_id($conn);
        // NOTE: trial plans are no longer auto-activated for free. The
        // new user has no active subscription (requires_plan='Yes' blocks
        // them from connecting merchants / transacting) until they buy a
        // plan from auth/subscription.php - including the ₹1 trial plan
        // itself, which goes through the same real-payment activation flow
        // as every other plan (see auth/lib/callback.php -> activatePlanForUser).
        if ($result) {
            $siteSettingsRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT register_otp_enabled FROM site_settings LIMIT 1"));
            $registerOtpOn = $siteSettingsRow ? ((int)($siteSettingsRow['register_otp_enabled'] ?? 1) === 1) : true;

            if (!$registerOtpOn) {
                // OTP verification turned off from admin panel - activate the
                // account immediately, no email round-trip needed.
                mysqli_query($conn, "UPDATE users SET email_verified = 'Yes' WHERE id = $new_user_id");
                echo '<script>Swal.fire({title:"Registration Successful! 🎉",text:"Account created! Please login and buy a plan to activate.",icon:"success",confirmButtonText:"Go to Login",background:"#14141f",color:"#fff"}).then(r=>{if(r.isConfirmed)window.location.href="auth/index";});</script>';
            } else {
                $_SESSION['pending_otp_user_id'] = $new_user_id;
                $otpResult = issue_email_otp($conn, $new_user_id, $email, $name, 'register');

                if ($otpResult['ok']) {
                    echo '<script>Swal.fire({title:"Registration Successful! 🎉",text:"Aapke email pe ek verification code bheja gaya hai.",icon:"success",confirmButtonText:"Verify Now",background:"#14141f",color:"#fff",allowOutsideClick:false}).then(()=>{window.location.href="auth/verify_email_otp";});</script>';
                } else {
                    // Account is created either way - don't block signup over an
                    // email hiccup, just let them verify (or resend) from there.
                    echo '<script>Swal.fire({title:"Registered, but email failed", text:"' . addslashes($otpResult['message']) . ' - aap verify page se dobara OTP bhej sakte hain.", icon:"warning", background:"#14141f", color:"#fff"}).then(()=>{window.location.href="auth/verify_email_otp";});</script>';
                }
            }
        } else {
            $dbErr = addslashes(mysqli_error($conn));
            echo '<script>Swal.fire({title:"Registration Failed",text:"'.$dbErr.'",icon:"error",background:"#14141f",color:"#fff"});</script>';
        }
    }
}
?>

<div class="card">
  <div class="logo-wrap">
    <img src="<?php echo $site_settings['logo_url']; ?>" alt="Logo" onerror="this.style.display='none'">
  </div>
  <div class="brand-name">Create Account 🚀</div>
  <div class="brand-sub">Join <?php echo htmlspecialchars($site_settings['brand_name']); ?> — Start accepting payments</div>

  <form method="POST" action="">
    <div class="fg">
      <label>Full Name</label>
      <div class="input-wrap">
        <i class="fas fa-user"></i>
        <input type="text" name="name" placeholder="Your full name" required autofocus>
      </div>
    </div>
    <div class="fg">
      <label>Mobile Number</label>
      <div class="input-wrap">
        <i class="fas fa-mobile-alt"></i>
        <input type="tel" name="mobile" placeholder="10-digit mobile number" inputmode="numeric" pattern="[0-9]*" maxlength="10" oninput="this.value=this.value.replace(/[^0-9]/g,'').slice(0,10)" required>
      </div>
    </div>
    <div class="fg">
      <label>Email Address</label>
      <div class="input-wrap">
        <i class="fas fa-envelope"></i>
        <input type="email" name="email" placeholder="your@email.com" required>
      </div>
    </div>
    <div class="fg">
      <label>Password</label>
      <div class="input-wrap">
        <i class="fas fa-lock"></i>
        <input type="password" name="password" id="regPass" placeholder="Create a strong password" required minlength="6">
        <button type="button" class="eye-btn" onclick="toggleEye('regPass','eyeI')"><i class="fas fa-eye" id="eyeI"></i></button>
      </div>
    </div>
    <div class="fg">
      <label>Confirm Password</label>
      <div class="input-wrap">
        <i class="fas fa-lock"></i>
        <input type="password" name="confirm_password" id="regPassConfirm" placeholder="Re-enter your password" required>
        <button type="button" class="eye-btn" onclick="toggleEye('regPassConfirm','eyeI2')"><i class="fas fa-eye" id="eyeI2"></i></button>
      </div>
      <div id="pwMatchHint" style="font-size:12px;margin-top:6px;min-height:14px"></div>
    </div>
    <div class="terms">
      <input type="checkbox" id="tc" required>
      <label for="tc">I agree to the <a href="#">Terms of Service</a> and <a href="#">Privacy Policy</a></label>
    </div>
    <button type="submit" name="create" class="btn-reg"><i class="fas fa-user-plus" style="margin-right:8px"></i>Create My Account</button>
  </form>

  <p class="login-link">Already have an account? <a href="auth/index">Sign In</a></p>
  <div class="badges">
    <span class="badge-item"><i class="fas fa-shield-alt"></i>SSL Secured</span>
    <span class="badge-item"><i class="fas fa-lock"></i>Encrypted</span>
    <span class="badge-item"><i class="fas fa-check-circle"></i>RBI Compliant</span>
  </div>
</div>
<script>
function toggleEye(inputId, iconId){
  var i=document.getElementById(inputId), e=document.getElementById(iconId);
  i.type = i.type==='password' ? 'text' : 'password';
  e.className = i.type==='password' ? 'fas fa-eye' : 'fas fa-eye-slash';
}
(function(){
  var pw = document.getElementById('regPass');
  var cpw = document.getElementById('regPassConfirm');
  var hint = document.getElementById('pwMatchHint');
  function checkMatch(){
    if (!cpw.value) { hint.textContent = ''; return; }
    if (pw.value === cpw.value) {
      hint.innerHTML = '<i class="fas fa-check-circle" style="color:#43e97b"></i> <span style="color:#43e97b">Passwords match</span>';
    } else {
      hint.innerHTML = '<i class="fas fa-circle-xmark" style="color:#ff6584"></i> <span style="color:#ff6584">Passwords do not match</span>';
    }
  }
  pw.addEventListener('input', checkMatch);
  cpw.addEventListener('input', checkMatch);
  document.querySelector('form').addEventListener('submit', function(e){
    if (pw.value !== cpw.value) {
      e.preventDefault();
      Swal.fire({title:'Passwords do not match', text:'Please make sure both password fields are identical.', icon:'error', background:'#14141f', color:'#fff'});
    }
  });
})();
</script>
</body>
</html>
