<?php
App::uses('Ffmpeg', 'Lib');
App::uses('Utility', 'Lib');
//require_once ROOT . DS . 'app' . DS . 'Vendor' . DS . 'aws' . DS . 'autoload.php';
require_once ROOT . DS . 'app' . DS . 'Vendor'  . DS . 'vendor' . DS . 'autoload.php';
use Aws\S3\S3Client;
use Aws\MediaConvert\MediaConvertClient;
use Aws\Exception\AwsException;


class Aws
{

    private $s3;
    private static $instance = null;
    private function __construct()
    {
        $IAM_KEY = IAM_KEY;
        $IAM_SECRET = IAM_SECRET;

        // Set Amazon S3 Credentials
        $s3 = S3Client::factory(
            array(
                'credentials' => array(
                    'key' => $IAM_KEY,
                    'secret' => $IAM_SECRET
                ),
                'version' => 'latest',
                'region' => S3_REGION
            )
        );
        $this->s3 = $s3;
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new Aws();
        }
        return self::$instance;
    }
    function s3_video_upload($user_id, $param, $sound_details, $video_details, $duet)
    {


        $original_video_file_path = Utility::uploadOriginalVideoFileIntoTemporaryFolder($param, $user_id);




        if ($original_video_file_path['error'] > 0) {

            $error['code'] = 201;
            $error['msg'] = $original_video_file_path['msg'];

            echo json_encode($error);
            die();


        }
        $original_video_file_path = $original_video_file_path['msg'];

        $final_video = $original_video_file_path;
        if (count($video_details) > 0) {

            //duet feature

            $original_video_file_path = Ffmpeg::duet($final_video, $video_details['Video']['video'], $duet);
            $final_video = $original_video_file_path;



        }

        $gif = Ffmpeg::videoToGif($original_video_file_path, $user_id);
        $thumb =  Ffmpeg::videoToThumb($original_video_file_path, $user_id);
        $thumb_small = Utility::cropImage($thumb);





        if (count($sound_details) < 1) {
            $mp3_file_name = "";
            $mp3_file = Ffmpeg::convertVideoToAudio($final_video, $user_id);

            if ($mp3_file) {



                $mp3_file_name = "audio/" . basename($mp3_file);


                $output['audio'] = $mp3_file_name;

            } else {


                $output['audio'] = "";
            }

            $final_video_file_path = $final_video;
        } else {


            $mp3_file_name = "";
            $video_path_with_audio = Ffmpeg::mergeVideoWithSound($final_video, $sound_details['Sound']['audio']);
            $output['audio'] = "";
            $final_video_file_path = $video_path_with_audio;

        }




        $video_file_name = "video/" . basename($final_video_file_path);


        $gif_file_name = "gif/" .  basename($gif);


        $thumb_file_name = "thum/" .basename($thumb);


        $thumb_small_file_name = "thum/" . basename($thumb_small);




        // Set Amazon S3 Credentials
        $s3 = $this->s3;

        try {


            // Put on S3


            $upload_video = $s3->putObject(
                array(
                    'Bucket' => BUCKET_NAME,
                    'Key' => $video_file_name,
                    'ACL' => 'public-read',
                    'SourceFile' => $final_video_file_path,
                    'StorageClass' => 'REDUCED_REDUNDANCY'
                )
            );


            $upload_gif = $s3->putObject(
                array(
                    'Bucket' => BUCKET_NAME,
                    'Key' => $gif_file_name,
                    'ACL' => 'public-read',
                    'SourceFile' => $gif,
                    'StorageClass' => 'REDUCED_REDUNDANCY'
                )
            );

            $upload_thumb = $s3->putObject(
                array(
                    'Bucket' => BUCKET_NAME,
                    'Key' => $thumb_file_name,
                    'ACL' => 'public-read',
                    'SourceFile' => $thumb,
                    'StorageClass' => 'REDUCED_REDUNDANCY'
                )
            );

            $upload_small_thumb = $s3->putObject(
                array(
                    'Bucket' => BUCKET_NAME,
                    'Key' => $thumb_small_file_name,
                    'ACL' => 'public-read',
                    'SourceFile' => $thumb_small,
                    'StorageClass' => 'REDUCED_REDUNDANCY'
                )
            );

            if (strlen($mp3_file_name) > 2) {

                $upload_mp3 = $s3->putObject(
                    array(
                        'Bucket' => BUCKET_NAME,
                        'Key' => $mp3_file_name,
                        'ACL' => 'public-read',
                        'SourceFile' => $mp3_file,
                        'StorageClass' => 'REDUCED_REDUNDANCY'
                    )
                );

                $final_output['audio'] = $upload_mp3['ObjectURL'];
                unlink($mp3_file);

            } else {

                $final_output['audio'] = "";
            }
            $final_output['video'] = $upload_video['ObjectURL'];
            $final_output['gif'] = $upload_gif['ObjectURL'];
            $final_output['thum'] = $upload_thumb['ObjectURL'];
            $final_output['thum_small'] = $upload_small_thumb['ObjectURL'];



            Utility::unlinkFile($final_video);
            Utility::unlinkFile($gif);
            Utility::unlinkFile($thumb);
            Utility::unlinkFile($original_video_file_path);
            Utility::unlinkFile($thumb_small);


            return $final_output;

        } catch (S3Exception $e) {
            //echo $e->getMessage();
            if (strpos($e->getMessage(), "NoSuchBucket") != "") {

                echo $e->getMessage();
                define("s3_Error", "NoSuchBucket");
            } else
                if (strpos($e->getMessage(), "AccessDenied") != "") {
                    define("s3_Error", "AccessDenied");
                    echo $e->getMessage();
                }
        } catch (Exception $e) {
            echo $e->getMessage();


        }

        die();


    }


    function fileUploadToS3Multipart($file, $ext=null)
    {

        //$audio_data = base64_decode(end(explode(",", $base64)));
        $random_string = Utility::random_string(5);
        if(is_null($ext)){
            $type = $_FILES[$file]['type'];

            $ext_details = explode("/",$type);
            $ext = $ext_details[1];
            if($ext =="mpeg"){
                $ext = "mp3";
            }

        }
        $file_name = uniqid() . $random_string . "." . $ext;


        // Set Amazon S3 Credentials
        $s3 = $this->s3;


        try {


            if ($ext == "mp4") {



                $folder = 'videos/';
            } else   if ($ext == "jpg" || $ext == "jpeg" ||  $ext == "png" ||  $ext == "gif") {



                $folder = 'images/';

            }else   if ($ext == "pdf") {



                $folder = 'pdf/';

            }else   if ($ext == "mp3") {



                $folder = 'audio/';

            }else   if ($ext == "mpeg") {



                $folder = 'audio/';

            }
            $content_type = $_FILES[$file]['type'];

            $upload_file = $s3->createMultipartUpload(
                array(
                    'Bucket' => BUCKET_NAME,
                    'Key' => $folder . $file_name,
                    'ACL' => 'public-read',
                    //'Body' => $file,
                    'StorageClass' => 'REDUCED_REDUNDANCY',

                    'ContentType' => $content_type,
                    'Metadata' => array(
                        'Content-Type' => $content_type,
                        'Cache-Control' => 'max-age=31536000',
                        'x-amz-meta-uuid' => '14365123651274',
                        'x-amz-meta-tag' => 'some-tag'
                    )
                )
            );
            $uploadId = $upload_file['UploadId'];
            $temp_filename = $_FILES[$file]['tmp_name'];

            $file = fopen($temp_filename, 'r');
            $partNumber = 1;
            $partSize = 5 * 1024 * 1024; // 5 MB
            $parts = [];
            while (!feof($file)) {
                $body = fread($file, $partSize);
                $result = $s3->uploadPart([
                    'Bucket' => BUCKET_NAME,
                    'Key' => $folder . $file_name,
                    'UploadId' => $uploadId,
                    'PartNumber' => $partNumber,
                    'StorageClass' => 'REDUCED_REDUNDANCY',
                    'Body' => $body,
                    'ContentType' => $content_type,
                    'ACL' => 'public-read',
                ]);
                $parts[] = [
                    'PartNumber' => $partNumber,
                    'ETag' => $result['ETag'],
                ];
                $partNumber++;
            }
            fclose($file);

            $result = $s3->completeMultipartUpload([
                'Bucket' => BUCKET_NAME,
                'Key' => $folder . $file_name,
                'UploadId' => $uploadId,
                'ACL' => 'public-read',
                'ContentType' => $content_type,
                'StorageClass' => 'REDUCED_REDUNDANCY',
                'MultipartUpload' => [
                    'Parts' => $parts,
                ],
                'Metadata' => array(
                    'Content-Type' => $content_type,
                    'Cache-Control' => 'max-age=31536000',
                    'x-amz-meta-uuid' => '14365123651274',
                    'x-amz-meta-tag' => 'some-tag'
                )
            ]);



            $code = 200;
            $msg = $upload_file['Key'];


        } catch (S3Exception $e) {
            //echo $e->getMessage();
            if (strpos($e->getMessage(), "NoSuchBucket") != "") {

                echo $e->getMessage();
                define("s3_Error", "NoSuchBucket");

                $code = 201;
                $msg = "No such Bucket exist";
            } else
                if (strpos($e->getMessage(), "AccessDenied") != "") {
                    define("s3_Error", "AccessDenied");
                    echo $e->getMessage();

                    $code = 201;
                    $msg = "Access Denied of aws bucket";
                }
        } catch (Exception $e) {
            // echo $e->getMessage();

            $code = 201;
            $msg = "some invalid error in aws";

        }


        $final_output['code'] = $code;
        $final_output['msg'] = $msg;
        return $final_output;

    }



    function fileUploadToS3($file, $ext,$folderparam = false)
    {


        $ext = pathinfo($file, PATHINFO_EXTENSION);

        $random_string = Utility::random_string(5);
        $file_name = uniqid() . $random_string . "." . $ext;



        $s3 =$this->s3;


        try {



            if ($ext == "mp3") {


                $content_type = 'audio/mpeg';
                $folder = 'audio/';
            } else   if ($ext == "png") {

                $content_type = 'image/png';
                $folder = 'images/';
            }else if ($ext == "gif") {

                $content_type = 'image/gif';
                $folder = 'profile/';
            }else if ($ext == "mp4") {

                $content_type = 'video/mp4';
                $folder = 'video/';


            }else{


                $content_type = 'image/jpeg';
                $folder = 'thum/';

            }

            if(!$folderparam){

                $folder = "profile/";

            }



            if($ext == "gif"){

                $upload_file = $s3->putObject(
                    array(
                        'Bucket' => BUCKET_NAME,
                        'Key' => $folder.$file_name,
                        'ACL' => 'public-read',
                        'SourceFile' => $file,
                        'StorageClass' => 'REDUCED_REDUNDANCY'
                    )
                );

            }else {
                $upload_file = $s3->putObject(
                    array(
                        'Bucket' => BUCKET_NAME,
                        'Key' => $folder . $file_name,
                        'ACL' => 'public-read',
                        //'Body' => $file,
                        'SourceFile' => $file,
                        'StorageClass' => 'REDUCED_REDUNDANCY',
                        'ContentType' => $content_type
                    )
                );
            }

            //  $final_output['audio'] = $upload_file['ObjectURL'];
            $code = 200;
            $msg = $upload_file['ObjectURL'];


        } catch (S3Exception $e) {
            //echo $e->getMessage();
            if (strpos($e->getMessage(), "NoSuchBucket") != "") {

                echo $e->getMessage();
                define("s3_Error", "NoSuchBucket");

                $code = 201;
                $msg = "No such Bucket exist";
            } else
                if (strpos($e->getMessage(), "AccessDenied") != "") {
                    define("s3_Error", "AccessDenied");
                    echo $e->getMessage();

                    $code = 201;
                    $msg = "Access Denied of aws bucket";
                }
        } catch (Exception $e) {
            // echo $e->getMessage();

            $code = 201;
            $msg = "some invalid error in aws";

        }


        $final_output['code'] = $code;
        $final_output['msg'] = $msg;
        return $final_output;

    }
    function fileUpload($file, $ext,$folderparam = false)
    {
        //$ext = pathinfo($file, PATHINFO_EXTENSION);
        //$audio_data = base64_decode(end(explode(",", $base64)));
        $random_string = Utility::random_string(5);

        $file_name = uniqid() . $random_string . "." . $ext;
        $IAM_KEY = IAM_KEY;
        $IAM_SECRET = IAM_SECRET;

        // Set Amazon S3 Credentials
        $s3 = $this->s3;


        try {

            if($ext == "mp3"){
                $content_type = 'audio/mpeg';
                $folder = 'audio/';

            }else
                if($ext == "png"){
                    $content_type = 'image/png';
                    $folder = 'thum/';

                }else if($ext == "mp4"){
                    $content_type = 'video/mp4';
                    $folder = 'video/';

                }





            $upload_file = $s3->putObject(
                array(
                    'Bucket' => BUCKET_NAME,
                    'Key' => $folder . $file_name,
                    'ACL' => 'public-read',
                    'Body' => $file,
                    //'SourceFile' => $file,
                    'StorageClass' => 'REDUCED_REDUNDANCY',
                    'ContentType' => $content_type
                )
            );


            //  $final_output['audio'] = $upload_file['ObjectURL'];
            $code = 200;
            $msg = $upload_file['ObjectURL'];


        } catch (S3Exception $e) {
            //echo $e->getMessage();
            if (strpos($e->getMessage(), "NoSuchBucket") != "") {

                echo $e->getMessage();
                define("s3_Error", "NoSuchBucket");

                $code = 201;
                $msg = "No such Bucket exist";
            } else
                if (strpos($e->getMessage(), "AccessDenied") != "") {
                    define("s3_Error", "AccessDenied");
                    echo $e->getMessage();

                    $code = 201;
                    $msg = "Access Denied of aws bucket";
                }
        } catch (Exception $e) {
            // echo $e->getMessage();

            $code = 201;
            $msg = "some invalid error in aws";

        }


        $final_output['code'] = $code;
        $final_output['msg'] = $msg;
        return $final_output;

    }




    function testFileUploadToS3($file)
    {


        $IAM_KEY = IAM_KEY;
        $IAM_SECRET = IAM_SECRET;

        // Set Amazon S3 Credentials
        $s3 = $this->s3;


        try {


            $upload_file = $s3->putObject(
                array(
                    'Bucket' => BUCKET_NAME,
                    'Key' => "thum/test.png",
                    'ACL' => 'public-read',
                    'SourceFile' => $file,
                    'StorageClass' => 'REDUCED_REDUNDANCY',
                    'ContentType' => 'image/jpeg'
                )
            );


            //  $final_output['audio'] = $upload_file['ObjectURL'];
            $code = 200;
            $msg = $upload_file['ObjectURL'];


        } catch (S3Exception $e) {
            //echo $e->getMessage();
            if (strpos($e->getMessage(), "NoSuchBucket") != "") {

                echo $e->getMessage();
                define("s3_Error", "NoSuchBucket");

                $code = 201;
                $msg = "No such Bucket exist";
            } else
                if (strpos($e->getMessage(), "AccessDenied") != "") {
                    define("s3_Error", "AccessDenied");
                    echo $e->getMessage();

                    $code = 201;
                    $msg = "Access Denied of aws bucket";
                }
        } catch (Exception $e) {
            // echo $e->getMessage();

            $code = 201;
            $msg = $e->getMessage();

        }


        $final_output['code'] = $code;
        $final_output['msg'] = $msg;
        return $final_output;

    }


    function profileImageToS3($file,$extension)
    {

        $random_string = Utility::random_string(5);
        $file_name = uniqid() . $random_string . "." . $extension;
        $IAM_KEY = IAM_KEY;
        $IAM_SECRET = IAM_SECRET;

        // Set Amazon S3 Credentials
        $s3 = $this->s3;


        try {

            if($extension == "png") {

                $upload_file = $s3->putObject(
                    array(
                        'Bucket' => BUCKET_NAME,
                        'Key' => "profile/$file_name",
                        'ACL' => 'public-read',
                        'SourceFile' => $file,
                        'StorageClass' => 'REDUCED_REDUNDANCY',
                        'ContentType' => 'image/png'
                    )
                );

            }else{

                $upload_file = $s3->putObject(
                    array(
                        'Bucket' => BUCKET_NAME,
                        'Key' => "profile/$file_name",
                        'ACL' => 'public-read',
                        'SourceFile' => $file,
                        'StorageClass' => 'REDUCED_REDUNDANCY',
                        //'ContentType' => 'image/png'
                    )
                );

            }
            //  $final_output['audio'] = $upload_file['ObjectURL'];
            $code = 200;
            $msg = $upload_file['ObjectURL'];


        } catch (S3Exception $e) {
            //echo $e->getMessage();
            if (strpos($e->getMessage(), "NoSuchBucket") != "") {

                echo $e->getMessage();
                define("s3_Error", "NoSuchBucket");

                $code = 201;
                $msg = "No such Bucket exist";
            } else
                if (strpos($e->getMessage(), "AccessDenied") != "") {
                    define("s3_Error", "AccessDenied");
                    echo $e->getMessage();

                    $code = 201;
                    $msg = "Access Denied of aws bucket";
                }
        } catch (Exception $e) {
            // echo $e->getMessage();

            $code = 201;
            $msg = $e->getMessage();

        }


        $final_output['code'] = $code;
        $final_output['msg'] = $msg;
        return $final_output;

    }

    function addSticker($file,$extension)
    {

        $random_string = Utility::random_string(5);
        $file_name = uniqid() . $random_string . "." . $extension;
        $IAM_KEY = IAM_KEY;
        $IAM_SECRET = IAM_SECRET;

        // Set Amazon S3 Credentials
        $s3 = $this->s3;


        try {

            if($extension == "png") {

                $upload_file = $s3->putObject(
                    array(
                        'Bucket' => BUCKET_NAME,
                        'Key' => "sticker/$file_name",
                        'ACL' => 'public-read',
                        'SourceFile' => $file,
                        'StorageClass' => 'REDUCED_REDUNDANCY',
                        'ContentType' => 'image/png'
                    )
                );

            }else{

                $upload_file = $s3->putObject(
                    array(
                        'Bucket' => BUCKET_NAME,
                        'Key' => "sticker/$file_name",
                        'ACL' => 'public-read',
                        'SourceFile' => $file,
                        'StorageClass' => 'REDUCED_REDUNDANCY',
                        //'ContentType' => 'image/png'
                    )
                );

            }
            //  $final_output['audio'] = $upload_file['ObjectURL'];
            $code = 200;
            $msg = $upload_file['ObjectURL'];


        } catch (S3Exception $e) {
            //echo $e->getMessage();
            if (strpos($e->getMessage(), "NoSuchBucket") != "") {

                echo $e->getMessage();
                define("s3_Error", "NoSuchBucket");

                $code = 201;
                $msg = "No such Bucket exist";
            } else
                if (strpos($e->getMessage(), "AccessDenied") != "") {
                    define("s3_Error", "AccessDenied");
                    echo $e->getMessage();

                    $code = 201;
                    $msg = "Access Denied of aws bucket";
                }
        } catch (Exception $e) {
            // echo $e->getMessage();

            $code = 201;
            $msg = $e->getMessage();

        }


        $final_output['code'] = $code;
        $final_output['msg'] = $msg;
        return $final_output;

    }




   

    function deleteObjectS3($video_url)
    {


        $pieces = explode('/', $video_url);

        $count = count($pieces);

        $key_name = $pieces[$count-1];
        $directory = $pieces[$count-2];


        if (count($pieces) > 0) {

            $IAM_KEY = IAM_KEY;
            $IAM_SECRET = IAM_SECRET;



            // Set Amazon S3 Credentials
            $s3 = $this->s3;
            try {


                $result = $s3->deleteObject([
                    'Bucket' => BUCKET_NAME,
                    'Key' => $directory."/".$key_name
                ]);



                $deleteMarker = (bool)$result->get('DeleteMarker');

                if ($deleteMarker) {

                    return true;
                } else {

                    return false;
                }
            } catch (S3Exception $e) {
                return false;
            }
        } else {

            return false;
        }

    }

    function renameS3File($new_file_key,$old_file_key){
        $IAM_KEY = IAM_KEY;
        $IAM_SECRET = IAM_SECRET;



        // Set Amazon S3 Credentials
        $s3 = $this->s3;

        try {
            // Copy the object to a new location
            $result = $s3->copyObject([
                'Bucket'     => BUCKET_NAME,
                'CopySource' => BUCKET_NAME."/video/$new_file_key",
                'Key'        => "video/$old_file_key",
            ]);

            // If the copy was successful, delete the original object
            if ($result) {
                $s3->deleteObject([
                    'Bucket' => BUCKET_NAME,
                    'Key'    => "video/$new_file_key",
                ]);

                return true;
            }
        } catch (AwsException $e) {
            // Output error message if fails
            echo $e->getMessage();
            echo "\n";
        }
    }


    function s3FilePermission($key){


        $IAM_KEY = IAM_KEY;
        $IAM_SECRET = IAM_SECRET;

        // Set Amazon S3 Credentials
        $s3 = $this->s3;



// Upload the file to S3 with public-read ACL
        $result = $s3->putObject([
            'Bucket' => BUCKET_NAME,
            'Key'    => $key,
            'ACL'    => 'public-read', // This makes the object publicly accessible
        ]);
    }
    static function transcodeVideo($name){
        $onlyname = pathinfo($name, PATHINFO_FILENAME);

        $IAM_KEY = IAM_KEY;
        $IAM_SECRET = IAM_SECRET;



// Set up AWS credentials and region
        $credentials = new Aws\Credentials\Credentials($IAM_KEY, $IAM_SECRET);
        $region = S3_REGION; // Change this to your desired region

// Create a MediaConvert client
        $mediaConvert = new MediaConvertClient([
            'version' => 'latest',
            'region' => $region,
            'credentials' => $credentials
        ]);



// Define the job settings from the provided JSON data
        $jobSettings = [
            // "Queue" => "arn:aws:mediaconvert:us-west-2:730335416723:queues/Default",
            "Role" => "arn:aws:iam::730335416723:role/service-role/MediaConvert_Default_Role",
            "Settings" => [
                "TimecodeConfig" => [
                    "Source" => "ZEROBASED"
                ],
                "OutputGroups" => [
                    [
                        "Name" => "File Group",
                        "Outputs" => [
                            [
                                "ContainerSettings" => [
                                    "Container" => "MP4",
                                    "Mp4Settings" => [
                                        "CslgAtom" => "INCLUDE",
                                        "FreeSpaceBox" => "EXCLUDE",
                                        "MoovPlacement" => "PROGRESSIVE_DOWNLOAD"
                                    ]
                                ],
                                "VideoDescription" => [
                                    //"Width" => 1080, // set appropriate width
                                    //"Height" => 1920, // set appropriate height
                                    "CodecSettings" => [
                                        "Codec" => "H_264",
                                        "H264Settings" => [
                                            "MaxBitrate" => 5000000,
                                            "QualityTuningLevel" => "MULTI_PASS_HQ",
                                            "QvbrSettings" => [
                                                "QvbrQualityLevel" => 8 // Adjust QVBR quality level (1-10)
                                            ],
                                            "RateControlMode" => "QVBR",
                                            "SceneChangeDetect" => "TRANSITION_DETECTION"
                                        ]
                                    ]
                                ],
                                "AudioDescriptions" => [
                                    [
                                        "CodecSettings" => [
                                            "Codec" => "AAC",
                                            "AacSettings" => [
                                                "Bitrate" => 96000,
                                                "CodingMode" => "CODING_MODE_2_0",
                                                "SampleRate" => 48000
                                            ]
                                        ]
                                    ]
                                ],
                                "NameModifier" => "_1"
                            ]
                        ],
                        "OutputGroupSettings" => [
                            "Type" => "FILE_GROUP_SETTINGS",
                            "FileGroupSettings" => [
                                "Destination" => "s3://foodtok/video/"
                            ]
                        ]
                    ],

                ],
                "FollowSource" => 1,
                "Inputs" => [
                    [
                        "AudioSelectors" => [
                            "Audio Selector 1" => [
                                "DefaultSelection" => "DEFAULT"
                            ]
                        ],
                        "VideoSelector" => [
                            "Rotate" => "AUTO"
                        ],
                        "TimecodeSource" => "ZEROBASED",
                        "FileInput" => "s3://foodtok/video/$name"
                    ]
                ]
            ],
            "BillingTagsSource" => "JOB",
            "AccelerationSettings" => [
                "Mode" => "DISABLED"
            ],
            "StatusUpdateInterval" => "SECONDS_60",
            "Priority" => 0
        ];


// Create a MediaConvert job
        try {
            $result = $mediaConvert->createJob($jobSettings);

            $jobId = $result["Job"]["Id"];

            $code = 200;
            $msg = $jobId;
        } catch (AwsException $e) {
            // echo $e->getMessage() . "\n";

            $code = 201;
            $msg = $e->getMessage();
        }

        $output['code'] = $code;
        $output['msg'] = $msg;
        return $output;





    }

    static function getVideoRotationInfo($filepath)
    {

        $command = "ffprobe -v quiet -select_streams v:0 -show_streams $filepath | grep -i rotation=";

        $output = exec($command);
        pr($output);
// Check and output the rotation metadata
        if ($output !== null) {
            return trim($output);

        }
    }
    static function getVideoResolution($filePath) {
        $cmd = "ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=s=x:p=0 " . escapeshellarg($filePath);
        $output = shell_exec($cmd);
        list($width, $height) = explode('x', trim($output));
        return ['width' => (int)$width, 'height' => (int)$height];
    }
    function transcodeAudio($name){
        $onlyname = pathinfo($name, PATHINFO_FILENAME);

        $IAM_KEY = IAM_KEY;
        $IAM_SECRET = IAM_SECRET;



// Set up AWS credentials and region
        $credentials = new Aws\Credentials\Credentials($IAM_KEY, $IAM_SECRET);
        $region = S3_REGION; // Change this to your desired region

// Create a MediaConvert client
        $mediaConvert = new MediaConvertClient([
            'version' => 'latest',
            'region' => $region,
            'credentials' => $credentials
        ]);



// Define the job settings from the provided JSON data
        $jobSettings = [
            "UserMetadata" => [],
            "Role" => "arn:aws:iam::730335416723:role/service-role/MediaConvert_Default_Role",
            "Settings" => [
                "TimecodeConfig" => [
                    "Source" => "ZEROBASED"
                ],
                "OutputGroups" => [
                    [
                        "Name" => "File Group",
                        "Outputs" => [
                            [
                                "ContainerSettings" => [
                                    "Container" => "RAW"
                                ],
                                "AudioDescriptions" => [
                                    [
                                        "AudioSourceName" => "Audio Selector 1",
                                        "CodecSettings" => [
                                            "Codec" => "AAC",
                                            "AacSettings" => [
                                                "Bitrate" => 96000,
                                                "CodingMode" => "CODING_MODE_2_0",
                                                "SampleRate" => 48000
                                            ]
                                        ]
                                    ]
                                ],
                                "Extension" => "mp3",
                                "NameModifier" => "1"
                            ]
                        ],
                        "OutputGroupSettings" => [
                            "Type" => "FILE_GROUP_SETTINGS",
                            "FileGroupSettings" => [
                                "Destination" => "s3://foodtok/audio/"
                            ]
                        ]
                    ]
                ],
                "FollowSource" => 1,
                "Inputs" => [
                    [
                        "AudioSelectors" => [
                            "Audio Selector 1" => [
                                "DefaultSelection" => "DEFAULT"
                            ]
                        ],
                        "VideoSelector" => [],
                        "TimecodeSource" => "ZEROBASED",
                        "FileInput" => "s3://foodtok/audio/$name"
                    ]
                ]
            ],
            "BillingTagsSource" => "JOB",
            "AccelerationSettings" => [
                "Mode" => "DISABLED"
            ],
            "StatusUpdateInterval" => "SECONDS_60",
            "Priority" => 0
        ];


// Create a MediaConvert job
        try {
            $result = $mediaConvert->createJob($jobSettings);

            $jobId = $result["Job"]["Id"];

            $code = 200;
            $msg = $jobId;
        } catch (AwsException $e) {
            // echo $e->getMessage() . "\n";

            $code = 201;
            $msg = $e->getMessage();
        }

        $output['code'] = $code;
        $output['msg'] = $msg;
        return $output;





    }











   









}