<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Auth;
use App\Models\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Input;
use DateTime;
use Illuminate\Support\Facades\Redirect;
use Session;
use File;
use Image;
use Illuminate\Support\Arr;

class UserController extends Controller
{

    protected $rules = [
        'name' => ['required'],
        'email' => ['required']
    ];

    public function index()
    {

        if (\Illuminate\Support\Facades\Auth::user()->level == 1 || \Illuminate\Support\Facades\Auth::user()->level == 2)
            return redirect('/admin/dashboard');

        $users = User::orderBy('name', 'ASC')->get();
        return view('users.index', compact('users'));
    }

    public function create()
    {
        return view('users.create');
    }

    public function store(Request $request)
    {

        $this->validate($request, $this->rules);

        // $input = $request->all();

        $input = $request->all();

        $input["disabled"] = isset($input["disabled"]) ? ($input["disabled"] == 'on' ? true : false) : false;

        $input["password"] = bcrypt($input["password"]);

        $user = User::create( $input );

        return Redirect::route('users.index')->with('message', 'Dati salvati');
    }

    public function show($id)
    {
        //
    }

    public function edit(User $user)
    {
        return view('users.edit', compact('user'));
    }

    public function update(Request $request, User $user)
    {

        $this->validate($request, $this->rules);

        $input = Arr::except($request->all(), array('_method', '_token'));

        $input["disabled"] = isset($input["disabled"]) ? ($input["disabled"] == 'on' ? true : false) : false;

        if ($input["password"] != '')
            $input["password"] = bcrypt($input["password"]);
        else
            $input["password"] = $user->password;

        $user->update($input);

        return Redirect::route('users.index')->with('message', 'Dati salvati');
    }

    public function destroy(User $user)
    {

        $user->delete();

        return Redirect::route('users.index')->with('message', 'Dati eliminati');
    }

}
