<?php

namespace App\Http\Controllers\Admin\Setting;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Master\UserRequest;
use App\Http\Requests\Admin\Setting\PasswordRequest;
use App\Models\User;
use App\Traits\UploadAttachment;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class AccountController extends Controller
{
    use UploadAttachment;

    public function index(): View
    {
        return view('pages.admin.setting.account', [
            'pageTitle' => 'Profil',
            'profile' => User::with(['attachments', 'biography', 'role'])->findOrFail(Auth::id()),
        ]);
    }

    public function updateProfile(User $user, UserRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();

        DB::transaction(function () use ($validatedData, $user) {
            $user->update($validatedData);

            $biographyData = collect($validatedData)
                ->except([
                    'email',
                    'username',
                    'avatar',
                ])
                ->toArray();
            $user->biography()->update($biographyData);
            if (isset($validatedData['avatar'])) {
                $this->uploadAttachment($validatedData['avatar'], 'users', User::class, $user->id, 'avatar');
            }
            if (isset($validatedData['ktp'])) {
                $this->uploadAttachment($validatedData['ktp'], 'users', User::class, $user->id, 'ktp');
            }
        });

        notify()->success('Data berhasil diubah', 'Berhasil');

        return back();
    }

    public function updatePassword(User $user, PasswordRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();
        if (! Hash::check($validatedData['current_password'], $user->password)) {
            notify()->error('Kata sandi yang Anda masukkan salah', 'Gagal');

            return back();
        } elseif ($validatedData['new_password'] == $validatedData['repeat_new_password']) {
            Auth::logoutOtherDevices($validatedData['current_password']);
            $user->update([
                'password' => Hash::make($validatedData['new_password']),
            ]);

            Auth::logout();

            request()->session()->invalidate();

            request()->session()->regenerateToken();
            notify()->success('Kata sandi Anda telah berhasil diperbarui. Silakan masuk kembali untuk melanjutkan', 'Berhasil');

            return redirect()->route('login');
        }

        notify()->error('Kata sandi baru yang Anda masukkan tidak sesuai dengan konfirmasi', 'Gagal');
    }
}
