<?php 

include("../includes/config.php");
include("../../quiklrn_app/rester_api.php");
include("../../quiklrn_app/config.php");

// include("../includes/s3.php");
include("../includes/presignedUrl.php");

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$method="Unknown";
if(isset($_REQUEST["method"]))
	$method=$_REQUEST["method"];

$path="";
if(isset($_REQUEST["path"]))
	$path=$_REQUEST["path"];
	
if($method==="upload"){

	$AWS_DESTINATION_PATH = S3_BASE_URI."/".STATIC_CONTAINER."/xyz.png";
	$path= $AWS_DESTINATION_PATH;
	$src_path = $_REQUEST["src"];
	
	if(empty($path) || empty($_REQUEST['src'])) {
		return header('HTTP/1.1 400 Bad Request', true, 400);
	}
	
	$accepted_files = ["jpg", "jpeg", "png", "gif", "webp", "tiff", "psd", "raw", "bmp", "heif", "indd", "svg", "eps"];
	$file_ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
	
	if(empty($path) || !in_array($file_ext, $accepted_files)) {
		return header('HTTP/1.1 400 Bad Request', true, 400);
	}
	
	$src_path = $_REQUEST['src'];
	// $dst_path = $path;
	$dst_path = $AWS_DESTINATION_PATH;
	echo s3_cloud_upload($src_path,$dst_path); //return the path
	
}else if($method==="delete"){
	echo s3_cloud_delete($path); //return true or false
}else if($method == 'uploadFile'){
	echo s4_cloud_upload(); //return the path	
}else if($method == 'sendEmailWorkFlow'){
	sendEmailWorkFlow();
}else if($method == 'generatePresignedURL'){
	generatePresignedURL();
}else if($method == 's3AccessUpload'){
	s3AccessUpload();
}else if($method == 'getListOffiles'){
	getListOffiles();
}else if($method == 'auth_function'){
	json_output(auth_function());
}else if($method == 'get_college_dept_id'){
	json_output(get_college_dept_id());
}else if($method == 'getSemesterCourseSectionDetailByUser'){
	json_output(getSemesterCourseSectionDetailByUser());
}

function getSemesterCourseSectionDetailByUser(){
    $auth = isset($_REQUEST['auth_code']) ? $_REQUEST['auth_code'] : '';
    $college_id = isset($_REQUEST['college_id']) ? $_REQUEST['college_id'] : '';
    $user_id = isset($_REQUEST['u_id']) ? $_REQUEST['u_id'] : '';
    $myArray = [
        "college_id" => $college_id,
        "user_idno" => $user_id
     ];
     $apiParameters = (form_rester_api_object("getSemesterCourseSectionDetailByUser", $myArray));
     $encodedParameters = (json_encode([$apiParameters]));
     $headers = array('x-auth-key: ' . $auth);
     $callAPI = APICall('POST', BASE_URL, $encodedParameters, $headers);

     $apiData = (json_decode($callAPI));
     $getSemesterCourseSectionDetailByUser = isset($apiData->data->getSemesterCourseSectionDetailByUser) ? $apiData->data->getSemesterCourseSectionDetailByUser : [];
     $data_arr['getSemesterCourseSectionDetailByUser'] = [];
     //  $data_arr['getCreatedCourseSectionList'] = getCreatedCourseSectionList();
     if (count($getSemesterCourseSectionDetailByUser)) {
        ($data_arr['getSemesterCourseSectionDetailByUser'] = $getSemesterCourseSectionDetailByUser);
    }
    return get_generic_response(200, $data_arr, "Records Found!");
}

function get_college_dept_id()
{
    $user = isset($_REQUEST['u_id']) ? $_REQUEST['u_id'] : '';
    $auth = isset($_REQUEST['auth']) ? $_REQUEST['auth'] : '';
    $myArray = [
        "user_id" => $user,
    ];
    $getClgMethod = "getCollegeIdName";
    $getDeptMethod = "getDepartmentIDName";
    $formVar = (form_rester_api_object($getClgMethod, $myArray));
    $encodedVar = (json_encode([$formVar]));
    $headers = array('x-auth-key: ' . $auth);
    $api_data = APICall('POST', BASE_URL, $encodedVar, $headers);

    $clgApiDecodedData = (json_decode($api_data));

    $data_arr['clg_details'] = array();
    $data_arr['dept_details'] = array();
    $data_arr['offering_details'] = array();
    $getClgFilteredData = isset($clgApiDecodedData->data->getCollegeIdName) ? $clgApiDecodedData->data->getCollegeIdName : null;
    if (count($getClgFilteredData)) {
        array_push($data_arr['clg_details'], $getClgFilteredData[0]);

        $myArray = [
            "college_id" => $getClgFilteredData[0]->college_id,
            "match_user" => " AND U.user_id = ($user)",
        ];

        $form_object_var = [
            ["method" => $getDeptMethod, "params" => $myArray],
            //  ["method" => "getOfferingByCollegeID", "params" => ["college_id" =>$getClgFilteredData[0]->college_id]],
        ];

        $encoded_object_var = (json_encode($form_object_var));
        $headers = array('x-auth-key: ' . $auth);
        $api_data = APICall('POST', BASE_URL, $encoded_object_var, $headers);

        $deptApiDecodedData = (json_decode($api_data));
       
        $getDeptData = isset($deptApiDecodedData->data->getDepartmentIDName) ? $deptApiDecodedData->data->getDepartmentIDName : null;
        // $getOfferingData = isset($deptApiDecodedData->data->getOfferingByCollegeID) ? $deptApiDecodedData->data->getOfferingByCollegeID : null;
       
        if (count($getDeptData)) {
            array_push($data_arr['dept_details'], $getDeptData[0]);
        }
        // if (count($getOfferingData)) {
        //     array_push($data_arr['offering_details'], $getOfferingData[0]);
        // }
    }

    (objectArrayToArray($data_arr));
    return get_generic_response(200, $data_arr, "Records Found!");
}

function objectArrayToArray($objArray)
{
    $json = json_encode($objArray);
    $array = json_decode($json, true);
    return $array;
}

function auth_function()
{

    $method = 'getUserIdByAuthCode';
    $auth = isset($_REQUEST['auth_code']) ? $_REQUEST['auth_code'] : '';
    $myArray = [
        "auth" => $auth,
    ];
    $aa_var = (form_rester_api_object($method, $myArray));
    $var = (json_encode([$aa_var]));
    $headers = array('x-auth-key: ' . $auth);
	
    $ab_var = APICall('POST', BASE_URL, $var, $headers);
	
    $my_data = (json_decode($ab_var));
	
    // $data_arr['auth'] = array();
	$data_arr = array();
    $getUserIdByAuthCode = $my_data->data->getUserIdByAuthCode;
    if (count($my_data->data->getUserIdByAuthCode)) {
        array_push($data_arr, $getUserIdByAuthCode);
    }
    return get_generic_response(200, $getUserIdByAuthCode, "Records Found!");

}
function array_to_csv_download() {

    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

    $delimiter = ",";
    $filename = "reports_" . date('Y-m-d') . ".csv";
   
    $tmpDir = '../../../tmp/output.csv';
    
    // $csvFile = fopen('/var/www/html/tmp/xyz.csv', 'w');
    $csvFile = fopen($tmpDir, 'w');
   
    if (!flock($csvFile, LOCK_EX)) {
        error_log('Cannot get lock!');
        return false;
    } 

    $fields = array('Dept Name', 'Course Name', 'Course Code');
    fputcsv($csvFile, $fields, $delimiter);
    $array = array(['department_name'=> 'Gen', 'course_name'=> 'Maths', 'course_code' => '123']);
    $csvData = array();
    foreach($array as $data){
        $csvData =  array($data['department_name'],$data['course_name'], $data['course_code']); 
        fputcsv($csvFile, $csvData);
    }
    fclose($csvFile);
    return true;
}   
function sendEmailWorkFlow()
{
	$email_type = isset($_REQUEST['email_type']) ? $_REQUEST['email_type']  : 0;
	if($email_type == 0){
	    return get_generic_response(404, null, "Email Type not found!");
	}
	$fromUserId = isset($_REQUEST['fromUserId']) && ($_REQUEST['fromUserId']) ? ($_REQUEST['fromUserId']) : 0;
	if ($fromUserId == 0) {
		return get_generic_response(404, null, "fromUserId not found!");
	}
	if($email_type == 2){
		$csvDownload = array_to_csv_download();
		if($csvDownload){
			// $uploadFile = (s4_cloud_upload($fromUserId));
			$uploadFile = (generateUploadedPresignedURL($fromUserId));
			
			$statusCode = $uploadFile['status_code'];	
			$action_url = $uploadFile['objectURI'];
			if($statusCode == 200){
				$get = $_GET;
				echo $uploadFile['msg']."</br>";
				
				echo $action_url."</br>";
				save_email($get, $action_url);
			}
		}
	}elseif($email_type == 1){
		$get = $_GET;
		save_email($get);
	}
    
}

function generatePresignedURL(){

	$fromUserId = isset($_REQUEST['fromUserId']) && ($_REQUEST['fromUserId']) ? ($_REQUEST['fromUserId']) : 0;
	if ($fromUserId == 0) {
		return get_generic_response(404, null, "fromUserId not found!");
	}
	$uploadFile = (generateUploadedPresignedURL($fromUserId));
}
function save_email($get, $action_url='') {
	
	 	$notification_type="3";
		$fromEmail = isset($get['fromEmail']) && ($get['fromEmail']) ? ($get['fromEmail']) : 0;
	
		if ($fromEmail == 0) {
			return get_generic_response(404, null, "fromEmail not found!");
		}
		$fromName = isset($get['fromName']) && ($get['fromName']) ? ($get['fromName']) : 0;
		if ($fromName == 0) {
			return get_generic_response(404, null, "fromName not found!");
		}
		$fromUserId = isset($get['fromUserId']) && ($get['fromUserId']) ? ($get['fromUserId']) : 0;
		if ($fromUserId == 0) {
			return get_generic_response(404, null, "fromUserId not found!");
		}
		$toEmail = isset($get['toEmail']) && count($get['toEmail']) ? $get['toEmail'] : 0;
		if ($toEmail == 0) {
			return get_generic_response(404, null, "toEmail not found!");
		}
		$toName = isset($get['toName']) && count($get['toName']) ? $get['toName'] : 0;
		if ($toName == 0) {
			return get_generic_response(404, null, "toName not found!");
		}

		$toUserId = isset($get['toUserId']) && count($get['toUserId']) ? $get['toUserId'] : 0;
		if ($toUserId == 0) {
			return get_generic_response(404, null, "toUserId not found!");
		}
		
		$subject = isset($get['subject']) && ($get['subject']) ? $get['subject'] : 0;
		if ($subject == 0) {
			return get_generic_response(404, null, "subject not found!");
		}
		$message = isset($get['message']) && ($get['message']) ? $get['message'] : 0;
		if ($message == 0) {
			return get_generic_response(404, null, "message not found!");
		}

		$action_value = isset($get['action_value']) && ($get['action_value']) ? $get['action_value'] : '';
		
		// $action_url = isset($get['action_url']) && ($get['action_url']) ? $get['action_url'] : '';
  
		$notification_type = 1;
		$notifier_history_id = 1;

		$toEmailCount = count($toEmail);
		for($i = 0; $i<($toEmailCount); $i++)
		{
			// echo $i+1;
			$params = array(    'method' => 'sendEmail', 
				'fromEmail' => $fromEmail,
				'fromName' => $fromName, 
				'fromUserId' => $fromUserId,
				'toEmail' => $toEmail[$i], 
				'toName' => $toName[$i],
				'toUserId' => $toUserId[$i], 
				'subject' => $subject,
				'message' => $message, 
				'action_value' => $action_value,
				'action_url' => $action_url,
				'notification_type' => 1                        
			);
			$callAPI = json_decode( CallAPI( 'GET', QUIKLRN_API_URL, $params ), true );
			var_dump($callAPI);
		}

		die;

	echo "<pre>";
	var_dump($aa);die;
}
function s3AccessUpload(){

	// Define the target directory
	$uploaddir = "../../../tmp/";
	// Get the file extension from the uploaded file
	$fileExtension = pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION);
	// Define the new filename (output) with the same extension
	$uploadfile = $uploaddir . "uploadedFile." . $fileExtension;
	// Get other parameters from the request
	$clgId = $_REQUEST['clgId'];
	$courseId = $_REQUEST['courseId'];
	$sectionId = $_REQUEST['sectionId'];
	$userId = $_REQUEST['userId'];
	$activityId = $_REQUEST['activityId'];
	// Uncomment this line if you need to generate a presigned URL or perform any other actions
	// Move the uploaded file to the target location
	if (move_uploaded_file($_FILES['uploadFile']['tmp_name'], $uploadfile)) 
	{
		echo "The file has been uploaded successfully as 'output.$fileExtension'.";
		$uploadFile = generateUploadedPresignedURL($clgId, $courseId, $sectionId, $userId,$uploadfile,$activityId,$fileExtension);
		var_dump($uploadfile);

		// echo json_encode($uploadFile);
	
	}else {
		echo "There was an error uploading the file.";
	}

}
function getListOffiles(){
	$clgId = $_REQUEST['clgId'];
	$courseId = $_REQUEST['courseId'];
	$sectionId = $_REQUEST['sectionId'];
	$userId = $_REQUEST['uId'];
	$activityId = $_REQUEST['activityId'];
	listFilesForUser($clgId, $courseId, $sectionId,$activityId, $userId);
}

function listFilesForUser1(){
	
	$clgId = $_REQUEST['clgId'];
	$courseId = $_REQUEST['courseId'];
	$sectionId = $_REQUEST['sectionId'];
	$userId = $_REQUEST['userId'];
	$activityId = $_REQUEST['activityId'];

	$credentials = [
		'key' => 'AKIA4ROQEOUP4XZNNHHA',
		'secret' => '05KHd2piuTd/mGWC/SJcqxNQ59zes5MG/p/A9zSH',
	];

	$bucket = 'quiklrnreports'; // Your S3 bucket name
	$region = 'ap-south-1'; // Your region

	$s3 = new S3Client([
		'version' => 'latest',
		'region' => $region,
		'credentials' => $credentials,
	]);

	// Define the folder prefix to look for files by user ID
	$prefix = $clgId . '/' . $courseId . '/' . $sectionId . '/'. '/' . $activityId . '/'.  $userId . '/';

	try 
	{   // List objects in the specified folder (user's directory)
		$result = $s3->listObjectsV2([
			'Bucket' => $bucket,
			'Prefix' => $prefix,  // List objects in the folder for this user
			'Delimiter' => '/',   // Use '/' to simulate folder structure
		]);
	
			// Check if objects exist
		if (isset($result['Contents']) && count($result['Contents']) > 0) {
			echo "<h2>Files for User ID: $userId</h2>";
			echo "<table border='1'>
					<tr>
						<th>File Name</th>
						<th>Download Link</th>
					</tr>";
			
			$fileIndex = 1; // Counter to rename files as file1, file2, etc.
			
			foreach ($result['Contents'] as $object) {
				// Get the key (filename) of each file
				$key = $object['Key'];
				$fileName = "file" . $fileIndex++; // Rename files as file1, file2, file3, etc.

				// Generate pre-signed URL for the file to allow downloading
				$cmd = $s3->getCommand('GetObject', [
					'Bucket' => $bucket,
					'Key' => $key,
				]);
				
				// Set the expiration time to 5 minutes (300 seconds)
				$expiration = '+1 minutes'; // 5 minutes expiration
				// '+7 days'
				// Create pre-signed URL for the file (valid for 7 days in this case)
				$request = $s3->createPresignedRequest($cmd, $expiration);
				$presignedUrl = (string) $request->getUri();

				// Output the file name and download link in a table row
				echo "<tr>
						<td>$fileName</td>
						<td><a href='$presignedUrl' target='_blank'>Download</a></td>
					</tr>";
			}

			echo "</table>";
		} else {
			echo "No files found for this user.";
		}

	} catch (AwsException $e) {
		// Handle any errors that occurred during the API request
		echo "Error listing files: " . $e->getMessage();
	}

}

// function listFilesForUser(){
// 	die('aa');
// }


?>
