<?php

namespace App\Http\Controllers;

use App\Http\Requests\AssetDestroyRequest;
use App\Http\Requests\AssetUploadRequest;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;

class AssetController extends Controller
{
    /**
     * Store a new asset file
     *
     * @param AssetUploadRequest $request
     * @return array|Response
     */
    public function store(AssetUploadRequest $request)
    {
        $path = tenant('id') . '/assets/' . $request->getFileName();
        $exists = Storage::disk(Config::get('filesystems.default_media'))->exists($path);
        if ($exists && $request->input('overwrite') != true) {
            return response([
                'errors' => [
                    'file' => ['File already exists, please confirm you want to overwrite']
                ]
            ], 422);
        }

        Storage::disk(Config::get('filesystems.default_media'))
            ->putFileAs(
                tenant('id') . '/assets/',
                $request->file('file'),
                $request->getFileName(),
                ['visibility' => $request->input('visibility')]
            );

        return [
            'url' => Storage::disk(Config::get('filesystems.default_media'))->url($path),
            'path' => $path,
        ];
    }

    /**
     * Remove an asset file
     *
     * @param AssetDestroyRequest $request
     * @return string[]
     */
    public function destroy(AssetDestroyRequest $request)
    {
        $path = $request->input('file_name');
        Storage::disk(Config::get('filesystems.default_media'))->delete($path);
        return [
            'url' => null,
            'path' => null,
        ];
    }

    /**
     * Store a new asset file
     *
     * @param AssetUploadRequest $request
     * @return array|Response
     */
    public function globalStore(AssetUploadRequest $request)
    {
        $path = 'assets/' . $request->getFileName();

        Storage::disk(Config::get('filesystems.default_media'))
            ->putFileAs(
                'assets/',
                $request->file('file'),
                $request->getFileName(),
                ['visibility' => $request->input('visibility')]
            );

        return [
            'url' => Storage::disk(Config::get('filesystems.default_media'))->url($path),
            'path' => $path,
        ];
    }
}
