<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Documentos;
use App\Http\Requests;
use App\Http\Requests\DocumentosRequest;
use Illuminate\Support\Facades\Session;

class DocumentosController extends Controller
{
    public function __construct() {

        $this->middleware('auth');
    }

    public function index()
    {
        if (Auth::user()->can('read-documents')) {
            $documentos = Documentos::where('promotoria_id',Auth::user() -> promotoria_id) -> get();;
            return view('documentos.index', compact('documentos'));
        }
        return redirect('auth/logout');

    }


    public function create()
    {

            if (Auth::user()->can('create-documents')) {
                $documentos = Documentos::orderBy('nombre', 'asc')->lists('nombre', 'id');
                return view('documentos.create', compact('documentos'));

            }
            return redirect('auth/logout');
     }

    public function store(DocumentosRequest $request)
    {
       if (Auth::user()->can('create-documents')) {

                $data = Documentos::create([
                    'nombre' =>  $request->input('nombre'),
                    'promotoria_id'   => Auth::user() -> promotoria_id,
                ]);
                $documento = Documentos::findOrFail($data->id);
                Session::flash('message', trans('ui.documents.message_create', array('name' => $documento->nombre)));
                return redirect('documento/create');
            }
            return redirect('auth/logout');
    }


    public function edit($id)
    {
            if (Auth::user()->can('update-documents')) {
                $documento = Documentos::findOrFail($id);
                return view('documentos.edit', compact('documento'));

            }
            return redirect('auth/logout');
    }

    public function update($id, DocumentosRequest $request)
    {
            if (Auth::user()->can('update-documents')) {

                $documento = Documentos::findOrFail($id);

                $documento->update([
                    'nombre' =>  $request->input('nombre'),
                    'promotoria_id'   => Auth::user() -> promotoria_id,
                ]);

                Session::flash('message', trans('ui.documents.message_update', array('name' => $documento->nombre)));

                return redirect('documento');
            }
            return redirect('auth/logout');
    }

    public function destroy($id)
    {
            if (Auth::user()->can('delete-documents')) {
                $documento = Documentos::findOrFail($id);
                Documentos::destroy($id);
                Session::flash('message', trans('ui.documents.message_delete', array('name' => $documento->nombre)));
                return redirect('documento');
            }


        return redirect('auth/logout');
    }

}
