<?php 
require dirname( dirname(__FILE__) ).'/inc/config.php';
require dirname( dirname(__FILE__) ).'/inc/FunctionQuery.php';
require dirname( dirname(__FILE__) ).'/inc/keyvaliation.php';

header('Content-Type: application/json');

$data = json_decode(file_get_contents('php://input'), true);

function generate_random()
{
    require dirname( dirname(__FILE__) ).'/inc/config.php';
    $six_digit_random_number = mt_rand(100000, 999999);
    $c_refer = $service->query("SELECT id FROM tbl_user WHERE code = '$six_digit_random_number'")->num_rows;
    if($c_refer != 0)
    {
        // 🔧 FIX: return recursive call result
        return generate_random();
    }
    else 
    {
        return $six_digit_random_number;
    }
}

if(empty($data['name']) || empty($data['mobile']) || empty($data['password']) || empty($data['ccode']) || empty($data['email']))
{
    $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}
else
{
    $name = mysqli_real_escape_string($service, strip_tags($data['name']));
    $email = mysqli_real_escape_string($service, strip_tags($data['email']));
    $mobile = mysqli_real_escape_string($service, strip_tags($data['mobile']));
    $ccode = mysqli_real_escape_string($service, strip_tags($data['ccode']));
    $password = mysqli_real_escape_string($service, strip_tags($data['password']));
    $refercode = isset($data['refercode']) ? mysqli_real_escape_string($service, strip_tags($data['refercode'])) : '';

    // 🔧 FIX: quote numbers properly
    $checkmob = $service->query("SELECT * FROM tbl_user WHERE mobile = '$mobile'");
    $checkemail = $service->query("SELECT * FROM tbl_user WHERE email = '$email'");

    if($checkmob->num_rows != 0)
    {
        $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Mobile Number Already Used!");
    }
    else if($checkemail->num_rows != 0)
    {
        $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Email Address Already Used!");
    }
    else
    {
        $timestamp = date("Y-m-d H:i:s");
        $prentcode = generate_random();

        $h = new FunctionQuery($service);

        if($refercode != '')
        {
            $c_refer = $service->query("SELECT * FROM tbl_user WHERE code = '$refercode'")->num_rows;
            if($c_refer != 0)
            {
                $wallet = $service->query("SELECT scredit FROM tbl_setting")->fetch_assoc();
                $fin = $wallet['scredit'];

                $table = "tbl_user";
                $field_values = array("name","email","mobile","rdate","password","ccode","refercode","wallet","code");
                $data_values = array("$name","$email","$mobile","$timestamp","$password","$ccode","$refercode","$fin","$prentcode");
                
                // 🔧 FIX: ensure $check gets new ID
                $check = $h->serviceinsertdata_Api_Id($field_values, $data_values, $table);
                
                // add wallet record
                $table = "wallet_report";
                $field_values = array("uid","message","status","amt","tdate");
                $data_values = array("$check","Sign up Credit Added!!","Credit","$fin","$timestamp");
                $h->serviceinsertdata_Api($field_values, $data_values, $table);
                
                // 🔧 FIX: fetch latest inserted user correctly
                $c = $service->query("SELECT * FROM tbl_user WHERE id = '$check'")->fetch_assoc();
                $returnArr = array("UserLogin"=>$c,"ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Sign Up Done Successfully!");
            }
            else 
            {
                $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Refer Code Not Found Please Try Again!!");
            }
        }
        else 
        {
            $table = "tbl_user";
            $field_values = array("name","email","mobile","rdate","password","ccode","code");
            $data_values = array("$name","$email","$mobile","$timestamp","$password","$ccode","$prentcode");
            
            $check = $h->serviceinsertdata_Api_Id($field_values, $data_values, $table);
            $c = $service->query("SELECT * FROM tbl_user WHERE id = '$check'")->fetch_assoc();
            
            $returnArr = array("UserLogin"=>$c,"ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Sign Up Done Successfully!");
        }
    }
}

echo json_encode($returnArr);
?>
