<?php

namespace App\Http\Controllers\Settings;

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

class ProfileController extends Controller
{
    use RegistersMedia;

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

        $media = $user->getFirstMedia('photos');
        $photoKey = $media?->getCustomProperty('s3_key') ?? $media?->getPath();
        $photoUrl = $media
            ? app(S3PresignedService::class)->getTemporaryUrl($media->getPath())
            : null;

        return Inertia::render('settings/profile', [
            'user' => [
                'id' => $user->id,
                'email' => $user->email,
                'username' => $user->username,
                'photo_key' => $photoKey,
                'photo_url' => $photoUrl,
                '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,
                    ],
                );

                $this->syncPhoto($user, ['photo_key' => $validated['photo'] ?? null], 'photos');
            },
            'Profil berhasil diperbarui.',
            'profile.edit',
        );
    }
}
