<?php

	session_start();

	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 'aws/aws-autoloader.php';
	use Aws\S3\S3Client;
	use Aws\S3\Exception\S3Exception;
	require_once('database.php');

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


	if(!isset($_REQUEST['loginPassword']) || $_REQUEST['loginPassword']  == '') {
		$validationErr = "Please enter the login password";
	} 

	else if(!isset($_REQUEST['loginPasswordConfirm']) || $_REQUEST['loginPasswordConfirm']  == '') {
		$validationErr = "Please enter the confirm login password!";
	}

	else if(!isset($_REQUEST['transPassword']) || $_REQUEST['transPassword']  == '') {
		$validationErr = "Please enter the transaction password!";
	} 

	else if(!isset($_REQUEST['transPasswordConfirm']) || $_REQUEST['transPasswordConfirm']  == '') {
		$validationErr = "Please enter the confirm transaction password!";
	} 

	else if(!isset($_REQUEST['motherName']) || $_REQUEST['motherName']  == '') {
		$validationErr = "Please enter the mother's name!";
	}

	else if($_REQUEST['loginPassword'] == $_REQUEST['transPassword']) {
		$validationErr = "Login and Transaction password must be different!";
	}

	if($validationErr != '') {

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

	}

	$password            = $_REQUEST['loginPassword'];
	$transactionPassword = $_REQUEST['transPassword'];
	$motherName          = $_REQUEST['motherName'];

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

	function verifyMemberID($db, $referID)
	{
		$stmt = $db->prepare("select password from my_registration where refer_id='$referID'");
		$stmt->execute();
		$resultData = $stmt->fetch(PDO::FETCH_ASSOC);
		$db = null;
		return $resultData['password'];
	}

	
	function updatePassword($db, $referID, $password, $transactionPassword, $motherName)
	{
		$stmt = $db->prepare("update my_registration set password='$password', transaction_password='$transactionPassword', mother_name='$motherName' where refer_id='$referID'");
		if($stmt->execute())
			return true;
		else
			return false;

		$db = null;
	}

	function addToMyBooster($data)
	{
		$apiUrl = "https://5a3db12020244ee2e56274dc0addfecb:7dfd66436f07538a43c806e1364f2b39@marvel-mii.myshopify.com/admin/customers.json";
		$customerData = array();
		
		if($data['source'] =='new')
			$customerData['customer']['email'] = $data['email_address'];
		
		else
			$customerData['customer']['email'] = $data['refer_id'] . "@mybooster.biz";

		$customerData['customer']['first_name'] = $data['name'];
		$customerData['customer']['last_name'] = $data['last_name'];
		//$customerData['customer']['phone'] = $data['mobile_number'];
		$customerData['customer']['verified_email'] = true;
		$customerData['customer']['password'] = $data['decryptPassword'];
		$customerData['customer']['password_confirmation'] = $data['decryptPassword'];
		$customerData['customer']['accepts_marketing'] = true;
		$customerData['customer']['addresses'][0]['address1'] = $data['address1'];
		$customerData['customer']['addresses'][0]['address2'] = $data['address2'];
		$customerData['customer']['addresses'][0]['city'] = $data['city'];
		$customerData['customer']['addresses'][0]['province'] = $data['state'];
		$customerData['customer']['addresses'][0]['zip'] = $data['zip_code'];
		$customerData['customer']['addresses'][0]['last_name'] = $data['last_name'];
		$customerData['customer']['addresses'][0]['first_name'] =  $data['name'];
		$customerData['customer']['addresses'][0]['country'] = $data['country'];
		curlRequest($apiUrl, $customerData, $data['refer_id'], $data['source']);
	
	}



	function curlRequest($url, $data, $referID, $source){

			$url = $url;

			$params = $data;
			//print_r($data_string);
			$session = curl_init($url);
		    //curl_setopt($session, CURLOPT_HEADER, true);
			curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($session, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: POST'));
			curl_setopt($session, CURLOPT_POSTFIELDS, json_encode($params));
			curl_setopt($session, CURLOPT_CUSTOMREQUEST, 'POST');
			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);

			curl_close($session);
			
			if(isset($response->customer))
		    {
				updateassigned($referID, $response->customer->id, $source);
				$_SESSION['customer_id'] = $response->customer->id;
			}

		   
	}


	
	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['loginPassword'];
		$customerData['customer']['password_confirmation'] = $_REQUEST['loginPassword'];

		$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 updateassigned($referID, $customer_id, $source)
	{
		$updateEmail = 0;

		if($source == 'new')
			$updateEmail = 1;
		
		$conn = new Database;
		$db = $conn->getConnection();
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$stmt = $db->prepare("update my_registration set customer_id='$customer_id', assigned_user_id='1', update_email='$updateEmail' where refer_id='$referID'");
		$stmt->execute();
		$db = null;
	}


	function getData($db, $referID)
	{
		$stmt = $db->prepare("select * from my_registration where refer_id='$referID'");
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		$db = null;
		return $result;
	}


	if($storedPassword = verifyMemberID($db, $_SESSION['refer_id']))
	{

		if($storedPassword == md5($password))
		{
		    $result['success'] = false;
		    $result['message'] = "Login Password cannot be same as previous one!";
		    print $return = json_encode($result);
		}

		else
		{
			if(updatePassword($db, $_SESSION['refer_id'], md5($password), md5($transactionPassword), $motherName))
			{
				/*$result['success'] = true;
				$result['message'] = "Your account has been secured successfully!";
				print $return = json_encode($result);*/
				if($_SESSION['customer_id'] =='' || $_SESSION['customer_id'] ==0)
				{
					
					$data = getData($db, $_SESSION['refer_id']);
					$data['decryptPassword'] = $password;
					addToMyBooster($data);
					$result['success'] = true;
					$result['message'] = "Your account has been secured successfully!";
					print $return = json_encode($result);

				}

				else
				{
					updateCredentials();
					$result['success'] = true;
				    $result['message'] = "Your account has been secured successfully!";
				    print $return = json_encode($result);

				}

			}

			else
			{
				$result['success'] = false;
				$result['message'] = "Your request failed! Please try again.";
				print $return = json_encode($result);
			}

		}

	}


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


?> 
