<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use YoutubeDl\Options;
use YoutubeDl\YoutubeDl;

class YoutubeDownloadController extends Controller
{
    public function index(Request $request)
    {
        $url = $request->get('videourl');
        $yt = new YoutubeDl();

        $collection = $yt->download(
            Options::create()
                ->downloadPath(env('PATH_TO_DOWNLOAD'))
                ->url($url)
                ->remuxVideo('mp4')
        );
        $videotitle = '';
        foreach ($collection->getVideos() as $video) {
            if ($video->getError() !== null) {
                $error = "Error downloading video: {$video->getError()}.";
                $response = new \stdClass();
                $response->error = $error;
                return response(json_encode($response));
            } else {
                $videotitle = $video->getFile()->getFilename(); // Will return Phonebloks
                // $video->getFile(); // \SplFileInfo instance of downloaded file
                //$file_path = public_path('/downloads/'.$videotitle);
                return redirect('/download/'.$videotitle);
                //return response()->download($file_path);
            }
        }
        $response = new \stdClass();
        $response->error = 'No video';
        return response(json_encode($response));
    }
}
