<?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($_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($_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['swiftCode']) || $_REQUEST['swiftCode'] == '') {
			$validationErr = "Please Enter Swift Code!";
		} else if(!isset($_REQUEST['ifscCode']) || $_REQUEST['ifscCode'] == '') {
			$validationErr = "Please Enter IFSC Code!";
		}
	
	}

	else if($_REQUEST['section']==4)
	{
		if(!isset($_REQUEST['txtKYC']) || $_REQUEST['txtKYC'] == '') {
			$validationErr = "Please Enter KYC Details!";
		} else if(!isset($_FILES['kyc']) || $_FILES['kyc'] == '') {
			$validationErr = "Please upload KYC Docs!";
		}

	}

}



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['gender'];
$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'];
$pan_no = $_REQUEST['txtKYC'];
$account_type = $_REQUEST['membershipRadios'];


$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($section==1 || $section==2)
{

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

			$data = [
				'name' => $name,
				'last_name' => $last_name,
				'mobile_number' => $mobile_number,
				'email_address' => $email_address,
				'dob' => $dob,
				'gender' => $gender,
				'address1' => $addressLine1,
				'address2' => $addressLine2,
				'zip_code' => $zip_code,
				'country' => $country,
				'state' => $state,
				'city' => $city,
				'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 name=:name, last_name=:last_name, mobile_number=:mobile_number, email_address=:email_address, dob=:dob, gender=:gender, address1=:address1, address2=:address2, zip_code=:zip_code, country=:country, state=:state, city=:city, account_number=:account_number, bank_name=:bank_name, swift_code=:swift_code, ifsc_code=:ifsc_code, update_email='1' where refer_id=:refer_id";
		

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


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

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

		   }
				
		} 

		catch(PDOException $ex){
		   $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
		{
			$result['message'] = "Mobile Number is already registered with another user!";
		}

	}


}


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['data'] = json_encode($mybooster);
	   }

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

	   }
			
	} 

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


}


else
{

	$filepath = $_FILES['kyc']['tmp_name'];
	$info= new SplFileInfo($_FILES['kyc']['name']);
	$extension = strtolower($info->getExtension());
	$type = "";
	$filename = "";

	if($extension=="pdf")
		$type = "application/";

	else
		$type = "image/";

	$filename = time() . "." . $extension;

	
	if(uploadFile($filepath, $filename, $type, $extension))
	{
		
		try {

				$data = [
					'filename' => $filename,
     				'account_type' => $account_type,
					'pan_no' => $pan_no,
					'refer_id' => $refer_id
				];

			   $sql = "UPDATE my_registration set doc_name=:filename, account_type=:account_type, pan_no=:pan_no where refer_id=:refer_id";
			   $stmt= $db->prepare($sql);
			   $stmt->execute($data);

			   if($stmt->execute())
			   {
				   $result['success'] = true;
				   $result['message'] = "KYC Document uploaded successfully!";
			   }

			   else
			   {
				   $result['success'] = false;
				   $result['message'] = "KYC Document Failed!";
			   }
					
		} 

		catch(PDOException $ex){
		   $result['success'] = false;
		   $result['message'] = $ex->getMessage();
		}


	}


	else
	{
		 $result['success'] = false;
		 $result['message'] = "KYC Upload Failed. Please try later!";
	}



}

	echo json_encode($result);


	function updateProfile()
	{

		$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)
		{
			$customerData['customer']['email'] = $_REQUEST['emailID'];
			$customerData['customer']['phone'] = $_REQUEST['mobileNumber'];
		}

		$customerData['customer']['first_name'] = ucwords($_REQUEST['firstName']);
		$customerData['customer']['last_name'] = ucwords($_REQUEST['lastName']);
		$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'] = 'Residential';
		$customerData['customer']['addresses'][0]['first_name'] = 'Office';
		$customerData['customer']['addresses'][0]['country'] = ucwords($_REQUEST['country']);
		$customerData['customer']['addresses'][0]['default'] = true;


		$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 uploadFile($filepath, $filename, $type, $extension)
	{
		$bucketName = 'mybooster';
		$IAM_KEY    = 'AKIAIXFBI2SZQ54SYTSA';
		$IAM_SECRET = '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';

		// Connect to AWS
		try {
			// You may need to change the region. It will say in the URL when the bucket is open
			// and on creation.
			$s3 = S3Client::factory(
				array(
					'credentials' => array(
						'key' => $IAM_KEY,
						'secret' => $IAM_SECRET
					),
					'version' => 'latest',
					'region'  => 'ap-south-1'
				)
			);
		} catch (Exception $e) {
			// We use a die, so if this fails. It stops here. Typically this is a REST call so this would
			// return a json object.
			die("Error: " . $e->getMessage());
		}

				
		// For this, I would generate a unqiue random string for the key name. But you can do whatever.
		$keyName = 'KYC/' . basename($filename);
		$pathInS3 = 'https://s3.ap-south-1.amazonaws.com/' . $bucketName . '/' . $keyName;

		// Add it to S3
		try {
			
			$s3->putObject(
				array(
					'Bucket'=>$bucketName,
					'Key' =>  $keyName,
					'SourceFile' => $filepath,
					'StorageClass' => 'REDUCED_REDUNDANCY',
				    'ContentType' => $type.$extension,
					'ACL' => 'public-read'

				)
			);
		
		    return true;

		} catch (S3Exception $e) {
			return false;
		} catch (Exception $e) {
			return false;
		}

	}



?> 
