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


if(isset($_REQUEST['dob'])) {

	$_REQUEST['dob'] = str_replace("/", "-" , $_REQUEST['dob']);
	$_REQUEST['dob'] = date("Y-m-d", strtotime($_REQUEST['dob']));

}


/*$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 = '';
$result = array();

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

	if($_REQUEST['section']==1)
	{
		if(!isset($_REQUEST['firstName']) || $_REQUEST['firstName'] == '') {
			$validationErr = "Please Enter first name!";
		} else if(!isset($_REQUEST['lastName']) || $_REQUEST['lastName'] == '') {
			$validationErr = "Please Enter last name!";
		} else if(!isset($_REQUEST['mobileNumber']) || $_REQUEST['mobileNumber'] == '') {
			$validationErr = "Please Enter Mobile Number!";
		} else if(!isset($_REQUEST['emailID']) || $_REQUEST['emailID'] == '') {
			$validationErr = "Please enter email_address!";
		} else if(!isset($_SESSION['refer_id']) || $_SESSION['refer_id'] == '') {
			$validationErr = "Please Enter Member ID!";
		} else if(!isset($_SESSION['user_id']) || $_SESSION['user_id'] == '') {
			$validationErr = "Please Enter User ID!";
		} else if(!isset($_REQUEST['txtAuthenticate']) || $_REQUEST['txtAuthenticate'] == '') {
			$validationErr = "Please Enter Transaction Password!";
		} 

	}

	else if($_REQUEST['section']==2)
	{
		if(!isset($_REQUEST['addressLine1']) || $_REQUEST['addressLine1'] == '') {
			$validationErr = "Please Enter Address Line1!";
		} else if(!isset($_REQUEST['addressLine2']) || $_REQUEST['addressLine2'] == '') {
			$validationErr = "Please Enter Address Line2!";
		} else if(!isset($_REQUEST['zipCode']) || $_REQUEST['zipCode'] == '') {
			$validationErr = "Please Enter Zip Code!";
		} else if(!isset($_REQUEST['country']) || $_REQUEST['country'] == '') {
			$validationErr = "Please enter the country name!";
		} else if(!isset($_REQUEST['state']) || $_REQUEST['state'] == '') {
			$validationErr = "Please enter the state name!";
		} else if(!isset($_REQUEST['city']) || $_REQUEST['city'] == '') {
			$validationErr = "Please enter the city name!";
		} else if(!isset($_REQUEST['txtAuthenticate']) || $_REQUEST['txtAuthenticate'] == '') {
			$validationErr = "Please Enter Transaction Password!";
		} 

	}


	else if($_REQUEST['section']==3)
	{

		if(!isset($_REQUEST['accountNo']) || $_REQUEST['accountNo'] == '') {
			$validationErr = "Please Enter Bank Account Number!";
		} else if(!isset($_REQUEST['bankName']) || $_REQUEST['bankName'] == '') {
			$validationErr = "Please Enter Bank Name!";
		} else if(!isset($_REQUEST['ifscCode']) || $_REQUEST['ifscCode'] == '') {
			$validationErr = "Please Enter IFSC Code!";
		} else if(!isset($_REQUEST['txtAuthenticate']) || $_REQUEST['txtAuthenticate'] == '') {
			$validationErr = "Please Enter Transaction Password!";
		} 
	
	}

}



else
{
    $result['success'] = false;
	$result['message'] = "Profile Update 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;

}

$refer_id = $_SESSION['refer_id'];
$name =  ucwords($_REQUEST['firstName']);
$last_name = ucwords($_REQUEST['lastName']);
$mobile_number = $_REQUEST['mobileNumber'];
$email_address = $_REQUEST['emailID'];
$dob = $_REQUEST['dob'];
$gender = $_REQUEST['selectGender'];
$addressLine1 = ucwords($_REQUEST['addressLine1']);
$addressLine2= ucwords($_REQUEST['addressLine2']);
$zip_code = $_REQUEST['zipCode'];
$country = ucwords($_REQUEST['country']);
$state = ucwords($_REQUEST['state']);
$city = ucwords($_REQUEST['city']);
$account_number = $_REQUEST['accountNo'];
$bank_name= ucwords($_REQUEST['bankName']);
$swift_code = $_REQUEST['swiftCode'];
$ifsc_code = $_REQUEST['ifscCode'];
$section = $_REQUEST['section'];






$result = array();


$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);


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



if($section==1 || $section==2)
{

    
	$type = updateType($db);

	if($type)
	{
	   
		$mybooster = updateProfile($type);
		if(isset($mybooster->customer))
		{
			
			try {

				$sql = "";
				$data = [];

				if($section==1)
				{
					$d1 = new DateTime($dob);
					$d2 = new DateTime(date("Y-m-d"));
					$diff = $d2->diff($d1);

	
					if($diff->y<18)
					{
						$result['success'] = false;
						$result['message'] = "Profile Updation failed! Your age must be more than 18 years!";
						echo json_encode($result);
						exit;
					}

					if($type == 1)
					{
						$sql = "UPDATE my_registration set name=:name, last_name=:last_name, dob=:dob, gender=:gender where refer_id=:refer_id";
						
						$data = ['name' => $name, 'last_name' => $last_name, 'dob' => $dob, 'gender' => $gender, 'refer_id' => $refer_id];

					}

					else if($type == 2)
					{
						$sql = "UPDATE my_registration set name=:name, last_name=:last_name, mobile_number=:mobile_number, dob=:dob, gender=:gender where refer_id=:refer_id";
						
						$data = ['name' => $name, 'last_name' => $last_name, 'mobile_number' => $mobile_number, 'dob' => $dob, 'gender' => $gender, 'refer_id' => $refer_id];
					}

					else if($type == 3)
					{
						$sql = "UPDATE my_registration set name=:name, last_name=:last_name, mobile_number=:mobile_number, email_address=:email_address, dob=:dob, gender=:gender, update_email='1', verified='1' where refer_id=:refer_id";
						
						$data = ['name' => $name, 'last_name' => $last_name, 'mobile_number' => $mobile_number, 'email_address' => $email_address, 'dob' => $dob, 'gender' => $gender, 'refer_id' => $refer_id];
					}

					else
					{
						$sql = "UPDATE my_registration set name=:name, last_name=:last_name, email_address=:email_address, dob=:dob, gender=:gender, update_email='1', verified='1' where refer_id=:refer_id";
						
						$data = ['name' => $name, 'last_name' => $last_name, 'email_address' => $email_address, 'dob' => $dob, 'gender' => $gender, 'refer_id' => $refer_id];
					}

				}


				else
				{
					$sql = "UPDATE my_registration set address1=:address1, address2=:address2, zip_code=:zip_code, country=:country, state=:state, city=:city where refer_id=:refer_id";
					
					$data = ['address1' => $addressLine1, 'address2' => $addressLine2, 'zip_code' => $zip_code, 'country' => $country, 'state' => $state, 'city' => $city, 'refer_id' => $refer_id];
				}
			

				$stmt= $db->prepare($sql);
				$stmt->execute($data);


			   if($stmt->execute())
			   {
				   $result['success'] = true;
				   $result['message'] = "Profile Updated Successfully!";
				   $result['section'] = $section;
				   //$result['data'] = json_encode($mybooster);
			   }

			   else
			   {
				   $result['success'] = false;
				   $result['message'] = "Profile Updated Failed!";

			   }
					
			} 

			catch(PDOException $ex){
               //echo $ex->getMessage();
			   $result['success'] = false;
			   $result['message'] = "Profile Updated Failed!";
			}

		}


		else
		{

			$result['success'] = false;

			if(isset($mybooster->errors->email))
			{
				$result['message'] = "Email ID is already registered with another user!";
			}

			else if(isset($mybooster->errors->phone))
			{
				$result['message'] = "Mobile Number is already registered with another user!";
			}

			else if(isset($mybooster->errors->{'addresses.province'}))
			{
				$result['message'] = "State Name is invalid!";
			}

			else if(isset($mybooster->errors->{'addresses.country'}))
			{
				$result['message'] = "Country Name is invalid!";
			}


		}

	}

	else{

		$result['success'] = false;
		$result['message'] = "Profile Updation Failed! Please try later!";
	
	}


}


else if($section==3)
{

	try {

		$data = [
			'account_number' => $account_number,
			'bank_name' => $bank_name,
			'swift_code' => $swift_code,
			'ifsc_code' => $ifsc_code,
			'refer_id' => $refer_id,
		];

		$sql = "UPDATE my_registration set account_number=:account_number, bank_name=:bank_name, swift_code=:swift_code, ifsc_code=:ifsc_code where refer_id=:refer_id";
	

		$stmt= $db->prepare($sql);
		$stmt->execute($data);


	   if($stmt->execute())
	   {
		   $result['success'] = true;
		   $result['message'] = "Bank Profile Updated Successfully!";
		   $result['section'] = $section;
	   }

	   else
	   {
		   $result['success'] = false;
		   $result['message'] = "Bank Profile Updation Failed!";

	   }
			
	} 

	catch(PDOException $ex){
	   $result['success'] = false;
	   $result['message'] = "Bank Profile Updation Failed!";
	}


}


    echo json_encode($result);


	function updateProfile($type)
	{

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

		$customerData= array();
		$customerData['customer']['id'] = $_SESSION['customer_id'];
		
		if($_REQUEST['section'] == 1)
		{
			if($type == 2)
			{
				$customerData['customer']['phone'] = $_REQUEST['mobileNumber'];
			}

			else if($type == 3)
			{
				$customerData['customer']['email'] = $_REQUEST['emailID'];
				$customerData['customer']['phone'] = $_REQUEST['mobileNumber'];
			}

			else if($type == 4)
				$customerData['customer']['email'] = $_REQUEST['emailID'];

			$customerData['customer']['first_name'] = ucwords($_REQUEST['firstName']);
		    $customerData['customer']['last_name'] = ucwords($_REQUEST['lastName']);

		}

		
		
		else if($_REQUEST['section'] == 2)
		{
		
			$customerData['customer']['addresses'][0]['address1'] = ucwords($_REQUEST['addressLine1']);
			$customerData['customer']['addresses'][0]['address2'] = ucwords($_REQUEST['addressLine2']);
			$customerData['customer']['addresses'][0]['city'] = ucwords($_REQUEST['city']);
			$customerData['customer']['addresses'][0]['province'] = ucwords($_REQUEST['state']);
			$customerData['customer']['addresses'][0]['zip'] = $_REQUEST['zipCode'];
			$customerData['customer']['addresses'][0]['last_name'] = ucwords($_REQUEST['lastName']);
			$customerData['customer']['addresses'][0]['first_name']= ucwords($_REQUEST['firstName']);
			$customerData['customer']['addresses'][0]['country'] = ucwords($_REQUEST['country']);
			$customerData['customer']['addresses'][0]['default'] = true;
		}

		else
			return 0;

		$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 updateType($db)
	{
		
		try {

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

			   $type = 1;

			   if($_REQUEST['mobileNumber'] != $row['mobile_number'])
			   {
				  
				  $type = 2;

				  if($_REQUEST['emailID'] != $row['email_address'])
					  $type = 3;

			   }

			   else if($_REQUEST['emailID'] != $row['email_address'])
				   $type = 4;

			 return $type;
		}

		catch(PDOException $ex){
		   return 0;
		}


	}

	
	function verifyPassword($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;
		}



	}


?> 
