<?php
header("Content-Type: application/json");
require "../config/db.php";

$name = trim($_POST['name']);
$email = trim($_POST['email']);
$city = $_POST['city'];
$state = $_POST['state'];
$mobile = $_POST['mobile'];
$pin = $_POST['pin'];
$gender = $_POST['gender'];
$rank = $_POST['rank'] === "custom" ? $_POST['custom_rank'] : $_POST['rank'];
$company = $_POST['company'];

if (!preg_match("/^\d{10}$/", $mobile)) {
  echo json_encode(["success"=>false,"message"=>"Invalid mobile"]);
  exit;
}

if (!preg_match("/^\d{4}$/", $pin)) {
  echo json_encode(["success"=>false,"message"=>"Invalid PIN"]);
  exit;
}

// Secure PIN

$hashedPin = password_hash($pin, PASSWORD_BCRYPT);

// Check for duplicate mobile
$check_mobile = $conn->query("SELECT id FROM users WHERE mobile = '$mobile'");
if ($check_mobile->num_rows > 0) {
    echo json_encode(["success" => false, "message" => "Mobile number already exists!"]);
    exit;
}
    else 
      
    {
        $sql = "INSERT INTO users (name, email, city, state, mobile, pin, gender, rank, company) 
        VALUES ('$name', '$email', '$city', '$state', '$mobile', '$hashedPin', '$gender', '$rank', '$company')";

        if ($conn->query($sql) === TRUE) {
            $new_user_id = $conn->insert_id;

            if (isset($_POST['upliner_ids']) && is_array($_POST['upliner_ids'])) {
                foreach ($_POST['upliner_ids'] as $u_id) {
                    $u_id = intval($u_id);
                    $conn->query("INSERT INTO user_upliners (user_id, upliner_id) VALUES ('$new_user_id', '$u_id')");
                }
            }

            // Instead of redirecting, send a SUCCESS JSON
            echo json_encode([
                "success" => true, 
                "message" => "User $name registered successfully with " . count($_POST['upliner_ids'] ?? []) . " upliners!"
            ]);
        } else {
                echo json_encode(["success" => false, "message" => "Database error: " . $conn->error]);
            }
    }

$conn->close();
exit; // No more header Location


// $stmt = $conn->prepare("
//   INSERT INTO users
//   (name,email,city,state,mobile,pin,gender,rank,company)
//   VALUES (?,?,?,?,?,?,?,?,?)
// ");

// $stmt->bind_param(
//   "ssssssssi",
//   $name,$email,$city,$state,$mobile,$hashedPin,
//   $gender,$rank,$company
// );

// if ($stmt->execute()) {
//   echo json_encode(["success"=>true,"message"=>"User created successfully"]);
// } else {
//   echo json_encode(["success"=>false,"message"=>"Mobile already exists"]);
// }

// if ($conn->query($sql) === TRUE) {
//         $new_user_id = $conn->insert_id; // Get the ID of the user we just created

//         // 3. Handle the Multiple Upliners
//         if (isset($_POST['upliner_ids']) && is_array($_POST['upliner_ids'])) {
//             foreach ($_POST['upliner_ids'] as $u_id) {
//                 $u_id = intval($u_id);
//                 $link_sql = "INSERT INTO user_upliners (user_id, upliner_id) 
//                              VALUES ('$new_user_id', '$u_id')";
//                 $conn->query($link_sql);
//             }
//         }

//         $_SESSION['msg'] = "User $name registered with " . count($_POST['upliner_ids'] ?? []) . " upliners!";
//         $_SESSION['msg_type'] = "success";
//     } else {
//         $_SESSION['msg'] = "Error: " . $conn->error;
//         $_SESSION['msg_type'] = "error";
//     }
