<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Image;
use Spatie\Permission\Models\Role;

class UsersController extends Controller
{
	/**
	 * Display a listing of the resource.
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function index(Request $request)
	{
	    $users_total = User::count();
	    $users_active = User::where('active', 1)->count();
	    $query = User::query();
	    if($request->has('q')) {
	        $query->where('name', 'LIKE', "%{$request->q}%");
        }
	    if($request->has('roles')) {
	        $query->whereHas('roles', function($q) use($request) {
	            $q->whereIn('id', $request->roles);
            });
        }
	    if($request->has('active')) {
            $query->where('active', $request->active);
        }
		$users = $query->paginate(10);
        $roles = Role::orderBy('name')->pluck('name', 'id')->toArray();

		return view('backend.users.index', [
			'users' => $users,
            'roles' => $roles,
            'users_total' => $users_total,
            'users_active' => $users_active
		]);
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function create(User $user)
	{
		$roles = Role::orderBy('name')->pluck('name', 'id')->toArray();

		return view('backend.users.form', [
			'user' => $user,
			'roles' => $roles,
		]);
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @return \Illuminate\Http\Response
	 */
	public function store(Request $request)
	{
        try {
            $request->validate([
                'email' => 'unique:users,email',
                'name' => 'required'
            ]);

            $user = User::create($request->only('name', 'email', 'active', 'image'));
            $user->user_data()->create($request->user_data);

            $user->assignRole($request->roles);

            if($file = $request->file('image')) {
                $path = $file->hashName();
                $image = Image::make($file)->fit(300, 300, function($constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize();
                });

                Storage::put($path, $image->encode());

                $url = Storage::url($path);

                $user->fill([
                    'image' => $url,
                ])->save();
            }

            if($request->password) {
                $user->fill([
                    'password' => bcrypt($request->password)
                ])->save();
            }

            return redirect()->route('backend.users.edit', $user->id)->with('status', 'El usuario ha sido creado');
        } catch(\Exception $e) {
            return back()->withInput()->withErrors($e->getMessage());
        }
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  \App\User  $user
	 * @return \Illuminate\Http\Response
	 */
	public function edit(User $user)
	{
		$roles = Role::orderBy('name')->pluck('name', 'id')->toArray();

		return view('backend.users.form', [
			'user' => $user,
			'roles' => $roles,
		]);
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \App\User  $user
	 * @return \Illuminate\Http\Response
	 */
	public function update(Request $request, User $user)
	{
        try {
            $request->validate([
                'email' => 'unique:users,email,'.$user->id,
                'name' => 'required'
            ]);

            $user->fill($request->only('name', 'email', 'active', 'image'))->save();

            if($user->user_data) $user->user_data->fill($request->user_data)->save();
            else $user->user_data()->create($request->user_data);

            $user->syncRoles($request->roles);

            if($file = $request->file('image')) {
                $path = $file->hashName();
                $image = Image::make($file)->fit(300, 300, function($constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize();
                });

                Storage::put($path, $image->encode());

                $url = Storage::url($path);

                $user->fill([
                    'image' => $url,
                ])->save();
            }

            if($request->password) {
                $user->fill([
                    'password' => bcrypt($request->password)
                ])->save();
            }

            return back()->with('status', 'El usuario ha sido editado');
        } catch(\Exception $e) {
            return back()->withInput()->withErrors($e->getMessage());
        }
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  \App\User  $user
	 * @return \Illuminate\Http\Response
	 */
	public function destroy(User $user)
	{
        try {
            if($user->id == auth()->id()) {
                return back()->withErrors('No se puede eliminar al usuario actual');
            }
            $user->delete();

            return redirect()->back()->with('status', 'El usuario ha sido eliminado');
        } catch(\Exception $e) {
            return back()->withInput()->withErrors($e->getMessage());
        }
	}
}
