<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Support\TwoFactor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SettingsController extends Controller
{
    public function enableEmailTwoFactor(Request $request)
    {
        abort_unless(site_bool('two_factor_site_enabled', false), 404);

        $user = Auth::user();

        if (is_null($user->email_verified_at)) {
            return back()->with('error', 'Verify your email address before enabling email 2FA.');
        }

        $user->update([
            'two_factor_enabled' => true,
            'two_factor_method' => 'email',
            'two_factor_secret' => null,
            'two_factor_confirmed_at' => now(),
        ]);

        return back()->with('success', 'Email two-factor authentication is now enabled.');
    }

    public function setupTotp(Request $request)
    {
        abort_unless(site_bool('two_factor_site_enabled', false), 404);

        $user = Auth::user();
        $secret = TwoFactor::generateSecret();

        // Store the secret but leave it unconfirmed until the user proves they
        // added it to their app by entering a valid code.
        $user->update([
            'two_factor_method' => 'totp',
            'two_factor_secret' => $secret,
            'two_factor_enabled' => false,
            'two_factor_confirmed_at' => null,
        ]);

        return back()->with('totp_setup', [
            'secret' => $secret,
            'uri' => TwoFactor::otpauthUri($secret, $user->email, brand_name()),
        ]);
    }

    public function confirmTotp(Request $request)
    {
        abort_unless(site_bool('two_factor_site_enabled', false), 404);

        $request->validate(['code' => ['required', 'string', 'max:10']]);
        $user = Auth::user();

        if (!$user->two_factor_secret || !TwoFactor::verify($user->two_factor_secret, $request->input('code'))) {
            return back()->with('error', 'That code did not match. Make sure your device clock is correct and try again.');
        }

        $user->update([
            'two_factor_enabled' => true,
            'two_factor_confirmed_at' => now(),
        ]);

        return back()->with('success', 'Authenticator app two-factor authentication is now enabled.');
    }

    public function disableTwoFactor(Request $request)
    {
        $user = Auth::user();
        $user->update([
            'two_factor_enabled' => false,
            'two_factor_method' => null,
            'two_factor_secret' => null,
            'two_factor_confirmed_at' => null,
        ]);

        return back()->with('success', 'Two-factor authentication has been disabled.');
    }

    public function index()
    {
        return redirect()->route('user.history', ['settings' => 1]);
    }

    public function update(Request $request)
    {
        $user = Auth::user();

        $request->validate([
            'password' => ['nullable', 'string', 'min:8'],
            'image' => ['nullable', 'image', 'mimes:jpeg,png,jpg,gif,webp', 'max:2048'],
            'balance_display' => ['nullable', 'in:coins,usd'],
        ]);

        if ($request->password) {
            $user->password = bcrypt($request->password);
        }

        if (isset($request->image)) {
            $user->profile_photo_path = $request->image->store('avatars', 'public');
        }

        if ($request->exists('is_profile_private')) {
            $user->is_profile_private = $request->boolean('is_profile_private');
        }

        if ($request->exists('balance_display')) {
            $user->balance_display = $request->input('balance_display') === 'usd' ? 'usd' : 'coins';
        }

        $user->save();

        if ($request->boolean('profile_settings_form')) {
            return redirect()->route('user.history', ['settings' => 1])
                ->with('success', 'Your profile has been updated!');
        }

        return back()->with('success', 'Your preference has been updated!');
    }


}
