<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use App\Http\Requests\Settings\ProfileUpdateRequest;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class ProfileController extends Controller
{
    public function edit(Request $request): Response
    {
        $user = $request->user();
        $user->load('userProfile');

        return Inertia::render('settings/profile', [
            'user' => [
                'id' => $user->id,
                'email' => $user->email,
                'username' => $user->username,
                'userProfile' => $user->userProfile ? [
                    'full_name' => $user->userProfile->full_name,
                    'phone_number' => $user->userProfile->phone_number,
                    'gender' => $user->userProfile->gender?->value,
                    'birth_date' => $user->userProfile->birth_date?->format('Y-m-d'),
                    'address' => $user->userProfile->address,
                ] : null,
            ],
            'mustVerifyEmail' => $user instanceof MustVerifyEmail,
            'status' => $request->session()->get('status'),
        ]);
    }

    public function update(ProfileUpdateRequest $request): RedirectResponse
    {
        return $this->handleAction(
            function () use ($request) {
                $validated = $request->validated();
                $user = $request->user();

                $user->fill([
                    'email' => $validated['email'],
                    'username' => $validated['username'],
                ]);

                if ($user->isDirty('email')) {
                    $user->email_verified_at = null;
                }

                $user->save();

                $user->userProfile()->updateOrCreate(
                    [],
                    [
                        'full_name' => $validated['full_name'],
                        'phone_number' => $validated['phone_number'] ?? null,
                        'gender' => $validated['gender'] ?? null,
                        'birth_date' => $validated['birth_date'] ?? null,
                        'address' => $validated['address'] ?? null,
                    ],
                );
            },
            'Profil berhasil diperbarui.',
            'profile.edit',
        );
    }
}
