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

ini_set('max_execution_time', 30000);

require 'aws/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;




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


	if(!isset($_REQUEST['txtPan']) || $_REQUEST['txtPan'] == '') {
		$validationErr = "Please enter PAN or TAX Identification Number!";
	} else if(!isset($_REQUEST['addressProofInfo']) || $_REQUEST['addressProofInfo'] == '') {
		$validationErr = "Please enter Address Proof details!";
	} else if(!isset($_REQUEST['refer_id']) || $_REQUEST['refer_id'] == '') {
		$validationErr = "Please Enter Member ID!";
	} else if(!isset($_REQUEST['user_id']) || $_REQUEST['user_id'] == '') {
		$validationErr = "Please Enter User ID!";
	} else if(!isset($_REQUEST['accountTypeRadios']) || $_REQUEST['accountTypeRadios'] == '') {
		$validationErr = "Please mention the account type!";
	} else if($_REQUEST['accountTypeRadios'] == 2){
		if(!isset($_REQUEST['companyName']) || $_REQUEST['companyName'] == '')
			$validationErr = "Please enter the company name!";
	} else if($_REQUEST['accountTypeRadios'] == 2){
		if(!isset($_REQUEST['companyName']) || $_REQUEST['companyName'] == '')
			$validationErr = "Please enter the company name!";
		if(!isset($_REQUEST['txtGSTNo']) || $_REQUEST['txtGSTNo'] == '')
			$validationErr = "Please enter the GST Number!";
	}


	if($validationErr != '') {

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

	}

	$refer_id		  = $_REQUEST['refer_id'];
	$user_id		  = $_REQUEST['user_id'];
	$customer_id      = $_REQUEST['customer_id'];
	$companyName	  = $_REQUEST['companyName'];
	$pan_no  		  = $_REQUEST['txtPan'];
	$addressProof     = $_REQUEST['addressProof'];
	$addressProofInfo = $_REQUEST['addressProofInfo'];
    $txtpanDocs       = $_REQUEST['txtpanDocs'];
	$txtFrontDocs     = $_REQUEST['txtFrontDocs'];
	$txtBackDocs      = $_REQUEST['txtBackDocs'];
	$txtGSTNo         = $_REQUEST['txtGSTNo'];
	$account_type     = $_REQUEST['accountTypeRadios'];

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

    $accountDetails = verifyUser($refer_id, $user_id, $db);

	if(!empty($accountDetails))
	{
		
		
		if(verifyAccountType($refer_id, $account_type, $pan_no, $db))
		{
							
			try{	


					if(!empty($_FILES['panDocs']['tmp_name']))
					{
						$filepath  = $_FILES['panDocs']['tmp_name'];
						$info      = new SplFileInfo($_FILES['panDocs']['name']);
						$size= $_FILES['panDocs']['size'];
						if($size > 2000000)
						{
							$result = array();
							$result['status'] = '0';
							$result['message'] = "Upload an image less than 2 MB!";
							print $return = json_encode($result);
							exit;
						}

						$extension = strtolower($info->getExtension());
						$type      = "";
						$filename  = "";

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

						else
							$type  = "image/";

						$filename  = "pan_" . time() . mt_rand(100, 999999) . "." . $extension;

						if(uploadFile($filepath, $filename, $type, $extension))
							$txtpanDocs = $filename;
				
					}

		


					if(!empty($_FILES['frontDocs']['tmp_name']))
					{
						$filepath  = $_FILES['frontDocs']['tmp_name'];
						$info      = new SplFileInfo($_FILES['frontDocs']['name']);
						$size= $_FILES['frontDocs']['size'];
						if($size > 2000000)
						{
							$result = array();
							$result['status'] = '0';
							$result['message'] = "Upload an image less than 2 MB!";
							print $return = json_encode($result);
							exit;
						}

						$extension = strtolower($info->getExtension());
						$type      = "";
						$filename  = "";

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

						else
							$type  = "image/";

						$filename  = "front_" . time() . mt_rand(100, 999999) . "." . $extension;

						if(uploadFile($filepath, $filename, $type, $extension))
							$txtFrontDocs = $filename; 

					}



					if(!empty($_FILES['backDocs']['tmp_name']))
					{

						$filepath  = $_FILES['backDocs']['tmp_name'];
						$info      = new SplFileInfo($_FILES['backDocs']['name']);
						$size= $_FILES['backDocs']['size'];
						if($size > 2000000)
						{
							$result = array();
							$result['status'] = '0';
							$result['message'] = "Upload a video less than 2 MB!";
							print $return = json_encode($result);
							exit;
						}
						$extension = strtolower($info->getExtension());
						$type      = "";
						$filename  = "";

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

						else
							$type  = "image/";

						$filename  = "back_" . time() . mt_rand(100, 999999) . "." . $extension;

						if(uploadFile($filepath, $filename, $type, $extension))
							$txtBackDocs = $filename;
		
					}


					$stmt = $db->prepare("update my_registration set account_type='$account_type', company_name='$companyName', gst_no='$txtGSTNo', pan_no='$pan_no', doc_name='$txtpanDocs', address_proof='$addressProof', proof_id='$addressProofInfo', front_cover='$txtFrontDocs', back_cover='$txtBackDocs' where refer_id='$refer_id' AND id='$user_id'");
					$stmt->execute();

					

					$result['success'] = true;
			        $result['message'] = "KYC updated successfully!";

    		}
			

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

 
		}

		else
		{

			$result['success'] = false;
			
			if( $account_type == 1)
				$result['message'] = "You can have maximum 3 individual account with the single pan card. Your KYC won't get accepted, please contact administrator.";
			
			else
				$result['message'] = "You can have maximum 5 company account with the single pan card. Your KYC won't get accepted, please contact administrator.";

		}

	}

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




	function verifyAccountType($refer_id, $account_type, $pan_no, $db)
	{

		try
		{
            $stmt = $db->prepare("select count(pan_no) as pancount from my_registration where pan_no='$pan_no'");
			$stmt->execute();
			$result = $stmt->fetch(PDO::FETCH_ASSOC);
			$db = null;
			
			if($account_type == 1)
			{
				if($result['pancount']<3)
					return true;
				else
					return false;
			}

			else
			{
				if($result['pancount']<5)
					return true;
				else
					return false;
			}

		
		}

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

	}


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

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

		
	}


	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) {
			echo $e->getMessage();
			return false;
		} catch (Exception $e) {
			return false;
		}

	}


	echo json_encode($result);

?> 
