<?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');


//require_once('database.php');
require 'aws/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

if($_REQUEST['dob'] != "") {
	$_REQUEST['dob'] 	= date('Y-m-d', strtotime($_REQUEST['dob']));
}


$file = fopen("API_logs/API_registration.txt","a");
$today = date("Y-m-d H:i:s");
$parameter = "-------------------".$today."----------------------------"."\n";
//$parameter = $parameter."File Name=>".$_FILES['videofile']['name']."\n";
foreach($_REQUEST as $key=>$value) {
	$parameter = $parameter."$key=>$value"."\n";
}
$parameter = $parameter."-----------------------------------------------"."\n";
//print "<br>".$parameter;
fwrite($file, $parameter);
fclose($file);

$_REQUEST['sponsor_id'] = $_REQUEST['sponsor_id'];
$_REQUEST['sponsor_by'] = $_REQUEST['sponsor_by'];
$_REQUEST['right_node'] = (int) $_REQUEST['right_node'];
$_REQUEST['left_node']  = (int) $_REQUEST['left_node'];




if(!isset($_REQUEST['first_name']) || $_REQUEST['first_name'] == '') {
	$validationErr = "Please enter First Name!";
} else if(!isset($_REQUEST['last_name']) || $_REQUEST['last_name'] == '') {
	$validationErr = "Please enter Last Name!";
} else if(!isset($_REQUEST['mobile_number']) || $_REQUEST['mobile_number'] == '') {
	$validationErr = "Please enter Mobile Number!";
} else if(!isset($_REQUEST['email_address']) || $_REQUEST['email_address'] == '') {
	$validationErr = "Please enter Email Address!";
} else if(!isset($_REQUEST['password']) || $_REQUEST['password'] == '') {
	$validationErr = "Please enter password!";
} else if(!isset($_REQUEST['country_code']) || $_REQUEST['country_code'] == '') {
	$validationErr = "Please enter Country Code!";
} else if(!isset($_REQUEST['sponsor_by']) || $_REQUEST['sponsor_by'] == '') {
	$validationErr = "Please enter Sponsor ID!";
} else if($_REQUEST['right_node'] == '' && $_REQUEST['left_node'] == '') {
	$validationErr = "Pleas enter Right or Left Node!";
} else if($_REQUEST['right_node'] == 1 && $_REQUEST['left_node'] == 1) {
	$validationErr = "A user can be only at Left or Right Leg!";
} else if($_REQUEST['right_node'] == 0 && $_REQUEST['left_node'] == 0) {
	$validationErr = "Right and Left node cannot be empty!";
} else if(!isset($_REQUEST['sponsor_id']) || $_REQUEST['sponsor_id'] == '') {
	$validationErr = "Please enter Placement ID!";
} /*else if(!isset($_REQUEST['txtKYC']) || $_REQUEST['txtKYC'] == '') {
	$validationErr = "Please enter KYC info!";
} else if(!isset($_REQUEST['kyc']) || $_REQUEST['kyc'] == '') {
	$validationErr = "Please upload KYC File!";
} else if($_REQUEST['kyc']['size'] >= 5000000) {
	$validationErr = "Please upload file upto 5MB!";
}*/




	function uploadFile($filepath, $filename, $type, $extension)
	{
		$bucketName = 'mybooster';
		$IAM_KEY    = 'AKIAIXFBI2SZQ54SYTSA';
		$IAM_SECRET = '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';

		// Connect to AWS
		try {
			// You may need to change the region. It will say in the URL when the bucket is open
			// and on creation.
			$s3 = S3Client::factory(
				array(
					'credentials' => array(
						'key' => $IAM_KEY,
						'secret' => $IAM_SECRET
					),
					'version' => 'latest',
					'region'  => 'ap-south-1'
				)
			);
		} catch (Exception $e) {
			// We use a die, so if this fails. It stops here. Typically this is a REST call so this would
			// return a json object.
			die("Error: " . $e->getMessage());
		}

				
		// For this, I would generate a unqiue random string for the key name. But you can do whatever.
		$keyName = 'KYC/' . basename($filename);
		$pathInS3 = 'https://s3.ap-south-1.amazonaws.com/' . $bucketName . '/' . $keyName;

		// Add it to S3
		try {
			
			$s3->putObject(
				array(
					'Bucket'=>$bucketName,
					'Key' =>  $keyName,
					'SourceFile' => $filepath,
					'StorageClass' => 'REDUCED_REDUNDANCY',
				    'ContentType' => $type.$extension,
					'ACL' => 'public-read'

				)
			);

		} catch (S3Exception $e) {
			die('Error:' . $e->getMessage());
		} catch (Exception $e) {
			die('Error:' . $e->getMessage());
		}

	}

	

	

if($validationErr != '') {

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

} 

/*
$headers = apache_request_headers();

if($headers['enc_text'] != "") {
	$enc_text = $headers['enc_text'];
} 
*/

require_once('database.php');
require_once('API_main_class.php');

class member_sign_up extends main_class {
    //global $sugar_config;

    public $conn;
	public $db;
	public $pdo;
	
	function __construct() {
		global $sugar_config;

		$host_name = 'localhost';
		$user_name = 'root';
		$password  = 'root';
		$db_name   = 'mybooster';

		$this->pdo = new PDO("mysql:host=$host_name;dbname=$db_name", $user_name, $password);
		// set the PDO error mode to exception
		$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		$this->pdo->beginTransaction();

		$this->db = mysql_connect($host_name, $user_name, $password);
		mysql_select_db($db_name);		

		if(!$this->db) {
			$result = array();
			$result['status'] = '0';
			$result['message'] = "APP temporarily Unavailable!";
			print $return = json_encode($result);
			//exit;
		}

		if(!$this->pdo) {
			$result = array();
			$result['status'] = '0';
			$result['message'] = "APP temporarily Unavailable!";
			print $return = json_encode($result);
			//exit;
		}

   }

 
	public function check_sponsor_id($sponsor_id) {

		$sqlSelect 	= "SELECT id FROM my_registration WHERE refer_id='$sponsor_id'";
		$stmt 		= $this->pdo->prepare($sqlSelect);
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		return $result['id'];
    }



	public function getRefID($newReferID) {

		$sqlSelect 	= "SELECT id FROM my_registration WHERE refer_id='$newReferID'";
		$stmt 		= $this->pdo->prepare($sqlSelect);
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		return $result['id'];

    }

    public function checkUserID($newUserID) {

		$sqlSelect 	= "SELECT id FROM my_registration WHERE id='$newUserID'";
		$stmt 		= $this->pdo->prepare($sqlSelect);
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		return $result['id'];

    }




	public function getMobile($mobile_number){
		
		$sqlSelect 	= "SELECT id FROM my_registration WHERE mobile_number='$mobile_number'";
		$stmt 		= $this->pdo->prepare($sqlSelect);
		$stmt->execute();
		$sqlCnt 	= $stmt->rowCount();
		return $sqlCnt;

    }

	

	public function getKYCInfo($pan_no){
		
		$sqlSelect 	= "SELECT id FROM my_registration WHERE pan_no='$pan_no'";
		$stmt 		= $this->pdo->prepare($sqlSelect);
		$stmt->execute();
		$sqlCnt 	= $stmt->rowCount();
		return $sqlCnt;

    }
  

	public function getID($email_address) {

		$sqlSelect 	= "SELECT id FROM my_registration WHERE email_address='$email_address'";
		$stmt 		= $this->pdo->prepare($sqlSelect);
		$stmt->execute();
		$sqlCnt 	= $stmt->rowCount();
		return $sqlCnt;
		
   }



	public function check_node() {
		
		$sponsorID 	 = $_REQUEST['sponsor_id'];

		$query 		 = "select left_node, right_node from my_registration where deleted = 0 and sponsor_id = '".$sponsorID."'"; 
		$mysqlResult = mysql_query($query);
		$myNumRows	 = mysql_num_rows($mysqlResult);
		
		if($myNumRows >= 2) {
			$checkNodeResult['status']  = 0;
			$checkNodeResult['message'] = 'Already two members are added in the network!';
		} else {
			$mysqlResult = mysql_fetch_assoc($mysqlResult);

			//print "<pre>";
			//print_r($mysqlResult);
			//print "</pre>";

			if($_REQUEST['right_node'] == 1 && $mysqlResult['right_node'] == 1) {
				$checkNodeResult['status']  = 0;
				$checkNodeResult['message'] = 'Right node already occupied in the network!';
			} else if($_REQUEST['left_node'] == 1 && $mysqlResult['left_node'] == 1) {
				$checkNodeResult['status']  = 0;
				$checkNodeResult['message'] = 'Left node already occupied in the network!';
			} else {
				$checkNodeResult['status']  = 1;
				$checkNodeResult['message'] = '';
			}
		}	
			
		return $checkNodeResult;
    }




    public function makeEntry($loginData, $referID, $userID){


		$date = date("Y-m-d H:i:s");
		// Uploaded:
		/*$filepath = $_REQUEST['kyc']['tmp_name'];
		$info= new SplFileInfo($_REQUEST['kyc']['name']);
		$extension = strtolower($info->getExtension());
		$type = "";
		$filename = "";

		if($extension=="pdf")
			$type = "application/";

		else
			$type = "image/";

		$filename = time() . "." . $extension;*/


		try{

			$sql = "INSERT INTO my_registration (id, name, date_entered, date_modified, customer_id, deleted, assigned_user_id, password, country, mobile_number, email_address, city, source, address1, relation_nominee, sponsor_id, sponsor_by, left_node, right_node, last_name, verified, gender, dob, account_holder_name, state, bank_name, swift_code, doc_name, ifsc_code, zip_code, address2, branch_name, nominee_name, refer_id, account_number, pan_no, ip_address, last_login_datetime, country_code, account_type, update_email, power_leg)  values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

			$stmt = $this->pdo->prepare($sql);

			$result =  $stmt->execute(array($userID, $loginData['first_name'], $date, $date, NULL, '0', NULL, $loginData['password'], NULL,  $loginData['mobile_number'],  $loginData['email_address'], NULL, NULL, NULL, NULL, $loginData['sponsor_id'], $loginData['sponsor_by'], $loginData['left_node'], $loginData['right_node'], $loginData['last_name'],  NULL, NULL,  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $referID, NULL, NULL, NULL, $date, $_REQUEST['country_code'], $_REQUEST['account_type'], '0', '0'));

		    $this->pdo->commit();
			//uploadFile($filepath, $filename, $type, $extension);
            return true;
	        
		}



		catch(Exception $ex){
		   $this->pdo->rollBack();
		   return false;
		}

		
    }


	public function get_refer_id() {

		$otp1 	= date('Y') - 2017;
		$otp2 	= date('d');
		$otp3 	= date('m');
		$otp4 	= rand(0, 9);
		$otp5 	= rand(0, 9);
		$otp6 	= rand(0, 9);
		$otp7 	= rand(0, 9);

		$otp 	= $otp1.$otp2.$otp3.$otp4;
		$otp 	.=	$otp5.$otp6.$otp7;

		$newReferID = $otp; 

		$id = $this->getRefID($newReferID);
		if($id == "") {
			return $newReferID;
		} else {
			$this->get_refer_id();	
		}	
    }

	public function get_user_id() {
		
		$user_id = $this->createUserID();
		$id = $this->checkUserID($user_id);
		if($id == "") {
			return $user_id;
		} else {
			$this->get_user_id();	
		}	
    }





	public function get_package_details($refer_id) {

		$sqlPackage 		= "SELECT total_bb_token FROM `my_member_package` WHERE `refer_id` = '".$refer_id."' and payment_status=1";
		$resPackage 		= mysql_query($sqlPackage);
		$rowCnt				= mysql_num_rows($resPackage);

		if($rowCnt == 0) {
			$responsePackage = 0;
		} else {
			$responsePackage = 1;
		}

		return $responsePackage;
	}

	public function findExtremeLeft($referID) {
		$stmt = $this->pdo->prepare("SELECT refer_id, left_node FROM my_registration where sponsor_id=? AND left_node='1'");
		$stmt->execute(array($referID));
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		if(!empty($result))
		{
			if($result['left_node'])
				$this->findExtremeLeft($result['refer_id']);
		} else 	{
				//print "<br>Extreme Left: ".$referID;
				$_REQUEST['sponsor_id'] = $referID;
		}
	}

	public function findExtremeRight($referID) {
		$stmt = $this->pdo->prepare("SELECT refer_id, right_node FROM my_registration where sponsor_id=? AND right_node='1'");
		$stmt->execute(array($referID));
		$result = $stmt->fetch(PDO::FETCH_ASSOC);

		if(!empty($result))
		{
			if($result['right_node'])
				$this->findExtremeRight($result['refer_id']);
				return $result['refer_id'];
		} else {
			////print "<br>Extreme Right:".$referID;
			//return $referID;
			$_REQUEST['sponsor_id'] = $referID;	
		}
	}

	public function find_upper_hierarchy($referID) {

		$sqlSelect 	= "SELECT sponsor_id, left_node, right_node FROM my_registration where refer_id='$referID'";
		$stmt 		= $this->pdo->prepare($sqlSelect);
		$stmt->execute();
		$result 	= $stmt->fetch(PDO::FETCH_ASSOC);
		if(!empty($result))
		{
			$varChar = $result['sponsor_id'];
			if($result['sponsor_id'] != "" && $result['sponsor_id'] != 0) {
				$_REQUEST['uptreelist'][] = $varChar;
			}
			$this->find_upper_hierarchy($result['sponsor_id']);
		}
	}

	public function get_sponsor_by_mobile_no($sponsor_by) {
		
		$sqlSelect 	= "SELECT country_code, mobile_number FROM my_registration WHERE refer_id='$sponsor_by'";
		$stmt 		= $this->pdo->prepare($sqlSelect);
		$stmt->execute();
		$result 	= $stmt->fetch(PDO::FETCH_ASSOC);
		return "+" . $result['country_code'] . $result['mobile_number'];

	}
}
 




$conn 		= new member_sign_up();

if($_REQUEST['account_type'] == 1)
{
	$rowCount	= $conn->getKYCInfo($_REQUEST['txtKYC']);

	if($rowCount>=4) {
		$result['status'] = '0';
		$result['message'] = 'Maximum limit to use same pan card has been exceeded, please use another pan card for KYC!';
		print $result = json_encode($result);
		exit;
	}

}

if(!($_REQUEST['sponsor_id'] == $_REQUEST['sponsor_by']) ) {

	$conn->find_upper_hierarchy($_REQUEST['sponsor_id']);

	if(!in_array( $_REQUEST['sponsor_by'], $_REQUEST['uptreelist'] )) {
		$result['status'] = '0';
		$result['message'] = 'Placement ID and Sponsor ID does not match in our Database!';
		print $result = json_encode($result);	
		exit;
	}
}


$result 	= array();


if($_REQUEST['sponsor_id'] == $_REQUEST['sponsor_by'] ) {
	if( $_REQUEST['left_node'] == 1 ) {
		$conn->findExtremeLeft( $_REQUEST['sponsor_by'] );			
	} else if( $_REQUEST['right_node'] == 1 ) {
		$conn->findExtremeRight( $_REQUEST['sponsor_by'] );
	}	
}

//print "<br>sponsor_id: ".$_REQUEST['sponsor_id'];
//exit;

$getSponsorID = $conn->check_sponsor_id($_REQUEST['sponsor_id']);

if($_REQUEST['sponsor_id'] != "admin") {
	if($getSponsorID == "") {
	
		$result['status'] = '0';
		$result['message'] = 'Sponsor ID does not match in our Database!';

		print $result = json_encode($result);	
		exit;
	}
}

//$registrationID = $conn->getID($_REQUEST['email_address'], $moduleName);

//if($registrationID == "") {

	$checkNodeResult = $conn->check_node();
	if($checkNodeResult['status'] == 0) {
		$result['status'] = '0';
		$result['message'] = $checkNodeResult['message'];
	} else {	
		$referID	= $conn->get_refer_id();
		$user_id	= $conn->get_user_id();

		$responseID	= $conn->makeEntry($_REQUEST, $referID, $user_id);
		
		if($responseID != "") {

			if($_REQUEST['page_type'] == 1) {
	          $result['page_type'] = 1;
            }

			$result['status'] 	= '1';
			$result['message'] 	= 'Member has been registered successfully!';
			$result['refer_id'] = $referID;

			/*$mobileNumber 		= "+" . $_REQUEST['country_code'] . $_REQUEST['mobile_number'];
			$messageText 		= "Congratulations on signing up with MyBooster! Your User ID is ".$referID.". LOG IN at \n�www.mybooster.biz�\n to be a part of it!";
			$conn->sendOTP_special_Twilio($mobileNumber, $messageText);
			$conn->send_welcome_mail($_REQUEST['first_name'] . " " . $_REQUEST['last_name'], $referID,  $_REQUEST['email_address']);


			$sponsorByMobileNo 	= $conn->get_sponsor_by_mobile_no( $_REQUEST['sponsor_by'] );
	
			$memberName 		= $_REQUEST['first_name']." ".$_REQUEST['last_name'];	
			$messageText 		= "Congratulations! New member added to your network successfully,�User ID: ".$referID.". Name: ".$memberName.". Keep up the good work! For more info visit�www.mybooster.biz";
			$conn->sendOTP_special_Twilio($sponsorByMobileNo, $messageText);*/
			

		} else {
			$result['status'] = '0';
			$result['message'] = 'Currently we are unable to register the member. Please try after some time!';
		}

		
	} 
/*
} else {
	$result['status'] = '0';
	$result['message'] = 'This email id is already registered!';
}
*/
echo $result = json_encode($result);

?> 
