<?php

namespace App\Http\Controllers\Account;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Traits\CommonTrait;
use App\Rules\NumberLength;
use App\Rules\SpecialCharLength;
use App\Rules\UppercaseLength;
use App\Models\User;

class PasswordChangeController extends Controller
{
    use CommonTrait;

    private User $userModel;

    public function __construct(User $user)
    {
        $this->middleware(['front', 'auth']);
        $this->userModel = $user;
    }

    /**
     * 비밀번호 변경
     * @method GET
     * @see /account/password
     */
    public function index(Request $request)
    {
        $this->isCertified($request);
        $request->session()->reflash();

        return view(layout('account.passwordChange'), [
            'menuID' => 'PASSWORD'
        ]);
    }

    /**
     * 비밀번호 변경 처리
     * @method POST
     * @see /account/password/change
     */
    public function update(Request $request)
    {
        $request->session()->reflash();

        $rules = [
            'password' => [
                'required',
                'confirmed',
                new NumberLength,
                new SpecialCharLength,
                new UppercaseLength
            ],
        ];

        $attributes = [
            'new_password' => '새 비밀번호',
            'new_password_confirmation' => '새 비밀번호 확인'
        ];

        $posts = $this->validate($request, $rules, [], $attributes);

        // 동일 비밀번호 여부 확인
        if ($this->passwordAuthed($posts['password'])) {
            return back()->withErrors('이전 비밀번호는 사용할 수 없습니다.');
        }

        $this->userModel->updater(UID, [
            'password' => bcrypt($posts['password']),
            'password_updated_at' => now()
        ]);

        return redirect()->route('account.profile')->withErrors('비밀번호가 변경되었습니다.');
    }
}
