<?php

session_start();

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


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

	ini_set('display_startup_errors',1);
	ini_set('display_errors',1);
	error_reporting(1);

/*
$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 = '';
$section = 0;

if(!empty($_REQUEST['section']))
{
	$section = $_REQUEST['section'];

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

	else if($_REQUEST['section'] == 1)
	{
		if(!isset($_REQUEST['oldPassword']) || $_REQUEST['oldPassword'] == '') {
			$validationErr = "Please Enter Old Password!";
		} else if(!isset($_REQUEST['newPassword']) || $_REQUEST['newPassword'] == '') {
			$validationErr = "Please Enter New Password!";
		} else if(!isset($_REQUEST['confirmPassword']) || $_REQUEST['confirmPassword'] == '') {
			$validationErr = "Please Enter Confirm Password!";
		} else if($_REQUEST['confirmPassword'] != $_REQUEST['newPassword']) {
			$validationErr = "New and Confirm Password should be same!";
		} else if($_REQUEST['oldPassword'] == $_REQUEST['newPassword']){
			$validationErr = "Old and New Password cannot be same!";
		} else if(!isset($_REQUEST['txtAuthenticate']) || $_REQUEST['txtAuthenticate'] == '') {
			$validationErr = "Please enter transaction password!";
		} else if($_REQUEST['txtAuthenticate'] == $_REQUEST['newPassword']){
			$validationErr = "Login and Transaction password cannot be same!";
		}
	}

	else
	{
		if(!isset($_REQUEST['txtAuthenticate']) || $_REQUEST['txtAuthenticate'] == '') {
			$validationErr = "Please enter transaction password!";
		} else if(!isset($_REQUEST['newTransactPwd']) || $_REQUEST['newTransactPwd'] == '') {
			$validationErr = "Please Enter New Password!";
		} else if(!isset($_REQUEST['confirmTransactPwd']) || $_REQUEST['confirmTransactPwd'] == '') {
			$validationErr = "Please Enter Confirm Password!";
		} else if($_REQUEST['txtAuthenticate'] == $_REQUEST['newTransactPwd']){
			$validationErr = "Old and New Transaction password cannot be same!";
		} else if($_REQUEST['newTransactPwd'] != $_REQUEST['confirmTransactPwd']) {
			$validationErr = "New and Confirm Password should be same!";
		} else if(!isset($_REQUEST['txtMotherName']) || $_REQUEST['txtMotherName'] == '') {
			$validationErr = "Please Enter Mother's Name!";
		}
	 }

}


else
{
    $result['success'] = false;
	$result['message'] = "Change Password request failed! Please try later!";
	print $return = json_encode($result);
	exit;
}



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 = $_SESSION['refer_id'];
$user_id = $_SESSION['user_id'];
$oldpassword = md5($_REQUEST['oldPassword']);
$newpassword = md5($_REQUEST['newPassword']);
$oldTransactionPassword = md5($_REQUEST['txtAuthenticate']);
$newTransactionPassword = md5($_REQUEST['newTransactPwd']);
$motherName = $_REQUEST['txtMotherName'];
$result = array();


if(!verifyTransactionPassword($db, $refer_id))
{
	$result['success'] = false;
	$result['message'] = "Invalid Transaction Password or Member ID!";
	echo json_encode($result);
	exit;
}


if($section==1)
{

	if(verifyPassword($refer_id, $user_id, $oldpassword, $db))
	{

		if(updatePassword($user_id, $oldpassword, $newpassword, $db))
		{
			$result['success'] = true;
			$result['message'] = "Login Password updated successfully!";
		}

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

	}

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

}



else
{



    if(strtolower($motherName) == strtolower(getMotherName($refer_id, $db)))
	{


		if(matchPassword($refer_id, $user_id, $newTransactionPassword, $db))
		{					
			$result['success'] = false;
			$result['message'] = "Login and Transaction Password cannot be same!";
		
		}

		else
		{
			if(updateTransactionPassword($user_id, $oldTransactionPassword, $newTransactionPassword, $db))
			{
				$result['success'] = true;
				$result['message'] = "Transaction Password updated successfully!";
			}

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

	}

	else
	{
		$result['success'] = false;
		$result['message'] = "Mother's name does not match in our database. Please contact admin to update your password!";
	}


}



   function verifyPassword($refer_id, $user_id, $oldpassword, $db)
	{
		try
		{
            $stmt = $db->prepare("select refer_id from my_registration where refer_id='$refer_id' && id='$user_id' && password='$oldpassword'");
			$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'] = "Change Password request failed! Please try after sometime.";
		}

		
	}


	function updatePassword($user_id, $oldpassword, $newpassword, $db)
	{

		$mybooster = updateCredentials();

		
		if(!empty($mybooster->customer))
		{
			try
			{
				$stmt = $db->prepare("update my_registration set password=? where id=? && password=?");
				$stmt->execute(array($newpassword, $user_id, $oldpassword));
				//echo $stmt->rowCount(); exit;
				if($stmt->rowCount())
					return true;
				else
					return false;
			}

			catch(PDOException $ex){
			   $result['success'] = false;
			   $result['message'] = "Change Password request failed! Please try after sometime.";

			}
		}

		else
		{
			$result['success'] = false;
			$result['message'] = "Change Password request failed! Please contact admin.";
		}


	}


	function updateCredentials()
	{

		$apiUrl = "https://5a3db12020244ee2e56274dc0addfecb:7dfd66436f07538a43c806e1364f2b39@marvel-mii.myshopify.com/admin/customers/".$_SESSION['customer_id'].".json";


		$customerData= array();
		$customerData['customer']['id'] = $_SESSION['customer_id'];
		$customerData['customer']['password'] = $_REQUEST['newPassword'];
		$customerData['customer']['password_confirmation'] = $_REQUEST['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);

		$result = curl_exec($session);
		$response = json_decode($result);
		return $response;

	}


	 function verifyTransactionPassword($db, $referID)
	 {
			
			try{

				   $stmt   = $db->prepare("select refer_id from my_registration where refer_id=? AND transaction_password=?");
				   $stmt->execute(array($_SESSION['refer_id'], md5($_REQUEST['txtAuthenticate'])));			   
				   $row = $stmt->fetch(PDO::FETCH_ASSOC);

				   if($row['refer_id'])
					return true;

				   else
					return false;
			}

			catch(PDOException $ex){
			   return 0;
			}

	 }


	 function matchPassword($refer_id, $user_id, $newTransactionPassword, $db)
	 {

		 try{

		   $stmt   = $db->prepare("select refer_id from my_registration where id=? AND refer_id=? AND password=?");
		   $stmt->execute(array($user_id, $refer_id, $newTransactionPassword));			   
		   $row = $stmt->fetch(PDO::FETCH_ASSOC);

		   if(($row['refer_id']!='') && ($row['refer_id']!=NULL))
			return true;

		   else
			return false;
		}

		catch(PDOException $ex){
		   echo $ex->getMessage();
		   return 0;
		}


	 }



	 function updateTransactionPassword($user_id, $oldTransactionPassword, $newTransactionPassword, $db)
	 {

		 try
			{
				$stmt = $db->prepare("update my_registration set transaction_password=? where id=? && transaction_password=?");
				$stmt->execute(array($newTransactionPassword, $user_id, $oldTransactionPassword));
				//echo $stmt->rowCount(); exit;
				if($stmt->rowCount())
					return true;
				else
					return false;
			}

			catch(PDOException $ex){
			   $result['success'] = false;
			   $result['message'] = "Change Password request failed! Please try after sometime.";

			}

	 }



	 function getMotherName($refer_id, $db)
	 {
		 
		 try
			{
				$stmt = $db->prepare("select mother_name from my_registration where refer_id=?");
				$stmt->execute(array($refer_id));
				$row = $stmt->fetch(PDO::FETCH_ASSOC);
				return $row['mother_name'];

			}

			catch(PDOException $ex){
			   $result['success'] = false;
			   $result['message'] = "Change Password request failed! Please try after sometime.";

			}

    }



echo json_encode($result);



?> 
