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


/*if(($_SERVER['REMOTE_ADDR'] != '18.218.78.117') && ($_SERVER['REMOTE_ADDR'] != '18.221.9.214') && ($_SERVER['REMOTE_ADDR'] != '18.219.221.52'))  {
	$result['status'] 			= '2';
	$result['message'] 			= 'Authorisation Failed!';
	print $result = json_encode($result);
	exit;	
}*/

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

$validationErr = "";
$result = array();


if(!isset($_REQUEST['refer_id']) || $_REQUEST['refer_id']  == '') {
	$validationErr = "Please enter the the Member ID!";
} 

else if(!isset($_REQUEST['user_id']) || $_REQUEST['user_id']  == '') {
	$validationErr = "Please enter the User ID!";
} 

else
{
	$refer_id = $_REQUEST['refer_id'];
	$user_id= $_REQUEST['user_id'];

	if(verifyMemberID($refer_id, $user_id))
	{
		$data = getCouponCode($refer_id);
		if($data == null)
		{
			$result['success'] = true;
			$result['message'] = "No Data found";
			$result['data'] = 0;
		}


		else
		{
			$result['success'] = true;
			$result['message'] = "No Data found";
			$result['data'] = $data;
		}

	}

	else
	{
		$result['success'] = false;
		$result['message']="Invalid Member ID!";

	}

}

if($validationErr != '') {

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

} 


	function verifyMemberID($refer_id, $user_id)
	{
		$conn = new Database;
		$db = $conn->getConnection();
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    	$stmt = $db->prepare("select refer_id from my_registration where refer_id='$refer_id' and id='$user_id'");
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		$db = null;

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

		else
			return 0;
		
	}


	function getCouponCode($refer_id)
	{
		$conn = new Database;
		$db = $conn->getConnection();
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		$stmt = $db->prepare("select * from my_voucher where issued_by='$refer_id' order by created_date ASC");
		$stmt->execute();
		$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

		$db = null;
		return $result;
	}

	

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


?>