<?php

namespace Modules\VetSite\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\VetSite\Entities\VsMedia;
use Modules\VetSite\Http\Controllers\Concerns\HandlesUploads;

class MediaController extends Controller
{
    use HandlesUploads;

    private function biz()
    {
        return request()->session()->get('user.business_id');
    }

    private function gate()
    {
        if (! auth()->user()->can('vet_site.manage_content')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index()
    {
        $this->gate();
        $media = VsMedia::where('business_id', $this->biz())->orderByDesc('id')->paginate(40);
        return view('vetSite::admin.media', compact('media'));
    }

    public function upload(Request $request)
    {
        $this->gate();
        $request->validate(['files.*' => 'image|max:8192']);

        $biz = $this->biz();
        $saved = [];
        foreach ((array) $request->file('files', []) as $file) {
            if ($path = $this->storeUpload($file, $biz, 'media')) {
                $m = VsMedia::create([
                    'business_id'   => $biz,
                    'path'          => $path,
                    'original_name' => $file->getClientOriginalName(),
                    'mime'          => $file->getClientMimeType(),
                    'size'          => $file->getSize(),
                ]);
                $saved[] = ['id' => $m->id, 'url' => $m->url()];
            }
        }

        if ($request->wantsJson()) {
            return response()->json(['success' => true, 'media' => $saved]);
        }
        return back()->with('status', ['success' => 1, 'msg' => count($saved) . ' file(s) uploaded.']);
    }

    public function destroy($id)
    {
        $this->gate();
        $m = VsMedia::where('business_id', $this->biz())->findOrFail($id);
        $full = public_path('uploads/' . $m->path);
        if (is_file($full)) {
            @unlink($full);
        }
        $m->delete();

        return back()->with('status', ['success' => 1, 'msg' => __('vetSite::lang.deleted')]);
    }
}
