<?php

namespace App\Http\Controllers\Auth;

use Exception;
use Throwable;
use App\Models\User;
use App\Models\Setting;
use App\Enums\SettingType;
use App\Services\ImageService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Auth\Events\Registered;
use App\Http\Requests\Auth\UserSaveRequest;

class RegisteredUserController extends Controller
{
    protected $imageService;

    public function __construct(ImageService $imageService)
    {
        $this->imageService = $imageService;
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function save(UserSaveRequest $request): JsonResponse
    {
        $loginUserId = auth()->id();
        try {
            DB::beginTransaction();

            $user = User::updateOrCreate(
                ['id' => $loginUserId],
                [
                    'name' => $request->first_name + ' ' + $request->last_name,
                    'email' => $request->email,
                    'password' => Hash::make($request->password),
                ]
            );
            $user->profile()->updateOrCreate(
                ['id' => $loginUserId],
                [
                    'first_name' => $request->first_name,
                    'last_name' => $request->last_name,
                    'gender' => $request->gender,
                    'phone' => $request->phone,
                    'country' => $request->country,
                    'state' => $request->state,
                    'city' => $request->city,
                    'address' => $request->address,
                    'zip' => $request->zip,
                ]
            );

            if ($request->hasFile('image')) {
                $oldImage = $user->image;
                if ($oldImage) {
                    $this->imageService->delete($oldImage->id, User::class);
                }
                $image = $this->imageService->upload($request->file('image'), User::class);
                $user->image()->save($image);
            }

            if (!$loginUserId) {
                $settings = Setting::all();
                foreach ($settings as $setting) {
                    if ($setting->type == SettingType::BOOLEAN) {
                        $setting->users()->save($user, ['value' => true]);
                    }
                }
            }

            DB::commit();
        } catch (Throwable $e) {
            DB::rollBack();

            Log::error(__CLASS__ . '::' . __FUNCTION__ . '[line: ' . __LINE__ . ']Message: ' . $e->getMessage());

            throw new Exception('User saved failed.');
        }

        if (!$loginUserId) {
            event(new Registered($user));

            auth()->login($user);
        }

        return response()->json(['user' => $user]);
    }
}
