<?php

namespace App\Http\Controllers\Account;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Traits\CommonTrait;
use App\Models\User;

class LeaveController extends Controller
{
    use CommonTrait;

    private User $userModel;

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

    /**
     * 회원탈퇴
     * @method GET
     * @see /account/leave
     */
    public function index()
    {
        return view(layout('account.leave'), [
            'user' => $this->userModel->info(),
            'menuID' => 'LEAVE'
        ]);
    }

    /**
     * 회원 탈퇴 처리
     * @method POST
     * @see /account/leave/update
     */
    public function update(Request $request)
    {
        $rules = [
            'password' => 'required|confirmed',
            'withdrawal' => 'required|in:0,1'
        ];

        $attributes = [
            'password' => '비밀번호',
            'password_confirmation' => '비밀번호 확인',
            'withdrawal' => '안내 동의'
        ];

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

        // 비밀번호 확인
        $certified = $this->passwordAuthed($posts['password']);
        if(!$certified) {
            return back()->withErrors('비밀번호가 일치하지 않습니다.');
        }

        $user = $request->user();
        $user->is_withdraw = 1;
        $user->deleted_at = now();
        $user->save();

        return redirect()->route('logout')->with('message', '회원탈퇴가 완료되었습니다.');
    }
}
