<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Sucursales;
use App\Ventanillas;
use Illuminate\Support\Facades\Redirect;
use App\Http\Requests\VentanillaRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class VentanillasController extends Controller
{
    public function __construct() {

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

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

    }



    public function create(){
        if (Auth::user()->can('create-windows')) {

            $sucursales = Sucursales::where('promotoria_id',Auth::user() -> promotoria_id) -> get();
            $sucursales = $sucursales->lists('nombre', 'id');
            return view('ventanillas.create', compact('sucursales'));
        }
        return redirect('auth/logout');

    }


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

                $data = Ventanillas::create([
                    'nombre' => $request->input('nombre'),
                    'sucursal_id' => $request->input('sucursal_id'),
                ]);
                $ventanilla = Ventanillas::findOrFail($data->id);
                Session::flash('message', trans('ui.windows.message_create', array('name' => $ventanilla->nombre)));
                return redirect('ventanilla/create');
            }
            return redirect('auth/logout');
    }

    public function edit($id){
            if(Auth::user()->can('update-windows')) {
            $ventanilla = Ventanillas::findOrFail($id);
            $sucursales = Sucursales::where('promotoria_id',Auth::user() -> promotoria_id);
            $sucursales = $sucursales -> lists('nombre','id');
            return view('ventanillas.edit',compact('ventanilla','sucursales'));

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

    public function update($id, VentanillaRequest $request){
            if (Auth::user()->can('update-windows')) {
                $ventanilla = Ventanillas::findOrFail($id);
                $ventanilla->update($request->all());
                Session::flash('message', trans('ui.windows.message_update', array('name' => $ventanilla->nombre)));

                return redirect('ventanilla');

            }

            return redirect('auth/logout');
    }

    public function destroy($id){
            if(Auth::user()->can('delete-windows')) {
            $ventanilla = Ventanillas::findOrFail($id);
            Ventanillas::destroy($id);
            Session::flash('message', trans('ui.windows.message_delete', array('name' => $ventanilla->nombre)));
            return redirect('ventanilla');
         }
            return redirect('auth/logout');
    }
}
