<?php

namespace App\Http\Controllers\Account;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Controller;
use App\Http\Traits\CommonTrait;
use App\Models\User;
use App\Models\UserNameLog;
use App\Models\UserEmailLog;
use App\Models\FileLib;
use App\Rules\AllowNickname;

class ModifyController extends Controller
{
    use CommonTrait;

    private User $userModel;
    private UserNameLog $userNameLogModel;
    private UserEmailLog $userEmailLogModel;

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

    /**
     * 회원 정보 수정
     * @method GET
     * @see /account/modify
     */
    public function index(Request $request)
    {
        $this->isCertified($request);
        $request->session()->reflash();

        $changeNicknameDayLeft = $this->userNameLogModel->getDayLeft(UID);
        $changeEmailDayLeft = $this->userEmailLogModel->getDayLeft(UID);
        $userThumbWidth = config('user_thumb_width', THUMB_MAX_WIDTH);
        $userThumbHeight = config('user_thumb_height', THUMB_MAX_HEIGHT);
        $useUserThumb = config('use_user_thumb', 0);

        return view(layout('account.modify'), [
            'user' => $request->user(),
            'changeNicknameDayLeft' => $changeNicknameDayLeft,
            'changeEmailDayLeft' => $changeEmailDayLeft,
            'userThumbWidth' => $userThumbWidth,
            'userThumbHeight' => $userThumbHeight,
            'useUserThumb' => $useUserThumb,
            'menuID' => 'MODIFY'
        ]);
    }

    /**
     * 회원 정보 수정 처리
     * @method POST
     * @see /account/modify
     */
    public function update(Request $request, FileLib $fileLib)
    {
        $request->session()->reflash();

        $rules = [
            'nickname' => ['required', 'string', 'min:2', 'max:20',
                new AllowNickname, Rule::unique('users', 'nickname')->ignore(UID, 'id')],
            'thumb_img' => 'nullable|mimes:jpg,jpeg,gif,png|max:3192',
            'today_message' => ['nullable', 'string', 'max:40'],
            'about_me' => ['nullable', 'string', 'max:500'],
            'is_open_profile' => 'nullable|numeric|in:0,1',
            'receive_email' => 'nullable|numeric|in:0,1'
        ];

        $attributes = [
            'nickname' => '닉네임',
            'thumb_img' => '프로필 이미지',
            'today_message' => '오늘의 한마디',
            'about_me' => '자기소개',
            'is_open_profile' => '정보 공개 여부',
            'receive_email' => '수신여부 - 이메일(Email)'
        ];

        $messages = [
            'profile.max' => '첨부 가능한 이미지의 최대 용량은 3MB 입니다.'
        ];

        $posts = $this->validate($request, $rules, $messages, $attributes);
        $user = $request->user();

        if(!$this->userNameLogModel->isUpdateAble($user->id)) {
            $posts['nickname'] = $user->nickname;
        }
        if(!$request->has('is_open_profile')) {
            $posts['is_open_profile'] = 0;
        }
        if(!$request->has('receive_email')) {
            $posts['receive_email'] = 0;
        }

        $saveData = [
            'nickname' => $posts['nickname'],
            'today_message' => $posts['today_message'],
            'about_me' => $posts['about_me'],
            'is_open_profile' => $posts['is_open_profile'],
            'receive_email' => $posts['receive_email']
        ];

        // 파일 삭제
        if($request->get('thumb_img_del'))
        {
            $thumbPath = public_path($request->user()->thumb);
            if(file_exists($thumbPath)) {
                if(unlink($thumbPath)) {
                    $saveData['thumb'] = null;
                }
            }

        }else if($request->hasFile('thumb_img')) {

            // 파일 저장
            $thumb = $request->file('thumb_img');
            $savePath = $thumb->store(UPLOAD_PATH_PUBLIC . DIRECTORY_SEPARATOR . UPLOAD_PATH_USER_THUMB . DIRECTORY_SEPARATOR . $user->id);
            $storagePath = Storage::path($savePath);
            $saveData['thumb'] = Storage::url($savePath);

            // 이미지 크기 조정
            $fileLib->resize($storagePath, THUMB_MAX_WIDTH, THUMB_MAX_HEIGHT);
        }

        // 이름 변경 확인
        if($user->nickname != $posts['nickname']) {
            $this->userNameLogModel->setLog($user, $posts['nickname']);
        }

        $this->userModel->updater(UID, $saveData);

        return redirect()->route('account.profile')->withErrors('회원 정보가 수정되었습니다.');
    }
}
