<?php

namespace App\Http\Controllers\Layouts;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class UserProfileController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth', 'lock']);
    }

    /**
     * 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 = auth()->user(); // user can only update his own profile
        if (!auth()->user()->can('editProfile', $user)) {
            abort(401);
        }

        $this->validator($request->all(), $user->id)->validate();

        $user->fill([
            'fullname'      => request('fullname'),
            'email'         => request('email'),
        ]);

        try {
            DB::transaction(function () use ($user, $request) {
                $user->save();
            });

        } catch (\Exception $err) {
            return back()->with('notify', $this->notifArray('DB', 'error', $err->getMessage(), true));
        }
        return redirect()->route('profile', $user)
            ->with('notify', $this->notifArray('DB', 'success', __('Utente aggiornato con successo')));
    }

    /**
     * @param User $user
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showChangePassword()
    {
        $user = auth()->user(); // user can only change his own password
        if (!auth()->user()->can('selfUpdatePassword', $user)) {
            abort(401);
        }

        return view('layouts.changepassword', compact('user', $user));
    }

    /**
     * @param Request $request
     * @param User $user
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updateChangePassword(Request $request)
    {
        $user = auth()->user(); // user can only change his own password

        if (!auth()->user()->can('selfUpdatePassword', $user)) {
            abort(401);
        }

        $attributeNames = array(
            'old_password' => __('Vecchia password'),
            'new_password' => __('Nuova password')
        );

        Validator::make($request->all(), [
            'old_password'   => 'required|alpha_dash|min:6|max:100',
            'new_password'   => 'required|alpha_dash|min:6|max:100|confirmed|different:old_password',
            'new_password_confirmation'   => 'required',
        ])->setAttributeNames($attributeNames)->validate();

        if (auth()->attempt(['username'=>auth()->user()->username, 'password'=>request('old_password')])) {
            try {
                $user->fill([
                    'password' => request('new_password'),
                    'updated_by' => auth()->user()->id,
                ]);

                $user->save();

            } catch (\Exception $err) {
                return back()->with('notify', $this->notifArray('DB', 'error', $err->getMessage(), true));
            }

            return redirect()->route('change-password', $user)
                ->with('notify', $this->notifArray('DB', 'success', __('Password modificata con successo')));

        } else {
            return redirect()->route('change-password', $user)
                ->with('notify', $this->notifArray('DB', 'error', __('Vecchia password errata, riprovare')));

        }
    }


    /**
     * @param array $data
     * @param int $id
     * @return \Illuminate\Validation\Validator
     */
    protected function validator(array $data, $id = 0)
    {

        $attributeNames = array(
            'fullname' => __('Nome completo'),
        );

        return Validator::make($data, [
            'fullname'   => 'required|string|max:255',
            'email' => ['required','email','max:255',
                Rule::unique('users', 'email')
                    ->ignore($id)
                    ->where(function ($query) {
                        $query->where('deleted_at', null);
                    })
            ],
        ])->setAttributeNames($attributeNames);
    }
}
