<?php 
require dirname(dirname(__FILE__)).'/inc/Connection.php';
require dirname(dirname(__FILE__)).'/inc/Demand.php';

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

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

// Generate random 6-digit code
function generate_random($conn)
{
    $six_digit_random_number = mt_rand(100000, 999999);
    $c_refer = $conn->query("SELECT * FROM tbl_user WHERE code=".$six_digit_random_number)->num_rows;
    if($c_refer != 0) {
        return generate_random($conn);
    } else {
        return $six_digit_random_number;
    }
}

// Fetch values safely
$fname      = strip_tags(mysqli_real_escape_string($car, $data['name'] ?? ''));
$email      = strip_tags(mysqli_real_escape_string($car, $data['email'] ?? ''));
$mobile     = strip_tags(mysqli_real_escape_string($car, $data['mobile'] ?? ''));
$ccode      = strip_tags(mysqli_real_escape_string($car, $data['ccode'] ?? ''));
$password   = strip_tags(mysqli_real_escape_string($car, $data['password'] ?? ''));
$refercode  = isset($data['rcode']) && $data['rcode'] !== '' ? (int)$data['rcode'] : NULL;

// Basic validation
if(empty($fname) || empty($email) || empty($mobile) || empty($password) || empty($ccode)) {
    echo json_encode([
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Something Went Wrong!"
    ]);
    exit;
}

// Check if mobile/email already exists
$checkmob = $car->prepare("SELECT id FROM tbl_user WHERE mobile = ?");
$checkmob->bind_param("s", $mobile);
$checkmob->execute();
$checkmob_res = $checkmob->get_result();

$acheckmob = $car->prepare("SELECT id FROM admin WHERE mobile = ?");
$acheckmob->bind_param("s", $mobile);
$acheckmob->execute();
$acheckmob_res = $acheckmob->get_result();

$checkemail = $car->prepare("SELECT id FROM tbl_user WHERE email = ?");
$checkemail->bind_param("s", $email);
$checkemail->execute();
$checkemail_res = $checkemail->get_result();

if($checkmob_res->num_rows != 0 || $acheckmob_res->num_rows != 0) {
    echo json_encode([
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Mobile Number Already Used!"
    ]);
    exit;
} elseif($checkemail_res->num_rows != 0) {
    echo json_encode([
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Email Address Already Used!"
    ]);
    exit;
}

// Start user registration
$h = new Demand($car);
$timestamp = date("Y-m-d H:i:s");
$prentcode = generate_random($car);
$wallet = $car->query("SELECT * FROM tbl_setting")->fetch_assoc();
$fin = $wallet['scredit'] ?? 0;

// If refer code is provided, check if it exists
if(!is_null($refercode)) {
    $c_refer = $car->query("SELECT * FROM tbl_user WHERE code=".$refercode)->num_rows;
    if($c_refer == 0) {
        echo json_encode([
            "ResponseCode" => "401",
            "Result" => "false",
            "ResponseMsg" => "Refer Code Not Found Please Try Again!!"
        ]);
        exit;
    }
}

// Insert user into tbl_user
$field_values = ["name","email","mobile","rdate","password","ccode","wallet","code"];
$data_values  = [$fname,$email,$mobile,$timestamp,$password,$ccode,$fin,$prentcode];

if(!is_null($refercode)) {
    $field_values[] = "refercode";
    $data_values[]  = $refercode;
}

$check = $h->carinsertdata_Api_Id($field_values, $data_values, "tbl_user");

// Insert wallet report
$field_values = ["uid","message","status","amt","tdate"];
$data_values  = [$check,'Sign up Credit Added!!','Credit',$fin,date("Y-m-d")];
$h->carinsertdata_Api($field_values, $data_values, "wallet_report");

// Fetch user data
$stmt = $car->prepare("SELECT * FROM tbl_user WHERE id = ?");
$stmt->bind_param("i", $check);
$stmt->execute();
$c = $stmt->get_result()->fetch_assoc();

// Send response
echo json_encode([
    "UserLogin" => $c,
    "currency" => $wallet['currency'] ?? '₹',
    "ResponseCode" => "200",
    "Result" => "true",
    "ResponseMsg" => "Sign Up Done Successfully!"
]);
