<?php

namespace App\Http\Controllers\Shop\Auth;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Sebastienheyd\Boilerplate\Rules\Password;

use App\Models\Shop\Customer;

class RegisterController extends Controller
{
    use RegistersUsers;

    protected $redirectTo;

    protected function guard()
    {
        return Auth::guard('customer');
    }

    protected function redirectTo()
    {
        return route(config('boilerplate.app.redirectTo', 'boilerplate.dashboard'));
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'last_name'  => 'required|max:255',
            'first_name' => 'required|max:255',
            'email'      => 'required|email|max:255|unique:shop_customers,email,NULL,id,deleted_at,NULL',
            'password'   => ['required', 'confirmed', new Password()],
        ]);
    }

    public function showRegistrationForm()
    {
        return view('Shop.auth.register', $data ?? []);
    }

    protected function create(array $data)
    {
        $user = Customer::withTrashed()->updateOrCreate(['email' => $data['email']], [
            'active'     => true,
            'first_name' => $data['first_name'],
            'last_name'  => $data['last_name'],
            'email'      => $data['email'],
            'password'   => bcrypt($data['password']),
        ]);

        return $user;
    }

    public function emailVerify()
    {
        if (Auth::user()->hasVerifiedEmail()) {
            return redirect(route(config('boilerplate.app.redirectTo', 'boilerplate.dashboard')));
        }

        return view('boilerplate::auth.verify-email');
    }

    public function emailVerifyRequest(EmailVerificationRequest $request)
    {
        $request->fulfill();
        return redirect(route(config('boilerplate.app.redirectTo', 'boilerplate.dashboard')));
    }

    public function emailSendVerification(Request $request)
    {
        $request->user()->sendEmailVerificationNotification();
        return back()->with('message', 'Verification link sent!');
    }
}
