<?php
function convert_filesize($bytes, $decimals = 2){
    $size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB');
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
}


error_reporting(0);
header('Content-Type: application/json;');
$test = $_GET['test'] == 1;

$get_url = $_GET['url'];
if ($get_url == null) {
    $print_false_xd = array();
    $print_false_xd['res']['text'] = "لینک نامعتبر";
    echo json_encode(['ok' => false,  'Results' => $print_false_xd], 448);
    die;
}

try {
    if($test) {
        //var_dump($get_url);
        //die;
    }
    
    $context = stream_context_create(['http'=>[ 'timeout' => 30]]);
    $params = ['key' => 'UQUtiEQiMqfpDxv105jlwhyoX5apvmmy', 'v'=>"$get_url"];
        
    $endpoint = "https://api3.haji-api.ir/sub/youtube/download";
    $url = $endpoint . '?' . http_build_query($params);
    
    $end_url = file_get_contents($url, false, $context);
    
    if($end_url === false)
        throw new Exception("Cannot access url to read contents.");    
    
    $serviceResultArray = json_decode($end_url,true);   
    
    if($test) {
        var_dump(!$serviceResultArray['success']);
        var_dump(!$serviceResultArray['result']);
        var_dump(!$serviceResultArray['result']['mp4']);
        var_dump($serviceResultArray['success']);
        var_dump($serviceResultArray['result']);
        var_dump($serviceResultArray['result']['mp4']);
        die;
    }
    
    if(!$serviceResultArray['success'] || !$serviceResultArray['result'] || !$serviceResultArray['result']['mp4'])
        throw new Exception("result is not success."); 
        

    $links = [];
    foreach($serviceResultArray['result']['mp4'] as $format)
    {
        $links [] = [
            'title' => $format['resolution'],
            'type' => 'video',
            'url' => $format['url']
        ];
    }
    foreach($serviceResultArray['result']['audios'] as $formats)
    {
        foreach($formats as $format)
        {
            $links [] = [
                'title' => $format['resolution'] . ' ('. $format['ext'] .')' . ' ' . convert_filesize($format['size'], 0),
                'type' => 'audio',
                'url' => $format['url']
            ];
        }
    }
    
    $resultnext = [
            'number' => 0,
            0 => [
                'caption' => $serviceResultArray['result']['title'] . '\r\n' . $serviceResultArray['result']['description'],
                'links' => $links,
            ]
        ];
        
    if($test) {
        var_dump($resultnext);
        die;
    }
    
    echo json_encode(['ok' => true, 'Results' => $resultnext], 448);
} 
catch (Exception $ex) 
{
    $print_false_xd = array();
    $print_false_xd['res']['text'] = "خطا در خواندن اطلاعات ، لینک ورودی را چک کنید یا مجددا امتحان کنید";
    echo json_encode(['ok' => false,  'Results' => $print_false_xd], 448);
    exit;
}
