<?php declare(strict_types=1);

namespace App\Http\Controllers\Private;

use App\Enums\Lang;
use App\Helpers\Helpers;
use App\Http\Requests\Private\Profile\UpdatePasswordRequest;
use App\Http\Requests\Private\Profile\UpdateRequest;
use App\Http\Requests\Private\Profile\UpdateSettingsRequest;
use App\Services\Private\ProfileService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

final class ProfileController extends Controller
{
    public function __construct(
        private readonly ProfileService $profileService
    ) { }

    public function profile(Request $request): View
    {
        return view('private/profile/profile', [
            'user' => $request->user()
        ]);
    }

    public function settings(Request $request): View
    {
        return view('private/profile/settings', [
            'user'  => $request->user(),
            'languages' => Lang::toCollection()->pluck(value: 'title', key: 'value')->toArray(),
            'timezone' => Helpers::getTimeZoneList()->toArray(),
        ]);
    }

    public function update(UpdateRequest $request): RedirectResponse
    {
        $data = $request->getDto();
        $user = $request->user();

        $result = $this->profileService->update($data, $user);
        if ($result->isError()) {
            return redirect()->back()->withInput()->withErrors($result->getMessage());
        }
        return redirect()->route('profile.edit')->withSuccess($result->getMessage());
    }

    public function updatePassword(UpdatePasswordRequest $request): RedirectResponse
    {
        $data = $request->getDto();
        $user = $request->user();

        $result = $this->profileService->updatePassword($data, $user);
        if ($result->isError()) {
            return redirect()->back()->withInput()->withErrors($result->getMessage());
        }
        return redirect()->route('profile.edit')->withSuccess($result->getMessage());
    }

    public function updateSettings(UpdateSettingsRequest $request): RedirectResponse
    {
        $data = $request->getDto();
        $user = $request->user();

        $result = $this->profileService->updateSettings($data, $user);
        if ($result->isError()) {
            return redirect()->back()->withInput()->withErrors($result->getMessage());
        }
        return redirect()->route('profile.settings')->withSuccess($result->getMessage());
    }
}
