<?php 
session_start();
include "connection.php"; 

// Check if the user is already logged in via session or cookie
if (isset($_SESSION['userid']) || (isset($_COOKIE['userid']) && !empty($_COOKIE['userid']))) {
    // If a valid cookie exists, set the session and redirect to the dashboard
    if (isset($_COOKIE['userid'])) {
        $_SESSION['userid'] = $_COOKIE['userid'];
    }
    header("Location: UserPanel/index.php");
    exit();
}

// Function to validate form inputs
function validateFormData($username, $number, $email, $password, $pin) {
    $errors = [];
    
    // Check if number is exactly 11 digits and unique
    if (!preg_match('/^\d{11}$/', $number)) {
        $errors[] = " মোবাইল নাম্বারটি অবশ্যই ১১ ডিজিটের হতে হবে! ";
    }
    
    // Check for unique mobile number
    $query = "SELECT COUNT(*) FROM student WHERE number = '$number'";
    $result = mysqli_query($GLOBALS['con'], $query);
    $count = mysqli_fetch_array($result)[0];
    
    if ($count > 0) {
        $errors[] = "  মোবাইল নাম্বারটি একবার ব্যবহৃত হয়েছে! ";
    }
    
    return $errors;
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collecting form data
    $username = $_POST["username"];
    $number = $_POST["number"];
    $email = $_POST["email"];
    $password = $_POST["password"];
    $pin = $_POST["pin"];
    $date = date('Y-m-d');

    // Validate form data
    $validationErrors = validateFormData($username, $number, $email, $password, $pin);
    if (!empty($validationErrors)) {
        $_SESSION['error_message'] = implode('<br>', $validationErrors);
        header("Location: user-register.php");
        exit();
    }

    // Fetch the maximum userid
    $userid_query = "SELECT IFNULL(MAX(userid), 0) + 1 AS new_userid FROM student";
    $userid_result = mysqli_query($con, $userid_query);
    $new_userid = mysqli_fetch_assoc($userid_result)['new_userid'];
	
	

    // Insert query
    $sql = "INSERT INTO student (userid, username, number, email, password, pin,refer_id, entry_date) 
            VALUES ('$new_userid', '$username', '$number', '$email', '$password', '$pin',0, '$date')";

    if (mysqli_query($con, $sql)) {
        $_SESSION['success_message'] = $username. " অ্যাকাউন্ট তৈরি সম্পন্ন হয়েছে! এখন লগইন করুন  " ;
        header("Location: login.php");
        exit();
    } else {
        $_SESSION['error_message'] = " দু:খিত! আবার চেষ্টা করুন! : " . mysqli_error($con);
        header("Location: user-register.php");
        exit();
    }

    mysqli_close($con);
}
?>

    <?php include 'header-link.php'; ?>

<main>
    <section>
        <div class="container my-5">
            <div class="row justify-content-center">
                <div class="col-md-6">
                    <div class="card custom-card">
                        <div class="card-body">
                           	<h3 class="card-title text-center d-block text-primary">
								    <img  src="UserPanel/img/emt-w.png" height="90px" width="90px" > <br>
								    Easy Money Transfer</h3>
                            <h6 class="text-center my-4"> অ্যাকাউন্ট  আছে? <a href="login.php"> লগইন করুন! </a></h6>

                            <form action="" method="POST">
                                <div class="mb-3">
                                    <label for="username" class="form-label"> ইউজার নাম </label>
                                    <input type="text" name="username" class="form-control" id="username" placeholder=" ইউজার নাম..." required>
                                </div>

                                <div class="mb-2">
                                    <label for="number" class="form-label"> মোবাইল নং </label>
                                    <input type="text" pattern="^[0-9]{11}$" name="number" class="form-control" id="number"  placeholder=" মোবাইল নং..." required>
									<center>
										<small > সঠিক মোবাইল নাম্বার লিখুন   </small>
									</center>
                                </div>

                                <div class="mb-3">
                                    <label for="email" class="form-label"> ই-মেইল </label>
                                    <input type="email" name="email" class="form-control" id="email" placeholder=" ই-মেইল..." required>
                                </div>

                                <div class="mb-3">
                                    <label for="password" class="form-label"> পাসওয়ার্ড </label>
                                    <input type="password" name="password" class="form-control" minlength="6" id="password" placeholder=" পাসওয়ার্ড..." required>
									<center>
										<small> কমপক্ষে  6  ক্যারেক্টারের  পাসওয়ার্ড প্রদান করুন  </small>
									</center>
                                </div>

                                <div class="mb-3">
                                    <label for="pin" class="form-label"> পিন নং  </label>
                                    <input type="text" pattern="^[0-9]{4}$"  name="pin" class="form-control" id="pin"  placeholder=" পিন নং ..." required>
									<center>
										<small> 4  ডিজিটের  পিন প্রদান করুন  </small>
									</center>
                                </div>
                                
                                <div class="d-grid">
                                <button type="submit" class="btn custom-button w-50 mx-auto"> পরবর্তী </button>
                                </div>
                            </form>

                            <?php if (isset($_SESSION['error_message'])): ?>
                                <div class="alert alert-error mt-3 text-center" role="alert">
                                    <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                                </div>
                            
                            <?php endif; ?>
                            
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</main>
</body>
</html>
