<?php

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

/*
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
*/

date_default_timezone_set('Asia/Kolkata');

$file = fopen("../API_logs/API_forgot_password.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);


$validationErr = "";
$_REQUEST['refer_id'] 	 = (int) $_REQUEST['refer_id'];

if(!isset($_REQUEST['refer_id']) || $_REQUEST['refer_id'] == '') {
	$validationErr = "Please enter Member ID!";
} else if(!isset($_REQUEST['email_address']) || $_REQUEST['email_address'] == '') {
	$validationErr = "Please enter email address!";
} else if($_REQUEST['section'] != 1) {
	$validationErr = "Invalid section entered!";
}

if($validationErr != '') {

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

} 

/// OTP Verify




/// OTP Verify Code End
require_once('API_main_class.php');

class member_sign_up extends main_class {

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

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

		$pdoconn = new PDO("mysql:host=$host_name;dbname=$db_name", $user_name, $password);

		$pdoconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		$pdoconn->beginTransaction();
		
		if(!$pdoconn) {
			$result = array();
			$result['status'] = '0';
			$result['message'] = "Service temporarily Unavailable!";
			print $return = json_encode($result);
			exit;
		}

		$this->pdo = $pdoconn;
    }

	public function validate_login() {

		$refer_id 		= $_REQUEST['refer_id'];
    	$emailAddress 	= $_REQUEST['email_address'];

		$sqlSelect 		= "select id, name, last_name from my_registration where refer_id= '$refer_id' and email_address='$emailAddress'";
		$stmt 			= $this->pdo->prepare($sqlSelect);
		$stmt->execute();
		$rowSelect 		= (array) $stmt->fetch (PDO::FETCH_OBJ);
		//print_r($rowSelect);exit;
		return $rowSelect;
    }


	public function getMobileNumber() {

		$refer_id 		= $_REQUEST['refer_id'];
    	$emailAddress 	= $_REQUEST['email_address'];

		$sqlSelect 		= "select country_code, mobile_number from my_registration where refer_id= '$refer_id' and email_address='$emailAddress'";
		$stmt 			= $this->pdo->prepare($sqlSelect);
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);

		//print_r($rowSelect);exit;
		return $result;
    }

	public function validate_otp() {

		$refer_id  	= $_REQUEST['refer_id'];
		$section   	= $_REQUEST['section'];
		$otp		= $_REQUEST['otp'];

		$dataString = "";
		$dataString	= $dataString."?section=".$section;
		$dataString	= $dataString."&refer_id=".$refer_id;
		$dataString	= $dataString."&otp=".$otp;

		//$url 		= "http://localhost/marvel/API/API_verify_otp.php";
		$url 		= "http://localhost/MyBooster/API/API_verify_otp.php";
		$url 		= $url.$dataString;

		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_POST, 1);
		//curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);

		$outputArr = (array) json_decode($output);

		if( $outputArr['status'] != 1 ) {
			print $output;
			exit;
		}
	}
}
 
$conn 	= new member_sign_up();
try 
{

	$conn->validate_otp();

	$transferTo 	= $conn->validate_login();

	if( isset($transferTo['id']) && $transferTo['id'] != "") {

		$name  =$transferTo['name'].' '.$transferTo['last_name'];
		$transferToID = $transferTo['id'];

		$otp1 			= rand(1, 9);
		$otp2 			= rand(0, 9);
		$otp3 			= rand(0, 9);
		$otp4 			= rand(0, 9);
		$otp5 			= rand(0, 9);
		$otp6 			= rand(0, 9);
		$otp7 			= rand(0, 9);
		$otp8 			= rand(0, 9);
		$otp9 			= rand(0, 9);
		
		$otp 			= $otp1.$otp2.$otp3.$otp4.$otp5.$otp6;
		$newPassword 	= (int) $otp; 
		$newPasswordMd5 = md5($newPassword);
		$cDate  		= date("Y-m-d H:i:s");

		$sqlSelect 		= "UPDATE my_registration SET date_modified='$cDate', password='$newPasswordMd5' WHERE id='$transferToID'";
		$stmt 			= $conn->pdo->prepare($sqlSelect);
		$queryExec		= $stmt->execute();

		$stmt2 = $conn->pdo->prepare("select * from my_registration where id='$transferToID'");
		$stmt2->execute();
		$resultData2 = $stmt2->fetch(PDO::FETCH_ASSOC);
		$result2 = array();

		if($resultData2['refer_id'] != NULL)
		{
			if($resultData['update_email'] == 1)
			{
				$apiUrl = "https://5a3db12020244ee2e56274dc0addfecb:7dfd66436f07538a43c806e1364f2b39@marvel-mii.myshopify.com/admin/customers/".$resultData2['customer_id'].".json";
				$customerData= array();
				$customerData['customer']['id'] = $resultData2['customer_id'];
				$customerData['customer']['password'] = $newPassword;
				$customerData['customer']['password_confirmation'] = $newPassword;

				$session = curl_init($apiUrl);
				curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($session, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
				curl_setopt($session, CURLOPT_POSTFIELDS, json_encode($customerData));
				curl_setopt($session, CURLOPT_CUSTOMREQUEST, "PUT");
				curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
				curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);

				$result2 = curl_exec($session);
				$response2 = json_decode($result2);

			}

		}
			
		if($queryExec == 1) {
			// Call email api with curl


			$message  = "New password for your for MyBooster Member ID: " .  $_REQUEST['refer_id'] . " is " .  $newPassword;
			$regData  = $conn->getMobileNumber();
			$mobileNo 	= trim($regData['country_code']).trim($regData['mobile_number']);
			$conn->send_SMS_ID($mobileNo, $message);

			
			$emailAddress 	= $_REQUEST['email_address'];
			$url 		 	= "http://localhost/MyBooster/mailer/API_mailer_forgot_password.php";
			
			
			$params['password']		   = $newPassword;
			$params['referID']		   = $_REQUEST['refer_id'];
			$params['name']			   = $name;
			$params['HTTP_USER_AGENT'] = urlencode(urldecode($_REQUEST['HTTP_USER_AGENT']));
			$params['email_address']   = $emailAddress;

		   
		   	$data_string = http_build_query($params);

			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
			curl_setopt($ch, CURLOPT_VERBOSE, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$emailResponse = curl_exec($ch);
			$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

			if($status->status==1)
				$emailResponse	= '{"status":"1","message":"Email has been sent successfully."}';

			$emailResponseArr  	= (array)json_decode($emailResponse);		
			//print_r($emailResponseArr);
			if( $emailResponseArr['status'] == '1' ) {
				$result['status']  	= '1';
				$result['message'] 	= 'We have generated new password for you and sent it to your email address registered with us.';
				$conn->pdo->commit();
			} else {
				$result['status']  	= '0';
				$result['message'] 	= 'Unable to sent you the email. Please contact admin.';
			}
		} else {
				$result['status']  	= '0';
				$result['message'] 	= 'Unable to generate new password. Please contact admin.';
		}
	} else {
		$result['status'] 			= '0';
		$result['message'] 			= 'Invalid credentials!';
	}	
}
catch(PDOException $e)
{
	$conn->pdo->rollback();
	//echo "Error: " . $e->getMessage();
	$result['status'] 			= '0';
	$result['message'] 			= 'Unable to process the request at this time. Please try after some time!';
}

$conn->pdo = null;
print $result = json_encode($result);
?> 

