<?php
include_once("config.php");
require 'vendor/autoload.php';

if (!empty($_GET['video_player'])) {
    $name = str_replace("https://techgroww.s3.ap-south-1.amazonaws.com/", "", $_POST['_name']);

    $name = str_replace("%20", " ", $name);

    $bucket = 'techgroww';

    $object = $name;
    $expiry = new DateTime("+10 minutes");

    $resourceKey = "https://d22jaj1x4zpoxb.cloudfront.net/{$object}";
    $expires = time() + 10 * 60; // 5 minutes (5 * 60 seconds) from now.
    $privateKey = dirname(__FILE__) . '/private/pk-APKAIE2MMGXVN6OAZUTQ.pem';
    $keyPairId = 'APKAIE2MMGXVN6OAZUTQ';

    $cloudFrontClient = new \Aws\CloudFront\CloudFrontClient([
        'profile' => 'default',
        'version' => 'latest',
        'region'  => 'ap-south-1',
    ]);

    try {
        $result = $cloudFrontClient->getSignedUrl([
            'url' => $resourceKey,
            'expires' => $expires,
            'private_key' => $privateKey,
            'key_pair_id' => $keyPairId
        ]);

        $url =  $result;
        if (!empty($url)) {
            echo json_encode(["key" => base64_encode(base64_encode(base64_encode($url)))]);
            die;
        }
    } catch (\Aws\Exception\AwsException $e) {
        return 'Error: ' . $e->getAwsErrorMessage();
    }
} else if (!empty($_GET['check_video'])) {
    $queryNew = $db->query("SELECT * FROM `converter` WHERE (`status` = 'pending' OR `status` = 'processing' ) ");
    $tdata = $db->fetch_all($queryNew);
    $dId = [];
    if(!empty($tdata)){
        foreach ($tdata as $key => $value) {
            
            $mediaConvertClient =  new \Aws\MediaConvert\MediaConvertClient([
                'version' => 'latest',
                'region' => 'ap-south-1',
                'profile' => 'default',
                'endpoint' => 'https://xnbzilj6c.mediaconvert.ap-south-1.amazonaws.com'
            ]);
            
            try {
                $result = $mediaConvertClient->getJob([
                    'Id' => $value['job_id'],
                ]);
                $stat = $result['Job']['Status'];
                if( $result['Job']['Status'] == "COMPLETE"){
                    $stat = "done";
                }

                if( $result['Job']['Status'] == "PROGRESSING"){
                    $stat = "processing";
                }
                
                $dId[$value['video_id']] = $result['Job']['Status'];
                $od = $value['id'];
                $id = $db->query("UPDATE `converter` SET `status` = '{$stat}' WHERE `converter`.`id` = {$od}");
             
            } catch (\Aws\Exception\AwsException $e) {
                // output error message if fails
                echo $e->getMessage();
                echo "\n";
            }
        }
       
    }
    if(!empty($dId)){
        echo json_encode(["status"=>true,"data"=>$dId]);die;
    }else{
        echo json_encode(["status"=>true,"interval"=>"stop"]);die;
    }
    
    
} else {

    $url = $_POST['url'];
    $id = $db->query("INSERT INTO media_upload ( `media_name`) VALUES ('{$url}')");
    $last_id =  $db->lastinssertId();

    if (!empty($id)) {
        $name = str_replace("http://techgroww.s3-ap-south-1.amazonaws.com/", "", $url);

        $name = str_replace("%20", " ", $name);

        $mediaConvertClient = new \Aws\MediaConvert\MediaConvertClient([
            'region' => 'ap-south-1',
            'profile' => 'default',
            'version' => 'latest',
            'endpoint' => 'https://xnbzilj6c.mediaconvert.ap-south-1.amazonaws.com'
        ]);
        $jobSetting = [
            "OutputGroups" => [
                [
                    "Name" => "File Group",
                    "OutputGroupSettings" => [
                        "Type" => "FILE_GROUP_SETTINGS",
                        "FileGroupSettings" => [
                            "Destination" => "s3://techgroww/MP4/{$name}"
                        ]
                    ],
                    "Outputs" => [
                        [
                            "VideoDescription" => [
                                "Width"=> 1280,
                                "Height"=> 720,
                                "ScalingBehavior" => "DEFAULT",
                                "TimecodeInsertion" => "DISABLED",
                                "AntiAlias" => "ENABLED",
                                "Sharpness" => 50,
                                "CodecSettings" => [
                                    "Codec" => "H_264",
                                    "H264Settings" => [
                                        "InterlaceMode" => "PROGRESSIVE",
                                        "NumberReferenceFrames" => 3,
                                        "Syntax" => "DEFAULT",
                                        "Softness" => 0,
                                        "GopClosedCadence" => 1,
                                        "GopSize" => 90,
                                        "Slices" => 1,
                                        "GopBReference" => "DISABLED",
                                        "SlowPal" => "DISABLED",
                                        "SpatialAdaptiveQuantization" => "ENABLED",
                                        "TemporalAdaptiveQuantization" => "ENABLED",
                                        "FlickerAdaptiveQuantization" => "DISABLED",
                                        "EntropyEncoding" => "CABAC",
                                        "Bitrate" => 5000000,
                                        "FramerateControl" => "SPECIFIED",
                                        "RateControlMode" => "CBR",
                                        "CodecProfile" => "MAIN",
                                        "Telecine" => "NONE",
                                        "MinIInterval" => 0,
                                        "AdaptiveQuantization" => "HIGH",
                                        "CodecLevel" => "AUTO",
                                        "FieldEncoding" => "PAFF",
                                        "SceneChangeDetect" => "ENABLED",
                                        "QualityTuningLevel" => "SINGLE_PASS",
                                        "FramerateConversionAlgorithm" => "DUPLICATE_DROP",
                                        "UnregisteredSeiTimecode" => "DISABLED",
                                        "GopSizeUnits" => "FRAMES",
                                        "ParControl" => "SPECIFIED",
                                        "NumberBFramesBetweenReferenceFrames" => 2,
                                        "RepeatPps" => "DISABLED",
                                        "FramerateNumerator" => 30,
                                        "FramerateDenominator" => 1,
                                        "ParNumerator" => 1,
                                        "ParDenominator" => 1
                                    ]
                                ],
                                "AfdSignaling" => "NONE",
                                "DropFrameTimecode" => "ENABLED",
                                "RespondToAfd" => "NONE",
                                "ColorMetadata" => "INSERT"
                            ],
                            "AudioDescriptions" => [
                                [
                                    "AudioTypeControl" => "FOLLOW_INPUT",
                                    "CodecSettings" => [
                                        "Codec" => "AAC",
                                        "AacSettings" => [
                                            "AudioDescriptionBroadcasterMix" => "NORMAL",
                                            "RateControlMode" => "CBR",
                                            "CodecProfile" => "LC",
                                            "CodingMode" => "CODING_MODE_2_0",
                                            "RawFormat" => "NONE",
                                            "SampleRate" => 48000,
                                            "Specification" => "MPEG4",
                                            "Bitrate" => 64000
                                        ]
                                    ],
                                    "LanguageCodeControl" => "FOLLOW_INPUT",
                                    "AudioSourceName" => "Audio Selector 1"
                                ]
                            ],
                            "ContainerSettings" => [
                                "Container" => "MP4",
                                "Mp4Settings" => [
                                    "CslgAtom" => "INCLUDE",
                                    "FreeSpaceBox" => "EXCLUDE",
                                    "MoovPlacement" => "PROGRESSIVE_DOWNLOAD"
                                ]
                            ],
                            "NameModifier" => "_1"
                        ]
                    ]
                ]
            ],
            "AdAvailOffset" => 0,
            "Inputs" => [
                [
                    "AudioSelectors" => [
                        "Audio Selector 1" => [
                            "Offset" => 0,
                            "DefaultSelection" => "NOT_DEFAULT",
                            "ProgramSelection" => 1,
                            "SelectorType" => "TRACK",
                            "Tracks" => [
                                1
                            ]
                        ]
                    ],
                    "VideoSelector" => [
                        "ColorSpace" => "FOLLOW"
                    ],
                    "FilterEnable" => "AUTO",
                    "PsiControl" => "USE_PSI",
                    "FilterStrength" => 0,
                    "DeblockFilter" => "DISABLED",
                    "DenoiseFilter" => "DISABLED",
                    "TimecodeSource" => "EMBEDDED",
                    "FileInput" => "s3://techgroww/{$name}"
                ]
            ],
            "TimecodeConfig" => [
                "Source" => "ZEROBASED"
            ]
        ];
        try {
            $result = $mediaConvertClient->createJob([
                "Role" => "arn:aws:iam::411193302502:role/service-role/MediaConvert_Default_Role",
                "Settings" => $jobSetting, //JobSettings structure
                "Queue" => "arn:aws:mediaconvert:ap-south-1:411193302502:queues/Default",
                "UserMetadata" => [
                    // "Customer" => "Amazon"
                ],
            ]);
            $jobId =  $result['Job']['Id'];
            $Status =  $result['Job']['Status'];
            $dd = json_encode($result);
            $mediId = $db->query("INSERT INTO converter ( `video_id`,`job_id`,`data`,`status`) VALUES ('{$last_id}','{$jobId}','{$dd}','pending')");
            echo json_encode(["status" => true]);
            die;
        } catch (\Aws\Exception\AwsException $e) {
            // output error message if fails
            echo $e->getMessage();
            echo "\n";
        }

        echo json_encode(["status" => true]);
        die;
    }
}
