<?php

namespace App\Http\Controllers;

use App\Jobs\ProcessDownload;
use App\Models\Download;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class VideoController extends Controller
{
    public function download($id) {
        $download = Download::find($id);
        $path = storage_path('files/'.$download->path);
        return response()->download($path);
    }

    public function all() {
        $download = Download::where('status', 'pending')->orderBy('created_at', 'asc')->first();
        if($download) {
            ProcessDownload::dispatch($download);
        }
        return response()->json(Download::all()->toArray());
    }

    public function removeAll(){
        foreach(array_diff(scandir(storage_path('files')), ['.', '..']) as $file) {
            if(!Download::where('path', $file)->first()) {
                unlink(storage_path("files/$file"));
            }
        }

        Download::query()->delete();
        return redirect('/');
    }

    public function add($uniqid){
        $name = request()->get('name');

        $download = Download::where('uniqid', $uniqid)->first();
        if(!$download) {
            $download = new Download();
            $download->uniqid = $uniqid;
            $download->name = $name ?: $uniqid;
            $download->path = '';
            $download->save();

            ProcessDownload::dispatch($download);

            return response()->json(['status' => $download ? 'success' : 'error', 'data' => $download->toArray()]);
        }
        return response()->json(['status' => 'error', 'message' => 'Cette vidéo a déjà été traitée']);
    }

    public function remove($id){
        $download = Download::find($id);
        $success = $download && $download->delete();
        $filepath = storage_path('files/'.$download->path);
        if(is_readable($filepath)) {
            unlink($filepath);
        }
        return response()->json(['status' => $success ? 'success' : 'error']);
    }

    public function downloadAll() {
        $uniqid = date('d_m_Y_H_i_s');
        $zipPath = storage_path('temp/download'.$uniqid.'.zip');
        $allComplete = Download::where('status', 'completed')->get();
        $files = [];

        foreach ($allComplete as $dl) {
            $filepath = storage_path('files/'.$dl->path);
            if(is_readable($filepath)) {
                $files[] = $filepath;
            }
        }
        $this->makeZipWithFiles($zipPath, $files);
        return response()->download($zipPath);
    }

    private function makeZipWithFiles(string $zipPathAndName, $files): void
    {
        $pd = new \PharData($zipPathAndName);
        foreach($files as $file) {
            $pd->addFile($file, basename($file));
        }
        $pd->compressFiles(\Phar::GZ);
    }
}
