<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
class Course extends CI_Controller {
    function __construct()
 	{
	    parent::__construct();
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->model('common');
		$this->load->library('session');
		// $this->load->database();
		$this->load->library(array('form_validation','template'));
		define( 'API_ACCESS_KEY1', 'AAAAFqAjjzI:APA91bGlwApVaPeYiBww8P8N5vRKAqV5L2HMgC2lEtwS_9RdQfaK_9_SXoLfGJ9SJ3anynELX5gt-S8Vf8I-34QMkx84UB73LWIkI4j2pNeRzNhA3IG2F-JP9H3FRr-brdWU3Ht4DSUA');
	}

	public function index()   
	{

		$data["courses"] = $this->common->readdatafromcollectionbetween("Courses");
		$this->template->template_render('courses', $data); 
	}
	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,
		];
	}
	
	
	public function addchapterdata(){
		$data = $this->input->post();
		$data["id"] = time();
		settype($data["id"], "string");
	
		// AWS S3 credentials and config
		$s3Client = new S3Client([
			'region'  => 'us-east-1', // Replace with your AWS region
			'version' => 'latest',
			'credentials' => [
				'key'    => 'AKIAVWABJW5WS3RJEIMB',
				'secret' => 'TXyMsGXyAhOkw1lyo+22DV1SGBStLgDzr6ERkvOB',
			],
		]);
	
		$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'    => 'videos/' . $videoName, // Video file path in S3
					'SourceFile' => $videoPath,
					'ACL'    => 'public-read', // Optional: set the file to be publicly accessible
				]);
				$data['videoUrl'] = $result['ObjectURL']; // Get the URL of the uploaded video
	
				// 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'    => 'thumbnails/' . $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) {
					// 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);
			}
			echo "<pre>";
			print_r($data);
			echo "</pre>";
			exit;
	
			// Save chapter data to database
			$courseId = $this->input->post('courseId');
			$this->common->adddatamodel("Chapters", $data["id"], $data);
			$this->session->set_flashdata('successmessage', 'New Chapter added successfully');
			redirect('course/viewcourse/' . $courseId);
	
		} else {
			$courseId = $this->input->post('courseId');
			$this->session->set_flashdata('errormessage', 'File uploading issue, please try later');
			redirect('course/viewcourse/' . $courseId);
		}
	}

public function addchapterdatawithfirebasestorage(){
	$data=$this->input->post();
	$data["id"] = time();
	settype($data["id"], "string");
	$firebase = $this->firebase->init();
	$storage = $firebase->createStorage();
	$defaultBucket = $storage->getBucket();

	if ($_FILES['video']['tmp_name'] != '') {
		
		$uploadedFile = $defaultBucket->upload(
			file_get_contents($_FILES['video']['tmp_name']),
			[
				'name' => "videos/" . uniqid() . "_" . $_FILES['video']['name'],
			]
		);
		$data['videoUrl'] = $uploadedFile->info()['mediaLink'];

//		echo "Video file path: " . $_FILES['video']['tmp_name'];
		$videoInfo = $this->getVideoInfo($_FILES['video']['tmp_name']);
		$data['duration'] = (float) $videoInfo['duration'];
		$thumbnailPath = $videoInfo['thumbnail'];
		$thumbnailFile = $defaultBucket->upload(
			file_get_contents($thumbnailPath),
			[
				'name' => "thumbnails/" . uniqid() . ".jpg",
			]
		);
		$data['thumbnailUrl'] = $thumbnailFile->info()['mediaLink'];
		if (file_exists($thumbnailPath)) {
            unlink($thumbnailPath);
        }
		$courseId=$this->input->post('courseId');
		$this->common->adddatamodel("Chapters", $data["id"], $data);
		$this->session->set_flashdata('successmessage', 'New Chapter added successfully');
		redirect('course/viewcourse/'.$courseId);
	}else{
		$courseId=$this->input->post('courseId');
		$this->session->set_flashdata('errormessage', 'File uploading Issue please Try later');
		redirect('course/viewcourse/'.$courseId);
	}
}

/*
public function addchapterdata() {
    $data = $this->input->post();
    $courseId = $data['courseId'];
    $videoChunksDir = 'uploads/video_chunks/';
    $mergedVideoFile = 'uploads/videos/' . uniqid() . '.mp4';  // The final merged video file

    // Check if chunk data is received
    if (isset($_FILES['video']) && $_FILES['video']['tmp_name'] != '') {
        // Create a directory to store chunks if it doesn't exist
        if (!is_dir($videoChunksDir)) {
            mkdir($videoChunksDir, 0777, true);
        }

        // Get the chunk number and total chunks
        $chunkNumber = $this->input->post('chunkNumber');
        $totalChunks = $this->input->post('totalChunks');
        $chunkFileName = $videoChunksDir . 'chunk_' . $chunkNumber;

        // Move the chunk to the temporary directory
        move_uploaded_file($_FILES['video']['tmp_name'], $chunkFileName);

        // If this is the last chunk, merge all chunks into a single video file
        if ($chunkNumber == $totalChunks - 1) {
            // Merge all chunks into one file
            $this->mergeVideoChunks($videoChunksDir, $mergedVideoFile, $totalChunks);

            // After merging, you can upload the final video to your cloud storage
            $this->uploadToFirebase($mergedVideoFile, $courseId);

            // Clean up the chunk directory
            $this->deleteChunks($videoChunksDir);
            
            // Add chapter data to the database
            $this->common->adddatamodel("Chapters", $data["id"], $data);
            $this->session->set_flashdata('successmessage', 'New Chapter added successfully');
            redirect('course/viewcourse/'.$courseId);
        }

        echo json_encode(['status' => 'success']);
    } else {
        $this->session->set_flashdata('errormessage', 'File uploading Issue please Try later');
        redirect('course/viewcourse/'.$courseId);
    }
}
*/

private function mergeVideoChunks($chunksDir, $outputFile, $totalChunks) {
    // Assuming the video chunks are in order
    $chunkFiles = [];
    for ($i = 0; $i < $totalChunks; $i++) {
        $chunkFiles[] = $chunksDir . 'chunk_' . $i;
    }

    // Use ffmpeg to concatenate the video chunks
    $concatListFile = $chunksDir . 'concat_list.txt';
    file_put_contents($concatListFile, implode("\n", array_map(function($file) { return "file '$file'"; }, $chunkFiles)));

    // Run ffmpeg to merge the chunks
    exec("ffmpeg -f concat -safe 0 -i $concatListFile -c copy $outputFile");

    // Clean up
    unlink($concatListFile);
}

private function uploadToFirebase($filePath, $courseId) {
    $firebase = $this->firebase->init();
    $storage = $firebase->createStorage();
    $defaultBucket = $storage->getBucket();

    $uploadedFile = $defaultBucket->upload(
        file_get_contents($filePath),
        [
            'name' => "videos/" . uniqid() . ".mp4",
        ]
    );
    $data['videoUrl'] = $uploadedFile->info()['mediaLink'];

    // You can also process the video to get the thumbnail if necessary
}

private function deleteChunks($chunksDir) {
    foreach (glob($chunksDir . 'chunk_*') as $chunkFile) {
        unlink($chunkFile);  // Delete the chunk file
    }
}

public function updatepermotiondata($id){
		$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();
$data=$this->input->post();
if ($_FILES['file']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['file']['tmp_name']),
				[
					'name' => "permo" . rand() . time() . $_FILES['file']['name'],
				]
			);

			$data['url'] = $uploadedFile->info()['mediaLink'];
		}
		$data["startTime"] = strtotime($data["startTime"]) * 1000;
		$data["endTime"] = strtotime($data["endTime"]) * 1000;

		$data["promotions"] = $this->common->updatedatamodel("Promotions",$id,$data);
		$this->session->set_flashdata('successmessage', 'Promotion has been updated successfully');

		redirect('promotion');
	}
	
public function viewcourse($id){
	$data['id']=$id;
	$data['courseId']=$id;
	$data["courseinfo"] = $this->common->readdatadocument("Courses",$id);
	$data["quaizinfo"] = $this->common->readdatafromcollectionbetween2where("Quaiz","courseId","=",$id);
	$data["chapterinfo"] = $this->common->readdatafromcollectionbetween2where("Chapters","courseId","=",$id);
	$this->template->template_render('viewcourse', $data); 
}
//convertTimetohuman
public function deletequaiz($courseid,$quaizid){

		$this->common->deletedatamodel("Quaiz", $quaizid);
		$this->session->set_flashdata('successmessage', 'Quaiz Deleted');
		redirect(base_url().'course/viewcourse/'.$courseid);
		
}
public function updatequaizdata(){
	$post = $this->input->post();
	$id= $this->input->post('id');
	$courseId=$this->input->post('courseId');
	$this->common->updatedatamodel("Quaiz", $id, $post);
	$this->session->set_flashdata('successmessage', 'New Question added successfully');
	redirect('course/viewcourse/'.$courseId);

} 


public function quaizdata(){
	$post = $this->input->post();
	$post["id"] = time();
	settype($post["id"], "string");
	$courseId=$this->input->post('courseId');
	$this->common->adddatamodel("Quaiz", $post["id"], $post);
	$this->session->set_flashdata('successmessage', 'New Question added successfully');
	redirect('course/viewcourse/'.$courseId);
		
}
public function updatechapterdata(){
	$data=$this->input->post();
	$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();
		
	if ($_FILES['video']['tmp_name'] != '') {
		
		$uploadedFile = $defaultBucket->upload(
			file_get_contents($_FILES['video']['tmp_name']),
			[
				'name' => "videos/" . uniqid() . "_" . $_FILES['video']['name'],
			]
		);
		$data['videoUrl'] = $uploadedFile->info()['mediaLink'];

		$videoInfo = $this->getVideoInfo($_FILES['video']['tmp_name']);
		$data['duration'] = (float) $videoInfo['duration'];
		$thumbnailPath = $videoInfo['thumbnail'];


		
		$thumbnailFile = $defaultBucket->upload(
			file_get_contents($thumbnailPath),
			[
				'name' => "thumbnails/" . uniqid() . ".jpg",
			]
		);
		$data['thumbnailUrl'] = $thumbnailFile->info()['mediaLink'];
		if (file_exists($thumbnailPath)) {
            unlink($thumbnailPath);
        }
			$courseId=$this->input->post('courseId');
			$this->common->updatedatamodel("Chapters", $data["id"], $data);
			$this->session->set_flashdata('successmessage', ' Chapter updated successfully');
			redirect('course/viewcourse/'.$courseId);

		
	
		}else{
			$courseId=$this->input->post('courseId');
			$this->common->updatedatamodel("Chapters", $data["id"], $data);
			$courseId=$this->input->post('courseId');
			$this->session->set_flashdata('successmessage', ' Chapter updated successfully');
			redirect('course/viewcourse/'.$courseId);
		}
		


}
public function deletechapter($courseid,$quaizid){

	$this->common->deletedatamodel("Chapters", $quaizid);
	$this->session->set_flashdata('successmessage', 'Chapter Deleted Successfully');
	redirect(base_url().'course/viewcourse/'.$courseid);
	
}
	public function addcourse()
  {
    $data["categories"] = $this->common->readdatafromcollectionbetween("Categories");
    $data["teams"] = $this->common->readdatafromcollectionbetween("Teams");
	$data["coach"] = $this->common->readdatafromcollectionbetween("Coaches");
    
    $this->template->template_render('addcourse', $data);
  }
  public function editCourse($id){


	$data['id']=$id;
	$data["course"] = $this->common->readdatadocument("Courses",$id);
    $data["categories"] = $this->common->readdatafromcollectionbetween("Categories");
    $data["teams"] = $this->common->readdatafromcollectionbetween("Teams");
	$data["coach"] = $this->common->readdatafromcollectionbetween("Coaches");
	 $this->template->template_render('editcourse', $data); 
}
public function updatecoursedata(){
	$post = $this->input->post();
	$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();
$teams=array();
if($post['allowedFor']=="All Teams"){
	$teams=array();
}else{
	$teams=$post['allowedTeams'];
}
		$data = [
			'categoryId' => $post['categoryId'],
			'title' => $post['title'],
			'coachesId'=>$post['coachesId'],
			'isPro' => $post['isPro']?true:false,
			'rating' => 0,

			'description' => $post['description'],
			'allowedFor' => $post['allowedFor'],
			'allowedTeams' => $post['allowedTeams'],
			'id'=>$post["id"]
		  ];
		  if ($_FILES['image']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['image']['tmp_name']),
				[
					'name' => "Course/course" . rand() . time() . $_FILES['image']['name'],
				]
			);

			$data['Imageurl'] = $uploadedFile->info()['mediaLink'];
		}



		$this->common->updatedatamodel("Courses", $post["id"], $data);
	// echo "<pre>";
	// print_r($data);
	// echo "</pre>";
	// exit;


		$this->session->set_flashdata('successmessage', 'New Courses added successfully');
		redirect(base_url().'course/editCourse/'.$post["id"]);

		
}


	public function addcoursedata()   
	{
		$post = $this->input->post();
		
		$post["id"] = time();
		settype($post["id"], "string");

	$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();

if ($_FILES['image']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['image']['tmp_name']),
				[
					'name' => "Course/course" . rand() . time() . $_FILES['image']['name'],
				]
			);

			$post['Imageurl'] = $uploadedFile->info()['mediaLink'];
		}

		  $data = [
			'categoryId' => $post['categoryId'],
			'title' => $post['title'],
			'coachesId'=>$post['coachesId'],
			'isPro' => $post['isPro']?true:false,
			'rating' => 0,
			'createdDate' => time()*1000,

			'description' => $post['description'],
			'allowedFor' => $post['allowedFor'],
			'allowedTeams' => $post['allowedTeams'],
			'id'=>$post["id"],
			'Imageurl' => 	$post['Imageurl'],
		  ];
	
		 
		$this->common->adddatamodel("Courses", $post["id"], $data);
	
		$this->session->set_flashdata('successmessage', 'New Courses added successfully');
		redirect('course');
	}

public function mytest($id="111",$msg="new data",$type="promotion",$ntype="user"){
	$data["promotions"] = $this->common->readdatafromcollectionbetween2where("Users","userRole","=",$ntype,"token","!=","");
		$token=array();
		$userIdArray=array();
	


		foreach($data["promotions"] as $l=>$j){
			 if(!empty($j['token'])  && $j['token'] !=""){
			 	  $userIdArray[$l] = false;
			array_push($token, $j['token'])	; 	
			 }
	
		}
		// echo "<pre>";
		// print_r($token);

		$notification=$this->send_notification($token,"New Promotion",$msg,$id,$type);
// print_r($notification);
// echo "</pre>";
}

function send_notification($token_id,$title,$body,$id,$type){
	 
	$icon=base_url('uploads/logo.png');
	
	$finalPostArray = array('registration_ids' => $token_id,
								'notification' => array('body' => $body,
														'title' => $title,
														"image"=> $icon,
														   "sound"=> "sample4_out.caf"
													),
									'aps'=>array(
										"sound"=> "sample4_out.caf"
									),				
								"data"=> array("click_action"=> "FLUTTER_NOTIFICATION_CLICK",
												"type"=>$type,
												"id"=>$id,
												"sound"=> "sample4_out.caf", 
												"soundios"=> "sample4_out.caf",
												"vibrate"=> 1)); 
		
	
		
		
		$headers = array
				(
					'Authorization: key=' . API_ACCESS_KEY1,
					'Content-Type: application/json'
				);
	#Send Reponse To FireBase Server	
			$ch = curl_init();
			curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
			curl_setopt( $ch,CURLOPT_POST, true );
			curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
			curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
			curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
			curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $finalPostArray ) );
			$result['mystatus'] = curl_exec($ch );
			curl_close( $ch );
	#Echo Result Of FireBase Server
	//$result['firbasestatus']=$fields;
	return $result;
		}
	public function addPromotion()   
	{
		$data = $this->input->post();
		$data["id"] = time();
		$data["startTime"] = strtotime($data["startTime"]) * 1000;
		$data["endTime"] = strtotime($data["endTime"]) * 1000;
		$data["noOfTrips"] = (int)$data["noOfTrips"];
		$data["remainingRides"] = NULL;
		$data["rideModels"] = NULL;
		$data["type"] = "driver";
		settype($data["id"], "string");

	$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();

if ($_FILES['file']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['file']['tmp_name']),
				[
					'name' => "permo" . rand() . time() . $_FILES['file']['name'],
				]
			);

			$data['url'] = $uploadedFile->info()['mediaLink'];
		}


		$this->common->adddatamodel("Promotions", $data["id"], $data);
		$this->mytest($data["id"],$data['message'],'promotion',"driver");		
		
		$this->session->set_flashdata('successmessage', 'New Promotion added successfully');
		redirect('promotion');
	}

	public function deletePromotion($id)   
	{
		//$this->common->deletedatamodel("Promotions", $id);
		$data["courseinfo"] = $this->common->deletedatamodel("Courses",$id);

		$quaizinfo = $this->common->readdatafromcollectionbetween2where("Quaiz","courseId","=",$id);
		foreach($quaizinfo as $id=>$J){
			$this->common->deletedatamodel("Quaiz",$id);
		}
	
		$chapterinfo= $this->common->readdatafromcollectionbetween2where("Chapters","courseId","=",$id);
		foreach($chapterinfo as $id=>$J){
			$this->common->deletedatamodel("Chapters",$id);
		}

		$this->session->set_flashdata('successmessage', 'Course  Deleted');
		redirect('courses');
	}
	
	
}