<?php

namespace App\Http\Controllers\Shop\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Shop\RegisterCustomer;
use App\Repositories\Core\User\ShopCart;
use App\Repositories\Shop\CustomerSaleChannels;
use App\Repositories\Shop\CustomerAddresses;
use App\Repositories\Shop\Customers;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;


class RegisterController extends Controller
{
    protected $redirectTo;

    public function showRegistrationForm(Request $request)
    {
        return view('Shop.auth.register', ['customer' => $request->old()]);
    }

    public function register(RegisterCustomer $request)
    {
        if (back()->getTargetUrl() === route('Shop.Orders.store')) {
            $route = 'Shop.Orders.order';
        } else {
            $route = 'home';
        }

        $user = $this->create($request->all());

        $this->guard()->login($user);
        ShopCart::migrateGuestCartToUser();

        return $request->wantsJson()
            ? new JsonResponse([], 201)
            : redirect()->route($route);
    }

    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!');
    }

    protected function create(array $data)
    {
        $customer = Customers::create($data);
        CustomerAddresses::createByCustomer($customer->id, $data);
        CustomerSaleChannels::createByCustomer($customer->id);

        return $customer;
    }

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

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