<?php
include "control/activity.php";
$dd = new activity();

$userEmail = $_REQUEST['userEmail'];
$mobile = $_REQUEST['mobile'];
$pass = $_REQUEST['pass'];
$code = $_REQUEST['code'];
$secret_key = $_REQUEST['secret_key'];

if(empty($userEmail) || empty($mobile) || empty($pass) || empty($code) || empty($secret_key)) {
    echo json_encode(array("status" => "failed", "remark" => "All fields are required"));
    exit();
}
if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(array("status" => "failed", "remark" => "Invalid email format"));
    exit();
}

if(!preg_match('/^[0-9]{10}$/', $mobile)) {
    echo json_encode(array("status" => "failed", "remark" => "Invalid mobile number format"));
    exit();
}

$date = date("h:i d/m/Y");
$bytes = openssl_random_pseudo_bytes(8);
$refral = bin2hex($bytes);
$bytes = openssl_random_pseudo_bytes(6);
$memId = "MEMBER".bin2hex($bytes).mt_rand(11, 99);

$table = "userdetails";
$condition = "WHERE mobile = '$mobile' OR email = '$userEmail'";
$check = $dd->check($table, $condition);

if($check["status"] === "success") {
    echo json_encode(array("status" => "success", "remark" => "Already registered"));
    exit();
}

$value = "(`memId`, `mobile`, `email`, `password`, `join_date`, `my_refral_id`, `refral_from`, `level_1`, `level_2`, `level_3`, `level_4`, `level_5`, `level_6`, `level_7`, `level_8`, `level_9`, `level_10`, `secret_key`)
          SELECT '$memId', '$mobile', '$userEmail', '$pass', '$date', '$refral', '$code', '$code', level_1, level_2, level_3, level_4, level_5, level_6, level_7, level_8, level_9, '$secret_key' 
          FROM userdetails WHERE my_refral_id='$code'";
$result = $dd->insertData($table, $value);

if($result) {
    $table = "userdetails";
    $value = "wallet=wallet+10, withdraw_balance=withdraw_balance+0, refAmount=refAmount+10";
    $condition = "my_refral_id='$code'";
    $result = $dd->updateData($table, $value, $condition);
    
    if($result) {
        $date = date("h:i d/m/Y");
        $ref = mt_rand(1111111111, 9999999999);
        $table = "funds_request";
        $value = "(`userKey_id`, `request_date`, `request_type`, `amount`, `refrence_number`, `funds_status`, `approved_date`, `avl_balance`, `remark`) 
                  SELECT userKey, '$date', 'INR', '10', '$ref', 'success', '$date', wallet, 'Refral Incentive' 
                  FROM userdetails WHERE my_refral_id='$code'";
        $result = $dd->insertData($table, $value);
        
        if($result) {
            echo json_encode(array("status" => "success", "remark" => "Registration successful"));
            exit();
        }
    }
}

echo json_encode(array("status" => "failed", "remark" => "Registration failed"));
?>
