<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Aws\S3\S3Client;
//use Aws\Credentials\Credentials;
use Aws\Exception\AwsException;
class Site extends CI_Controller {

public function addchapter(){
	
		$data = $this->input->post();
		$data["id"] = time();
		settype($data["id"], "string");
		$s3Client = S3Client::factory([
			'region'  => 'us-east-2',
			'version' => 'latest',
			'key'     => 'AKIAVWABJW5WS3RJEIMB',
			'secret'  => 'TXyMsGXyAhOkw1lyo+22DV1SGBStLgDzr6ERkvOB',
			'signature' => 'v4', 
		]);
		// AWS S3 credentials and config
	
		$bucket = 'athletesedge'; // Replace with your bucket name
		
		
		
		if ($_FILES['video']['tmp_name'] != '') {
	
			// Upload the video to S3
			$videoPath = $_FILES['video']['tmp_name'];
			$videoName = uniqid() . "_" . $_FILES['video']['name'];
	
			try {
				$result = $s3Client->putObject([
					'Bucket' => $bucket,
					'Key'    =>  $videoName, // Video file path in S3
					'SourceFile' => $videoPath,
				//	'ACL'    => 'public-read', // Optional: set the file to be publicly accessible
				]);
				$data['videoUrl'] = $result['ObjectURL'];
				$data['VideoServerUrl']= "https://stream.edgetrac.com/videos/".$videoName;
	
				// Get video duration (you may need to use a library to fetch video metadata)
				$videoInfo = $this->getVideoInfo($videoPath);
				$data['duration'] = (float) $videoInfo['duration'];
				$thumbnailPath = $videoInfo['thumbnail'];
	
				// Upload the thumbnail to S3
				try {
					$thumbnailName = uniqid() . ".jpg"; // Use your desired thumbnail file name
					$resultThumbnail = $s3Client->putObject([
						'Bucket' => $bucket,
						'Key'    =>  $thumbnailName,
						'SourceFile' => $thumbnailPath,
				//		'ACL'    => 'public-read', // Optional: set the file to be publicly accessible
					]);
					$data['thumbnailUrl'] = $resultThumbnail['ObjectURL']; // Get the URL of the uploaded thumbnail
	
					// Clean up local thumbnail file after upload
					if (file_exists($thumbnailPath)) {
						unlink($thumbnailPath);
					}
	
				} catch (AwsException $e) {
					print_r($e->getMessage());
					// Handle thumbnail upload error
	//				$this->session->set_flashdata('errormessage', 'Error uploading thumbnail: ' . $e->getMessage());
	//				redirect('course/viewcourse/' . $courseId);
				}
	
			} catch (AwsException $e) {
				// Handle video upload error
			//	$this->session->set_flashdata('errormessage', 'Error uploading video: ' . $e->getMessage());
			//	redirect('course/viewcourse/' . $courseId);
			print_r($e->getMessage());	
		}
			echo "<pre>";
			print_r($data);
			echo "</pre>";
			exit;
	
	
		} else {
		echo "File uploading issue, please try later";
	
		}
	}
	function getVideoInfo($videoPath) {
		$thumbnailPath = '/var/www/html/athletic/uploads/' . 'thumbnail_' . uniqid() . '.jpg';
	
		if (!file_exists($videoPath)) {
			throw new Exception("Video file not found: " . $videoPath);
		}
	
		$cmdDuration = "ffmpeg -i " . escapeshellarg($videoPath) . " 2>&1 | grep 'Duration' | awk '{print $2}' | tr -d ,";
		$duration = shell_exec($cmdDuration);
	
		if (empty($duration)) {
			throw new Exception("Unable to retrieve video duration. Ensure ffmpeg is installed and accessible.");
		}
	
		$durationParts = explode(":", trim($duration));
		$durationInSeconds = ($durationParts[0] * 3600) + ($durationParts[1] * 60) + (float)$durationParts[2];
	
		$cmdThumbnail = "ffmpeg -i " . escapeshellarg($videoPath) . " -ss 00:00:01.000 -vframes 1 " . escapeshellarg($thumbnailPath) . " 2>&1";
		exec($cmdThumbnail, $output, $returnVar);
	
		if ($returnVar !== 0 || !file_exists($thumbnailPath)) {
			throw new Exception("Thumbnail generation failed. ffmpeg output: " . implode("\n", $output));
		}
	
		return [
			'duration' => $durationInSeconds,
			'thumbnail' => $thumbnailPath,
		];
	}

}
?>