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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    exit;
}

// Collect form data safely
$email      = mysqli_real_escape_string($con, $_POST['email']);
$username   = mysqli_real_escape_string($con, $_POST['username']);
$phone      = mysqli_real_escape_string($con, $_POST['phone']);
$password   = $_POST['password'];
$cpassword  = $_POST['con_password'];
$state      = mysqli_real_escape_string($con, $_POST['state']);
$country    = mysqli_real_escape_string($con, $_POST['country']);
$referral   = mysqli_real_escape_string($con, $_POST['referral'] ?? 'System');
$date       = date('Y-m-d');

if (strlen($password) < 6) {
    echo '<div class="alert alert-danger text-center">Password must be at least 6 characters</div>';
    exit;
}

if ($password !== $cpassword) {
    echo '<div class="alert alert-danger text-center">Confirm Password mismatched</div>';
    exit;
}

$hashedPassword = $password;

/* ðŸ”Ž Check username */
$checkUser = mysqli_query($con, "SELECT user_id FROM users WHERE user_name = '$username'");
if (mysqli_num_rows($checkUser) > 0) {
    echo '<div class="alert alert-danger text-center">Username already exists</div>';
    exit;
}

$checkEmail = mysqli_query($con, "SELECT user_id FROM users WHERE user_email = '$email'");
if (mysqli_num_rows($checkEmail) > 0) {
    echo '<div class="alert alert-danger text-center">Email already exists</div>';
    exit;
}

$query = mysqli_query($con, "
    INSERT INTO users
    (user_email, user_name, user_password, phone, referral, date, state, country)
    VALUES
    ('$email', '$username', '$hashedPassword', '$phone', '$referral', '$date', '$state', '$country')
");

if (!$query) {
    echo '<div class="alert alert-danger text-center">Registration failed</div>';
    exit;
}

/* âœ… Success */
echo '<div class="alert alert-success text-center">Account created successfully!</div>';
echo '<script>
    setTimeout(() => window.location.href = "index.php", 1200);
</script>';
