<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\UpdatePasswordRequest;
use App\Http\Requests\Auth\UpdateProfileRequest;
use App\Http\Requests\Auth\UpdateTwoFactorRequest;
use App\Services\Audit\AuditLogService;
use App\Support\TwoFactorSettings;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class ProfileController extends Controller
{
    public function __construct(
        private readonly AuditLogService $auditLog,
    ) {}

    public function edit(): View
    {
        $user = auth()->user();

        return view('profile.edit', [
            'user' => $user,
            'platformTwoFactorEnabled' => TwoFactorSettings::isPlatformEnabled(),
            'canEnableTwoFactor' => TwoFactorSettings::isPlatformEnabled() && filled($user?->phone),
        ]);
    }

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

        $user->fill([
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'] ?? null,
        ]);

        if (blank($user->phone) && $user->two_factor_enabled) {
            $user->two_factor_enabled = false;
        }

        $user->save();

        return redirect()->route('profile.edit')->with('status', 'Profile updated successfully.');
    }

    public function updatePassword(UpdatePasswordRequest $request): RedirectResponse
    {
        $user = $request->user();
        $user->password = $request->validated('password');
        $user->save();

        return redirect()->route('profile.edit')->with('status', 'Password updated successfully.');
    }

    public function updateTwoFactor(UpdateTwoFactorRequest $request): RedirectResponse
    {
        if (! TwoFactorSettings::isPlatformEnabled()) {
            return redirect()->route('profile.edit')->with('error', 'Two-factor authentication is disabled platform-wide by an administrator.');
        }

        $user = $request->user();
        $enabled = $request->boolean('two_factor_enabled');

        $user->two_factor_enabled = $enabled;
        $user->save();

        $this->auditLog->log($enabled ? 'user.two_factor_enabled' : 'user.two_factor_disabled', $user);

        return redirect()->route('profile.edit')->with('status', $enabled
            ? 'Two-factor authentication has been enabled for your account.'
            : 'Two-factor authentication has been disabled for your account.');
    }
}
