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

$mobile = $_POST['mobile'] ?? '';
$password = $_POST['password'] ?? '';
$rcode = $_POST['rcode'] ?? '';
$action = $_POST['action'] ?? '';
$acceptTC = isset($_POST['acceptTC']) ? $_POST['acceptTC'] : 0;

if ($action == "register") {
    $sql4 = "SELECT mobile FROM tbl_user WHERE mobile='$mobile'";
    $select5 = mysqli_query($con, $sql4) or die(mysqli_error($con));

    if (mysqli_num_rows($select5) == 0) {
        if (!empty($rcode)) {
            $chkrcode = mysqli_query($con, "SELECT * FROM tbl_user WHERE owncode='$rcode'");
            if (mysqli_num_rows($chkrcode)) {
                $codeRow1 = mysqli_fetch_array($chkrcode);
                $r_id = $codeRow1['id'];

                $sql = mysqli_query($con, "INSERT INTO tbl_user (mobile, password, show_password, code, owncode, privacy, status) 
                    VALUES ('$mobile', '".md5($password)."', '$password', '$rcode', '', '$acceptTC', '1')");
                $userid = mysqli_insert_id($con);
                $refcode = $userid . refcode();

                mysqli_query($con, "UPDATE tbl_user SET owncode = '$refcode' WHERE id = '$userid'");
                mysqli_query($con, "INSERT INTO tbl_wallet(userid, amount, envelopestatus) VALUES ('$userid', '0', '0')");
                mysqli_query($con, "INSERT INTO tbl_bonus(userid, amount, level1, level2) VALUES ('$userid', '0', '0', '0')");
                mysqli_query($con, "INSERT INTO tbl_interest(userid, amount) VALUES ('$userid', '0')");

                echo "<script>alert('Received Successfully'); window.location='login';</script>";
            } else {
                echo "<script>alert('Referral Code Not Found'); window.location='signup';</script>";
            }
        } else {
            $sql = mysqli_query($con, "INSERT INTO tbl_user (mobile, password, show_password, owncode, privacy, status) 
                VALUES ('$mobile', '".md5($password)."', '$password', '', '$acceptTC', '1')");
            $userid = mysqli_insert_id($con);
            $refcode = $userid . refcode();

            mysqli_query($con, "UPDATE tbl_user SET owncode = '$refcode' WHERE id = '$userid'");
            mysqli_query($con, "INSERT INTO tbl_wallet(userid, amount, envelopestatus) VALUES ('$userid', '0', '0')");
            mysqli_query($con, "INSERT INTO tbl_bonus(userid, amount, level1, level2) VALUES ('$userid', '0', '0', '0')");
            mysqli_query($con, "INSERT INTO tbl_interest(userid, amount) VALUES ('$userid', '0')");

            echo "<script>alert('Received Successfully'); window.location='login';</script>";
        }
    } else {
        echo "<script>alert('Applicant already applied'); window.location='signup';</script>";
    }
} else {
    echo "Invalid Action";
}
?>
