<?php
require_once 'functioncdr.php';

$json = file_get_contents('php://input');
$obj = json_decode($json);

//error_log("\n" . date('Y-m-d H:i:s') . " Incoming Request :\n $json ", 3, $destination);

$filename = $obj->{'filename'};
$audiod = $obj->{'audiod'};
$api_key = $obj->{'api_key'};

if($api_key == 'YTc4YWY3ZWVlZWViODU3YTY5ODUzNTA4ZGU3YzVhYzM1NTdjNjM1MWEyYzA1ODU1ZDhlqA12AjkP0qNTc4ZjU3N2QwMDVmMw==') {

try {
    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://41.221.51.92:8089/api',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        curl_setopt($curl, CURLOPT_VERBOSE, true),
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>'{
            "request": {
                "action": "challenge",
                "version": "1.0.25.9",
                "user": "cdruser"
            }
        }',
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Cookie: HttpOnly; CookieName=CookieValue; TRACKID=eb08b509b72dbbb05fe02f0d98916950; session-identify=sid88710864-1722432494'
        ),
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0, // Disable host verification
    ));

    $response = curl_exec($curl);

    $data = json_decode($response, true);

    //print_r($data);
// Extract the challenge value
    $challenge = $data['response']['challenge'];
    
    //echo "<br/>";
    $cookie=get_cookietpo($challenge);
    
    if (curl_errno($curl)) {
        throw new Exception('cURL error: ' . curl_error($curl));
    }

    curl_close($curl);

    

    
    //echo $cookie;

    try {
        $filePath = $filename;  // Ensure this directory exists and is writable
        doenload_fileaudio($cookie,$filePath,$audiod);
        
        $audioFileContent = file_get_contents($filePath);

        // Encode the file's contents to Base64
        $base64Audio = base64_encode($audioFileContent);



        $response = array(
            "status" => "200",
            "filename"=>$filePath,
            "filedata"=>$base64Audio
        );

        $response = json_encode($response);
        print_r($response);
        die(); 


    } catch (Exception $e) {
        $response = array(
            "status" => "201",
            "statusDesc" => $e->getMessage()      
        );
        $response = json_encode($response);
        print_r($response);
        die(); 
    }
    
   

} catch (Exception $e) {
    $response = array(
        "status" => "201",
        "statusDesc" => $e->getMessage()      
    );
    $response = json_encode($response);
    print_r($response);
}

}
else
{
    $response = array(
        "status" => "201",
        "statusDesc" => "Invalid API KEY"        
    );
    $response = json_encode($response);
    print_r($response);
    die(); 
}