<?php

namespace App\Services;

use App\Models\File;
use Exception;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RecursiveIteratorIterator;
use ZipArchive;

class FileService
{
    /**
     * @param $path
     * @param $file
     * @return File
     */
    public function saveUploadedFile($path, $file): File
    {
        Storage::disk('public')->put($path . '/' .$file->getClientOriginalName(), $file->getContent());
        return File::query()->updateOrCreate([
            'link' => url('/storage/') . '/' . $path . '/' .$file->getClientOriginalName(),
            'path' => $path . '/' .$file->getClientOriginalName(),
            'user_id' => auth()->user()->id,
            'original_name' => $file->getClientOriginalName(),
            'mime_type' => $file->getClientMimeType(),
        ]);
    }


    /**
     * @param string $path
     * @param string $archiveName
     * @param int|null $userId
     * @param bool $deleteSourceFiles
     * @return File
     * @throws Exception
     */
    public function createZipArchive(string $path, string $archiveName, int $userId = null, bool $deleteSourceFiles = false): File
    {

        if (!($tempFile = tempnam(sys_get_temp_dir(), Str::random()))) {
            throw new Exception('Cant create temporary file!');
        }
        var_dump(storage_path('app/public/' . $path));

        $zip = new ZipArchive();
        $fullPath = storage_path('app/public/' . $path);
        $zip->open($tempFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
        $files = new RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($fullPath),
            RecursiveIteratorIterator::LEAVES_ONLY
        );
        foreach ($files as $file) {
            if(!$file->isDir()) {
                // Get real and relative path for current file
                $filePath = $file->getRealPath();
                var_dump($filePath);
                $relativePath = substr($filePath, strlen($fullPath) + 1);
                var_dump($relativePath);
                // Add current file to archive
                $zip->addFile($filePath, $relativePath);
                if($deleteSourceFiles) {
                    Storage::disk($file->disk)->delete($file->path);
                    $file->delete();
                }
            }
        }
        $zip->close();
        $fileModel = File::query()->updateOrCreate([
            'link' => url('/storage/') . '/' . $path . '/' .$archiveName,
            'path' => $path . '/' .$archiveName,
            'user_id' => $userId ?? auth()->user()->id,
            'original_name' => $archiveName,
            'mime_type' => 'application/zip',
        ]);
        $contents = file_get_contents($tempFile);
        Storage::disk('public')->put($path . '/../' .$archiveName, $contents);
        unlink($tempFile);

        return $fileModel;
    }


}