<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
require "app/Config/constant.php";

if(strlen(DEEPENGIN_KEY) < 3){

    die();
}

// Ensure the trailing slash is consistent
$baseUrl = BASE_URL;
$baseUrl = ensureTrailingSlash($baseUrl);

fetchAndCompressVideo($baseUrl);
function fetchAndCompressVideo($baseUrl)
{



    $apiUrl = $baseUrl."api/showVideosForCompressionAndQualityCron";
    $apiKey = API_KEY;

    // Step 1: Fetch video data
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array());
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "API-KEY: $apiKey"
    ]);

    $response = curl_exec($ch);
/*print_r($response);
die();*/
    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        error_log("Fetch API cURL error: $error_msg");
        curl_close($ch);
        return false;
    }

    curl_close($ch);

    $responseData = json_decode($response, true);

    if ($responseData['code'] !== 200 || empty($responseData['msg']['Video'])) {
       echo "Invalid response from API: " . print_r($response, true);
        return false;
    }

    $videoData = $responseData['msg']['Video'];
    $videoUrl = $videoData['video'];
    $videoId = $videoData['id'];

    if(isValidVideoUrl($videoUrl)){

      $result =   compressVideo($baseUrl,$videoUrl, $videoId);

      if(!$result){

          errorVideo($baseUrl,$videoId);
      }else if($result['code'] == 200){




           $result2 =    checkNudity($baseUrl,$videoUrl, $videoId);

          if($result2['code'] !== 200){

              errorVideo($baseUrl,$videoId);
          }
      }

    }else{

        errorVideo($baseUrl,$videoId);
    }
    // Step 2: Call the third-party API for compression



}

function compressVideo($base_url,$videoUrl, $videoId)
{
    $videoModerationUrl = DEEPENGIN_VIDEO_COMPRESSOR_URL;
    $key = DEEPENGIN_KEY;

    $data = [
        'id' => $videoId,
        'url' => $videoUrl,
        'api_key' => $key,
        'webhook' => $base_url . "api/videoCompressorUpdate"
    ];
    $data = json_encode($data);
   
    // Fire and forget cURL call
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $videoModerationUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // No need to wait for response
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data)
    ]);


    $response = curl_exec($ch);


    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
   return false;
    }

    curl_close($ch);
return json_decode($response,true);

}

function checkNudity($base_url,$videoUrl, $videoId)
{
    $video_moderation_url = DEEPENGIN_VIDEO_MODERATION_URL;
    $key = DEEPENGIN_KEY;

    $data = array(
        'id' => $videoId,
        'url' => $videoUrl,
        'api_key' => $key,
        'webhook' => $base_url."api/getVideoDetection"
    );
    $data = json_encode($data);
    //exec("curl -X POST -d '$data' $video_moderation_url > /dev/null 2>&1 &",$output);


// Initialize a cURL session
    $ch = curl_init();

// Set the cURL options
    curl_setopt($ch, CURLOPT_URL, $video_moderation_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data)
    ));
    // curl_setopt($ch, CURLOPT_TIMEOUT, 1); // set timeout to 1 second
    curl_setopt($ch, CURLOPT_NOSIGNAL, 1); // ignore signals
// Execute the cURL request and capture the output
    $response = curl_exec($ch);


// Check for errors
    if(curl_errno($ch)) {
        $error_msg = curl_error($ch);
        error_log("cURL error: " . $error_msg);
        return false;
    }
    return json_decode($response,true);
// Close the cURL session
    curl_close($ch);

}

function errorVideo($base_url, $videoId)
{
    $apiUrl = $base_url."api/errorVideo";
    $apiKey = API_KEY;


    $data = [
        'video_id' => $videoId,

    ];
    $data = json_encode($data);
    print_r($data);
    // Fire and forget cURL call
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // No need to wait for response
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "API-KEY: $apiKey"
    ]);


    $response = curl_exec($ch);


    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        echo "cURL error: $error_msg";
    }

    curl_close($ch);


}

function isValidVideoUrl($videoUrl)
{
    // Step 1: Check if the URL is valid
    if (!filter_var($videoUrl, FILTER_VALIDATE_URL)) {
        error_log("Invalid video URL: $videoUrl");
        return false;
    }

    // Step 2: Check if the file is an MP4
    $pathInfo = pathinfo($videoUrl);
    if (strtolower($pathInfo['extension']) !== 'mp4') {
       echo "Video is not an MP4 file: $videoUrl";
        return false;
    }

    // Step 3: Check if the video exists using a HEAD request


    return true;
}
function ensureTrailingSlash($url) {
    // Add a slash if it's not already present
    return rtrim($url, '/') . '/';
}

// Execute the function

?>