<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Aws\S3\S3Client;
//use Aws\Credentials\Credentials;
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 uploadChunkWithChapterData() {
		$chunk = $this->input->post('chunk');
		$totalChunks = $this->input->post('totalChunks');
		$fileName = $this->input->post('fileName');
		$file = $_FILES['file']['tmp_name'];  
	
		$s3Client = S3Client::factory([
			'region'  => 'us-east-2',
			'version' => 'latest',
			'key'     => 'AKIAVWABJW5WS3RJEIMB',
			'secret'  => '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',
			'signature' => 'v4', 
		]);
	
		$uploadId = $this->session->userdata('upload_id');
		if (!$uploadId) {
			$result = $s3Client->createMultipartUpload([
				'Bucket' => 'athletesedge',
				'Key' => $fileName,
			]);
			$uploadId = $result['UploadId'];
			$this->session->set_userdata('upload_id', $uploadId);
			error_log("Created new upload ID: $uploadId");
		}
	
		try {
			$result = $s3Client->uploadPart([
				'Bucket' => 'athletesedge',
				'Key' => $fileName,
				'UploadId' => $uploadId,
				'PartNumber' => $chunk,
				'SourceFile' => $file,
			]);
	
			$etag = $result['ETag'];
			$uploadedParts = $this->session->userdata('uploaded_parts') ?? [];
			$uploadedParts[$chunk] = ['PartNumber' => (int)$chunk, 'ETag' => $etag];
			$this->session->set_userdata('uploaded_parts', $uploadedParts);
	
			if ((int)$chunk === (int)$totalChunks) {
				$parts = array_values($uploadedParts);
	
				if (count($parts) !== $totalChunks) {
					echo json_encode(['error' => 'Some parts are missing. Please retry upload.']);
					return;
				}
	
				$s3Client->completeMultipartUpload([
					'Bucket' => 'athletesedge',
					'Key' => $fileName,
					'UploadId' => $uploadId,
					'MultipartUpload' => ['Parts' => $parts],
				]);
	
				$fileUrl = "https://athletesedge.s3.us-east-2.amazonaws.com/$fileName";
				$this->session->unset_userdata(['upload_id', 'uploaded_parts']);
	
				$data = [
					'title' => $this->input->post('chapterTitle'),
					'description' => $this->input->post('description'),
					'videoUrl' => $fileUrl,
					'created_at' => date('Y-m-d H:i:s')
				];
	
				//$this->db->insert('Chapters', $data);
	
				echo json_encode(['status' => 'complete', 'fileUrl' => $fileUrl, 'data' => $data]);
			} else {
				echo json_encode(['status' => 'partial', 'chunk' => $chunk]);
			}
		} catch (AwsException $e) {
			if ($e->getAwsErrorCode() === 'NoSuchUpload') {
				$this->session->unset_userdata(['upload_id', 'uploaded_parts']);
				echo json_encode(['error' => 'Upload session expired or invalid. Please restart upload.']);
			} else {
				echo json_encode(['error' => $e->getMessage()]);
			}
		}
	}
	
	public function addchapterdata() {
		$data = $this->input->post();
		$data["id"] = time();
		settype($data["id"], "string");
	
		try {
			/*
			if (!empty($_FILES['video']['tmp_name'])) {
				// Get video path from uploaded file
				$videoPath = $_FILES['video']['tmp_name'];
	
				// Generate thumbnail and video duration
				$videoInfo = $this->getVideoInfo($videoPath);
				$data['duration'] = (float) $videoInfo['duration'];
				$thumbnailPath = $videoInfo['thumbnail'];
	
	
				// Upload thumbnail to S3
			
				$data['thumbnailUrl'] = $thumbnailUrl;
			}
				*/
			$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);	

		} catch (Exception $e) {
			log_message('error', 'Error in addchapterdata: ' . $e->getMessage());
			echo json_encode(['success' => false, 'error' => $e->getMessage()]);
		}
	}
	/*
	public function uploadBlobAndGenerateThumbnail() {
    // Check if a file is uploaded
    if (!isset($_FILES['file'])) {
        echo json_encode(['status' => 'error', 'error' => 'No file uploaded']);
        return;
    }

    $fileName = $this->input->post('fileName');
    if (!$fileName) {
        echo json_encode(['status' => 'error', 'error' => 'File name is required']);
        return;
    }
	echo json_encode(['status' => 'success', 'fileName' => $fileName,'file'=>$_FILES['file']]);
	exit;
	$videoInfo = $this->getVideoInfo($_FILES['file']['tmp_name']);
	$duration = (float) $videoInfo['duration'];
	$thumbnailPath = $videoInfo['thumbnail'];
//	$this->load->library('Aws_s3');
	// $bucket = 'athletesedge';
	// $thumbnailName = uniqid() . '_thumbnail.jpg';

	// $thumbnailUrl = $this->aws_s3->uploadFile(
	// 	$thumbnailPath,
	// 	$thumbnailName,
	// 	$bucket,
	// 	'image/jpeg'
	// );

    
    echo json_encode(['status' => 'success', 'thumbnailUrl' => $videoInfo,'file'=>$_FILES['file']]);
}
*/
public function uploadBlobAndGenerateThumbnail() {
    // Check if required parameters are provided
    $fileName = $this->input->post('fileName');
    $thumbnailBase64 = $this->input->post('file');

    if (empty($fileName) || empty($thumbnailBase64)) {
        $this->sendErrorResponse('File name and thumbnail data are required');
        return;
    }

    try {
        // Decode base64 thumbnail data
        $imageData = explode(',', $thumbnailBase64);
        $imageContent = base64_decode(end($imageData));

        if (!$imageContent) {
            throw new Exception('Invalid base64 image data');
			
        }

        // Define temporary file path
        $tempThumbnailPath = '/var/www/html/athletic/uploads/' . uniqid('thumbnail_') . '.jpg';

        // Save the decoded image to the server
        if (!file_put_contents($tempThumbnailPath, $imageContent)) {

			echo json_encode(['status' => 'error', 'message' => 'Failed to save the thumbnail.']);
		}

        // Load AWS S3 Library
        $this->load->library('Aws_s3');
        $bucket = 'athletesedge';

        // Define S3 thumbnail file name
        $thumbnailName = uniqid('thumbnail_') . '.jpg';

        // Upload to S3 and get the URL
        $thumbnailUrl = $this->aws_s3->uploadFile($tempThumbnailPath, $thumbnailName, $bucket, 'image/jpeg');

        if (!$thumbnailUrl) {
            throw new Exception('Failed to upload the thumbnail to S3');
        }

        // Clean up temporary file
        if (file_exists($tempThumbnailPath)) {
            unlink($tempThumbnailPath);
        }

		echo json_encode(['status' => 'success', 'thumbnailUrl' =>$thumbnailUrl]);
		exit;
 
    } catch (Exception $e) {
        // Handle errors and send error response
  
        $this->sendErrorResponse($e->getMessage());
		echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}

// Helper function to get video information including duration and thumbnail generation
function getVideoInfo2($videoPath) {
    $thumbnailPath = '/var/www/html/athletic/uploads/thumbnail_' . uniqid() . '.jpg';

    if (!file_exists($videoPath)) {
        throw new Exception("Video file not found: " . $videoPath);
    }


    // Generate the thumbnail
    $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' => 10,
        'thumbnail' => $thumbnailPath,
    ];
}

	
	
	public function addchapterdataold(){
		$data = $this->input->post();
		$data["id"] = time();
		settype($data["id"], "string");
	
		// AWS S3 credentials and config
		$s3Client = S3Client::factory([
			'region'  => 'us-east-2',
			'version' => 'latest',
			'key'     => 'AKIAVWABJW5WS3RJEIMB',
			'secret'  => 'TXyMsGXyAhOkw1lyo+22DV1SGBStLgDzr6ERkvOB',
			'signature' => 'v4', 
		]);
	
		$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) {
					// 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){
	echo "yes";
	exit;

		$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'],
			'contentType'=>$post['contentType'],
			'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'],
			'contentType' => $post['contentType'],
			'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');
	}
	
	
}
