<?php

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

ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(1);
ini_set("log_errors", 1);
ini_set("error_log", "php-error.log");

date_default_timezone_set('Asia/Kolkata');

$data = json_decode(trim(file_get_contents("php://input")),true);
/*
$requestParameter['mobile_number'] = $_REQUEST['mobile_number'];
$requestParameter['first_name']   = $_REQUEST['first_name'];
$requestParameter['device_type']  = $_REQUEST['device_type'];
$requestParameter['source'] 	  = $_REQUEST['source'];
print "<pre>";
print_r($_REQUEST);
print "</pre>";
*/

/*$file = fopen("API_logs/API_updateProfile.txt","a");
$today = date("Y-m-d H:i:s");
$parameter = "-------------------".$today."----------------------------"."\n";
foreach($_REQUEST as $key=>$value) {
	$parameter = $parameter."$key=>$value"."\n";
}
$parameter = $parameter."-----------------------------------------------"."\n";
fwrite($file, $parameter);
fclose($file);*/

$validationErr = '';


/*$_REQUEST['refer_id'] = '123123629';
$_REQUEST['user_id'] = '7cb3c901-ffc3-e12b-9d6b-5a3918fb456d';

$data['refer_id'] = $_REQUEST['refer_id'];
$data['user_id'] = $_REQUEST['user_id'];*/

$validationErr = '';
if(!isset($data['refer_id'])){
	$validationErr = "Member ID Invalid!";
}else if(!isset($data['user_id'])){
	$validationErr = "Member ID Invalid!";
}

if($validationErr != '') {

	$result = array();
    $result['success'] = false;
	$result['message'] = $validationErr;
	print $return = json_encode($result);
	exit;

}

$db = new PDO('mysql:host=localhost;dbname=mybooster;', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$refer_id = $data['refer_id'];
$user_id = $data['user_id'];
$result = array();
$data = array();

if(verifyUser($refer_id, $user_id, $db))
{
	
	$result['success'] = true;
	$result['message'] = "Sponsor Member exist!";
	$result['data']['pv_balance'] = getPVBalance($refer_id, $db);

}

else
{
	$result['success'] = false;
	$result['message'] = "Invalid Credentials!";
}


   function verifyUser($refer_id, $user_id, $db)
	{
		try
		{
            $stmt = $db->prepare("select refer_id from my_registration where refer_id='$refer_id' && id='$user_id'");
			$stmt->execute();
			$result = $stmt->fetch(PDO::FETCH_ASSOC);
			$db = null;

			if($result['refer_id'] != NULL)
				return 1;

			else
				return 0;
		}

		catch(PDOException $ex){
		   $result['success'] = false;
		   $result['message'] = "Invalid Credentials!";
		}

		
	}


	function getPVBalance($refer_id, $db)
	{
		try
		{
			$stmt = $db->prepare("select balance from my_pv_balance where refer_id='$refer_id'");
			$stmt->execute();
			$result = $stmt->fetch(PDO::FETCH_ASSOC);
		  	return $result['balance'];
	
		}

		catch(PDOException $ex){
		   $result['success'] = false;
		   $result['message'] = "Invalid Credentials!";
		}
	}


echo json_encode($result);


?> 
