<?php
	
	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');

	$file = fopen("API_logs/API_uploadPackageSlip","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 = '';
	$result = array();

    if(!isset($_REQUEST['order_id']) || $_REQUEST['order_id'] == '') {		
		$validationErr = "Order ID is missing. Request Failed!";
	} else if(!isset($_FILES['bankSlip']) || $_FILES['bankSlip'] == '') {
		$validationErr = "Please upload Bank Deposit Slip!";
	}

	if($validationErr != '') {

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

	}

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

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

	else
		$type = "image/";

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

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

	$id = verifyOrder($db, $order_id, $refer_id);


	if(!empty($id))
	{
	    if(uploadFile($filepath, $filename, $type, $extension))
		{
           if(update_Member_Package($db, $order_id, $filename))
			{
			   $result['success'] = true;
			   $result['message'] = "Bank Deposit Slip uploaded. Would take 3 to 4 working days for verification!";
	
			}

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

		}


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

   

	}

	else
	{
		$result['success'] = false;
		$result['message'] = "Request cannot be processed due to invalid credentials. Please contact administrator!";
	}


	echo json_encode($result);


	function verifyOrder($db, $order_id, $refer_id)
	{
		$sqlSelect 	= "SELECT id FROM my_member_package WHERE refer_id='$refer_id' && order_id='$order_id' && payment_status='0'";
		$stmt 		= $db->prepare($sqlSelect);
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		return $result['id'];
	}



	function update_Member_Package($db, $order_id, $filename)
	{
		
	    try 
		{
			$data = [
				'deposit_slip' => $filename,
				'order_id' => $order_id
			];

			$sql = "UPDATE my_member_package set deposit_slip=:deposit_slip where order_id=:order_id";
		
			$stmt= $db->prepare($sql);
			$stmt->execute($data);

			if($stmt->execute())
			{
			  return true;
			}

		    else
		  	  return false;
		   			
		}

		catch(PDOException $ex){
		   return false;
		}

	}
	

	
	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 = 'Deposit_Slip/' . 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;
		}

	}


 ?>