<?php

namespace App\Http\Controllers;

use App\EmailSenderDefine;
use App\Menu;
use App\User;
use App\UserPassword;
use Auth;
use Carbon\Carbon;
use DB;
use Exception;
use Hash;

use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;

class UsersController extends Controller
{

    /**
     * @param Request $request
     * @return Factory|RedirectResponse|View
     */
    public function addUser(Request $request)
    {

        $data = $this->validatorNameEmail($request);


        if ($data->fails())
        {
            return redirect()->back()->withErrors($data->errors())->with('message-fail', 'Nastala chyba ve jméně nebo emailu');
        }
        /**
         * 1) kontrola jestli je SMTP naistaveny
         * 2) udělat zaznam s tokenem
         * 3) odeslat email s proklikem a použitím tokenu
         */
        if(EmailSenderDefine::whereAktivni(1)->exists())
        {
            $data = User::create([
                'name' => $request->get('name'),
                'email' => $request->get('email'),
                'password' =>  Hash::make(date('Y-m-d H:i:s'))

            ]);
            $token = $this->setUserPasswordToken($data->id);
            $this->sendEmail($request->all(),$token);

        }
        else
        {
            return redirect()->back()->with('message-fail', 'Není nastavený emailový server -> Nastavení emailu');
        }


        return redirect()->route('users-index')->with('message-ok', 'Uživatel vytvořen');

    }

    public function obnovitHeslo()
    {
        return view('UsersLayouts.obnovit');
    }

    public function obnovitHesloCreate(Request $request)
    {
        $this->resendPass(User::whereEmail($request->get('email'))->first());

        return redirect('/');
    }


    protected function resendPass(User $user)
    {
        if(EmailSenderDefine::whereAktivni(1)->exists())
        {
            $token = $this->setUserPasswordToken($user->id);
            $data['email'] = $user->email;
            $data['name'] = $user->name;
            $this->sendEmail($data, $token);

            return redirect()->route('users-index')->with('message-ok', 'Obnova hesla odeslána');
        }

        return redirect()->back()->with('message-fail', 'Není nastavený emailový server -> Nastavení emailu');
    }

    protected function setUserPasswordToken($id)
    {
        try
        {
            $stringToken = date('Y-m-d H:i:s') . 'DP_STD' . random_int(0, 10000);
        }
        catch (Exception $e)
        {
            $stringToken = date('Y-m-d H:i:s') . 'DP_STD';
        }
        $token = md5($stringToken);


        if(Auth::user())
        {
            $user = Auth::user()->id;
        }
        else
        {
            $user = 1;
        }

        UserPassword::create(
            [
                'id_user' => $id,
                'vlozil' => $user,
                'token' => $token
            ]);
       return $token;
    }

    public function sendEmail($data, $token): void
    {
        $email = new EmailController();
        $email->komu = $data['email'];
        $email->jmeno = $data['name'];
        $email->predmet = 'Vytvoření hesla pro DP STD';
        $email->zprava = $token;
        $email->sendEmail('mailChangePass');
    }

    protected function validatorPass(Request $data)
    {
        return Validator::make($data->all(), [
            'password' => ['required', 'string', 'min:8', 'confirmed', 'same:password_confirmation'],
        ]);

    }
    protected function validatorNameEmail(Request $data)
    {
        return Validator::make($data->all(), [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        ]);
    }

    public function showAddForm()
    {
        return view('auth.register',['user'=> Auth::user(), 'menu' => Menu::getData()]);
    }

    /**
     * @return Collection
     */
    public function getUsersBezPrihlaseneho(): Collection
    {
        return DB::table('users')->where([['id','!=',Auth::user()->id],['id','!=',1]])->get(['id','name','email', 'email_verified_at']);
    }

    public function index()
    {
        return view('UsersLayouts.users',['menu' => Menu::getData(),'otherUsers' =>$this->getUsersBezPrihlaseneho()]);
    }

    public function edit(User $user)
    {
        return view('UsersLayouts.usersEdit', ['user' => $user,'menu' => Menu::getData()]);
    }
    public function update(User $user, Request $request)
    {

        if($request->get('email') === $user->email)
        {
            $user->update(['name' => $request->get('name')]);
            return redirect()->route('users-index')->with('message-ok', 'Uživatel upraven');
        }
        $data = $this->validatorNameEmail($request);
        if ($data->fails())
        {
            return redirect()->back()->withErrors($data->errors());
        }

        $request->except('_token');
        $user->update($request->all());
        return redirect()->route('users-index')->with('message-ok', 'Uživatel upraven');
    }

    public function changePass(User $user)
    {
        return view('UsersLayouts.userschangePass', ['user' => $user,'menu' => Menu::getData()]);
    }

    public function delete(User $user)
    {
        try
        {
            $user->delete();
            return redirect()->route('users-index')->with('message','Uživatel smazán');
        }
        catch (Exception $e)
        {
            return redirect()->route('users-index')->with('message','Vyskytla se chyba'.$e);
        }
    }

    public function changePassupdate(User $user, Request $request)
    {
        $data = $this->validatorPass($request);
        if ($data->fails())
        {
            return redirect()->back()->withErrors($data->errors());
        }

        $request->merge(['password' => Hash::make($request['password'])]);
        $user->update($request->all());
        return redirect()->route('users-index')->with('message-ok', 'Heslo změněno!');
    }


    public function setPassLink(Request $token)
    {
        $token = $token->get('token');
        $data = UserPassword::whereToken($token)->first();
        if($data)
        {
            if($data->id_user && $data->aktivni === 1 && $data->vlozeny>= Carbon::yesterday()->format('Y-m-d H:i:s'))
            {
                return view('UsersLayouts.setPass',['data'=> $data]);
            }
            elseif ($data->vlozeny<= Carbon::yesterday()->format('Y-m-d H:i:s'))
            {
                $data->update(['aktivni' => 0]);
                return view('UsersLayouts.smula');
            }
            else
            {
                return view('UsersLayouts.smula');
            }
        }
        return view('UsersLayouts.smula');
    }

    public function setPassConfirm(Request $request, UserPassword $data)
    {
        $user = User::find($data->id_user);

        $dataVal = $this->validatorPass($request);
        if ($dataVal->fails())
        {
            return redirect()->back()->withErrors($dataVal->errors());
        }

        $request->merge(['password' => Hash::make($request['password'])]);
        $data->update(['aktivni' => 0]);
        $user->email_verified_at = date('Y-m-d H:i:s');
        $user->update($request->all());

        return  redirect('/login');
    }
}
