<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\RegisterRequest;
use Daylight\Core\Models\Country;
use Daylight\Core\Models\Customer;
use Daylight\Core\Models\Enums\AddressType;
use Daylight\Core\Models\Enums\CustomerType;
use Daylight\Core\Modules\Multilingualism\Entities\LocalizedRoute;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;

class RegisterController extends Controller
{
    public function create(): View
    {
        $localizedRoute = LocalizedRoute::create()
            ->setRoute('register')
            ->staticRoute();

        return view('auth.register', [
            'localizedRoute' => $localizedRoute,
            'countries' => Country::query()
                ->select(['id', 'code'])
                ->get()
                ->mapWithKeys(fn ($country) => [$country->id => $country->name]),
        ]);
    }

    public function store(RegisterRequest $request): RedirectResponse
    {
        $user = DB::transaction(function () use ($request) {
            $customer = Customer::create([
                'type' => CustomerType::COMPANY,
                'name' => $request->company_name,
            ]);

            $billingAddress = $customer->addresses()->create([
                'type' => AddressType::BILLING,
                'default' => true,
                'name' => $request->company_name,
                'address_line_1' => $request->street.' '.$request->house_number.($request->addition ? ' '.$request->addition : ''),
                'postal_code' => $request->postal_code,
                'city' => $request->city,
                'country_id' => $request->country,
                'invoicing_email' => $request->email,
                'kvk_number' => $request->kvk,
                'vat_number' => $request->vat,
            ]);

            // Copy billing address to shipping address
            $shippingAddress = $billingAddress->replicate();
            $shippingAddress->type = AddressType::SHIPPING;
            $shippingAddress->save();

            return $customer->users()->create([
                'name' => $request->name,
                'last_name' => $request->last_name,
                'email' => $request->email,
                'phone' => $request->phone,
                'password' => Hash::make($request->password),
            ]);
        });

        // @todo: Send notification to administrator about new registration and include notes
        event(new Registered($user));

        return redirect()
            ->back()
            ->with('success', __('Your registration was successful. After approval, you will receive an email with further instructions.'));
    }
}
