<?php
/**
 * Project:        M.VuiZ.Net
 * Author:         nampt.me <admin@vuiz.net>
 * Copyright:      © 2025 vuiz.net All rights reserved.
 */

require('YouTubeDownloader.php');

$link = isset($_POST['link']) ? htmlspecialchars(rawurldecode($_POST['link'])) : null;
$video_id = getYoutubeIdFromUrl($link);
$url = 'https://www.youtube.com/watch?v='.$video_id;
if (!$link && !preg_match('#https?://#is',$link) && !$video_id) {
	die(json_encode([
	    'error' => 'URL không hợp lệ!'
	], JSON_PRETTY_PRINT));
}

$youtube = new \YouTube\YouTubeDownloader();
$links = $youtube->getDownloadLinks($url);

$error = $youtube->getLastError();

echo json_encode([
    'success' => $links,
    'error' => $error
], JSON_PRETTY_PRINT);

function getYoutubeIdFromUrl($url) {
    $parts = parse_url($url);
    if(isset($parts['query'])){
        parse_str($parts['query'], $qs);
        if(isset($qs['v'])){
            return $qs['v'];
        }else if(isset($qs['vi'])){
            return $qs['vi'];
        }
    }
    if(isset($parts['path'])){
        $path = explode('/', trim($parts['path'], '/'));
        return $path[count($path)-1];
    }
    return false;
}