<?php

namespace Modules\Admin\Http\Controllers;

use Modules\Docs\Models\Document;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class AdminDocsController extends Controller
{
    public function index()
    {
        $docs = Document::orderBy('name')->get();
        return view('admin::docs.index', [
            'docs' => $docs
        ]);
    }


    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'        => 'required',
            'description' => '',
            'file'        => 'required|mimes:pdf,zip'
        ]);
        $path = $request->file('file')->store('docs', ['disk' => 'local']);
        $request['path'] = $path;
        $document = Document::create(
            $request->only(['name', 'description', 'path'])
        );
        return to_route('admin.docs');
    }

    public function edit(Document $document)
    {
        return view('admin::docs.edit', [
            'document' => $document
        ]);
    }

    public function update(Request $request, Document $document)
    {
        $validated = $request->validate([
            'name'        => 'required',
            'description' => '',
            'file'        => 'mimes:pdf,zip'
        ]);

        if ($request->file('file'))
        {
            $path = $request->file('file')->store('docs', ['disk' => 'local']);
            $request['path'] = $path;
        }
        else
        {
            $reuqest['path'] = $document->path;
        }
        $document = $document->update(
            $request->only(['name', 'description', 'path'])
        );
        return to_route('admin.docs');
    }

    public function delete(Document $document)
    {
        $document->delete();
        return to_route('admin.docs');
    }
}
