<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Max-Age: 86400');
header('Access-Control-Allow-Credentials: false');

header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit(0);
}

header('Content-Type: application/json; charset=utf-8');

include "../../conn.php";
include "../../functions2.php";

date_default_timezone_set('Asia/Kolkata');
$shnunc = date("Y-m-d H:i:s");
$res = [
    'code' => 11,
    'msg' => 'Method not allowed',
    'msgCode' => 12,
    'serviceNowTime' => $shnunc,
];

// Cloudflare IP handling
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
    $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
}

// Input data handle karein
$shonubody = file_get_contents("php://input");

// JSON decode mein error handling
$shonupost = null;
if (!empty($shonubody)) {
    $shonupost = json_decode($shonubody, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        $res['code'] = 400;
        $res['msg'] = 'Invalid JSON data';
        $res['msgCode'] = 400;
        http_response_code(400);
        echo json_encode($res);
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] != 'GET') {
    if ($shonupost && 
        isset($shonupost['domainurl']) &&
        isset($shonupost['invitecode']) &&
        isset($shonupost['language']) &&
        isset($shonupost['phonetype']) &&
        isset($shonupost['pwd']) &&
        isset($shonupost['random']) &&
        isset($shonupost['registerType']) &&
        isset($shonupost['signature']) &&
        isset($shonupost['timestamp']) &&
        isset($shonupost['username']) &&
        isset($shonupost['captchaId']) &&
        isset($shonupost['track'])
    ) {
        $domainurl = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['domainurl']));
        $invitecode = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['invitecode']));
        $language = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['language']));
        $phonetype = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['phonetype']));
        $pwd = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['pwd']));
        $random = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['random']));
        $registerType = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['registerType']));
        $username = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['username']));
        $signature = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['signature']));
        $captchaId = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['captchaId']));
        $trackData = $shonupost['track'];
        $shonustr = '{"domainurl":"'.$domainurl.'","invitecode":"'.$invitecode.'","language":'.$language.',"phonetype":'.$phonetype.',"pwd":"'.$pwd.'","random":"'.$random.'","registerType":"'.$registerType.'","username":"'.$username.'"}';
        $shonusign = strtoupper(md5($shonustr));

        $captchaQuery = "SELECT correctPositionx FROM captcha_data WHERE captchaId='$captchaId'";
        $captchaResult = $conn->query($captchaQuery);
        if ($captchaResult && mysqli_num_rows($captchaResult) == 1) {
            $captchaRow = mysqli_fetch_assoc($captchaResult);
            $correctPositionx = $captchaRow['correctPositionx'];
            $userTracks = $trackData['tracks'];
            $lastTrack = end($userTracks);
            $userPositionx = $lastTrack['x'];
            if (abs($userPositionx - $correctPositionx) > 5) {
                $res['data'] = null;
                $res['code'] = 1;
                $res['msg'] = 'Verification failed, please try again';
                $res['msgCode'] = 31;
                http_response_code(200);
                echo json_encode($res);
                exit;
            }
        } else {
            $res['data'] = null;
            $res['code'] = 1;
            $res['msg'] = 'Captcha data not found';
            $res['msgCode'] = 32;
            http_response_code(200);
            echo json_encode($res);
            exit;
        }

        if ($shonusign != $signature) {
            if (substr($username, 0, 2) != "91") {
                    $username = "91" . $username;
                }
            $samasye = "SELECT id FROM shonu_subjects WHERE owncode = '".$invitecode."'";
            $samasyephalitansa = $conn->query($samasye);
            $samasyephalitansa_dhadi = mysqli_num_rows($samasyephalitansa);
            if ($samasyephalitansa_dhadi == 1) {
                $samasye = "SELECT id FROM shonu_subjects WHERE mobile = $username";
                $samasyephalitansa = $conn->query($samasye);
                $samasyephalitansa_dhadi = mysqli_num_rows($samasyephalitansa);
                if ($samasyephalitansa_dhadi == 0) {
                    $samasye = "SELECT code FROM shonu_subjects WHERE owncode = '".$invitecode."'";
                    $samasyephalitansa = $conn->query($samasye);
                    $samasyephalitansa_dhadi = mysqli_num_rows($samasyephalitansa);
                    if ($samasyephalitansa_dhadi == 1) {
                        $samasyephalitansa_sreni = mysqli_fetch_array($samasyephalitansa);
                        $code1 = $samasyephalitansa_sreni['code'];
                        $samasye = "SELECT code FROM shonu_subjects WHERE owncode = '".$code1."'";
                        $samasyephalitansa = $conn->query($samasye);
                        $samasyephalitansa_dhadi = mysqli_num_rows($samasyephalitansa);
                        if ($samasyephalitansa_dhadi == 1) {
                            $samasyephalitansa_sreni = mysqli_fetch_array($samasyephalitansa);
                            $code2 = $samasyephalitansa_sreni['code'];
                            $samasye = "SELECT code FROM shonu_subjects WHERE owncode = '".$code2."'";
                            $samasyephalitansa = $conn->query($samasye);
                            $samasyephalitansa_dhadi = mysqli_num_rows($samasyephalitansa);
                            if ($samasyephalitansa_dhadi == 1) {
                                $samasyephalitansa_sreni = mysqli_fetch_array($samasyephalitansa);
                                $code3 = $samasyephalitansa_sreni['code'];
                                $samasye = "SELECT code FROM shonu_subjects WHERE owncode = '".$code3."'";
                                $samasyephalitansa = $conn->query($samasye);
                                $samasyephalitansa_dhadi = mysqli_num_rows($samasyephalitansa);
                                if ($samasyephalitansa_dhadi == 1) {
                                    $samasyephalitansa_sreni = mysqli_fetch_array($samasyephalitansa);
                                    $code4 = $samasyephalitansa_sreni['code'];
                                    $samasye = "SELECT code FROM shonu_subjects WHERE owncode = '".$code4."'";
                                    $samasyephalitansa = $conn->query($samasye);
                                    $samasyephalitansa_dhadi = mysqli_num_rows($samasyephalitansa);
                                    if ($samasyephalitansa_dhadi == 1) {
                                        $samasyephalitansa_sreni = mysqli_fetch_array($samasyephalitansa);
                                        $code5 = $samasyephalitansa_sreni['code'];
                                    } else {
                                        $code5 = null;
                                    }
                                } else {
                                    $code4 = null;
                                    $code5 = null;
                                }
                            } else {
                                $code3 = null;
                                $code4 = null;
                                $code5 = null;
                            }
                        } else {
                            $code2 = null;
                            $code3 = null;
                            $code4 = null;
                            $code5 = null;
                        }
                    } else {
                        $code1 = null;
                        $code2 = null;
                        $code3 = null;
                        $code4 = null;
                        $code5 = null;
                    }
                    
                    function generateRandomNumber() {
                        return mt_rand(100000000000, 999999999999);
                    }
                    function checkNumberExists($conn, $number) {
                        try {
                            mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
                            $stmt = $conn->prepare("SELECT COUNT(*) FROM shonu_subjects WHERE owncode = ?");
                            $stmt->bind_param("s", $number);
                            $stmt->execute();
                            $stmt->bind_result($count);
                            $stmt->fetch();
                            $stmt->close();
                            return $count > 0;
                        } catch (mysqli_sql_exception $e) {
                        }
                        return false;
                    }
                    
                    do {
                        $codethiefstfu = str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
                    } while (checkNumberExists($conn, $codethiefstfu));
                    $query = "SELECT id FROM shonu_subjects ORDER BY id DESC LIMIT 1";
                    $result = mysqli_query($conn, $query);
                    $row = mysqli_fetch_assoc($result);
                    $nextId = isset($row['id']) ? $row['id'] + 1 : 1;
                    $nextId = str_pad($nextId, 6, '0', STR_PAD_LEFT);
                    $owncode = $codethiefstfu . $nextId;
                    
                    $shnunc = date("Y-m-d H:i:s");
                    $ipaddress = '';
                    if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
                        $ipaddress = $_SERVER['HTTP_CF_CONNECTING_IP'];
                    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
                    } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
                        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
                    } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
                        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
                    } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
                        $ipaddress = $_SERVER['HTTP_FORWARDED'];
                    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                        $ipaddress = $_SERVER['REMOTE_ADDR'];
                    } else {
                        $ipaddress = 'UNKNOWN';
                    }
                    $user_agent = $_SERVER['HTTP_USER_AGENT'];
                    
                    function generateUniqueString($length = 8) {
                        $letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                        $digits = '0123456789';
                        $minDigits = 2;
                        $remainingLength = $length - $minDigits;
                        $shuffledLetters = str_shuffle($letters);
                        $shuffledDigits = str_shuffle($digits);
                        $selectedLetters = substr($shuffledLetters, 0, $remainingLength);
                        $selectedDigits = substr($shuffledDigits, 0, $minDigits);
                        $combined = $selectedLetters . $selectedDigits;
                        return 'Member' . str_shuffle($combined);
                    }
                    $codechorkamukala = generateUniqueString();
                    $password = md5($pwd);
                    
                    $tathya = mysqli_query($conn, "INSERT INTO `shonu_subjects` (`mobile`,`email`,`password`,`code`,`code1`,`code2`,`code3`,`code4`,`code5`,`owncode`,`privacy`,`status`,`createdate`,`ip`,`ishonup`,`pwd`,`shonullgnt`,`tnegaresunohs`,`codechorkamukala`) VALUES ('".$username."','','".$password."','".$invitecode."','".$code1."','".$code2."','".$code3."','".$code4."','".$code5."','".$owncode."','on','1','".$shnunc."','".$ipaddress."','".$ipaddress."','".$pwd."','".$shnunc."','".$user_agent."','".$codechorkamukala."')");
                    $last_id = $conn->insert_id;
                    
                    $status = 1;
                    $expiresIn = time() + 86400;
                    $shnutkn_head = ['alg' => 'HS256', 'typ' => 'JWT'];
                    $shnutkn_load = [
                        'id' => $last_id,
                        'mobile' => $username,
                        'status' => $status,
                        'expire' => $expiresIn,
                        'ishonup' => $ipaddress,
                        'codechorkamukala' => $codechorkamukala
                    ];
                    
                    // Fetch register_bonus value from web_setting table
                    $minRechargeQuery = "SELECT register_bonus FROM web_setting LIMIT 1";
                    $minRechargeResult = $conn->query($minRechargeQuery);

                    if ($minRechargeResult && $minRechargeResult->num_rows > 0) { 
                        $row = $minRechargeResult->fetch_assoc(); 
                        $amount = $row['register_bonus']; 
                    } else { 
                        $amount = 0; // Default value if no data found 
                    }
                    
                    $akshinak = generate_jwt($shnutkn_head, $shnutkn_load);
                    
                    $pwderrsql = "UPDATE shonu_subjects SET akshinak='".$akshinak."' WHERE id='$last_id'";
                    $conn->query($pwderrsql);
                    
                    $tathya = mysqli_query($conn, "INSERT INTO `shonu_kaichila` (`balakedara`,`motta`,`bonus`,`dinankavannuracisi`) VALUES ('".$last_id."','".$amount."','".$amount."','".$shnunc."')");
                    
                    $res['data']['tokenHeader'] = 'Bearer ';
                    $res['data']['token'] = $akshinak;
                    $res['code'] = 0;
                    $res['msg'] = 'Succeed';
                    $res['msgCode'] = 0;
                    http_response_code(200);
                    echo json_encode($res);
                } else {
                    $res['code'] = 1;
                    $res['msg'] = 'Phone number have been registered';
                    $res['msgCode'] = 111;
                    http_response_code(200);
                    echo json_encode($res);
                }
            } else {
                $res['code'] = 8;
                $res['msg'] = 'Invitor Not Existed';
                $res['msgCode'] = 110;
                http_response_code(200);
                echo json_encode($res);
            }
        }
    } else {
        $res['code'] = 400;
        $res['msg'] = 'Missing required parameters';
        $res['msgCode'] = 400;
        http_response_code(400);
        echo json_encode($res);
    }
} else {
    http_response_code(405);
    echo json_encode($res);
}
?>