<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

class UserController extends Controller
{

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

    public function index()
    {
        
        $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');
    }

}
