<?php

namespace App\Http\Controllers\Admin\User;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserGroup;

class GroupController extends Controller
{
    private User $userModel;
    private UserGroup $userGroupModel;

    public function __construct(User $user, UserGroup $userGroup)
    {
        $this->userModel = $user;
        $this->userGroupModel = $userGroup;
    }

    /**
     * 회원그룹 관리
     * @method GET
     * @see /admin/user/group
     */
    public function index()
    {
        $userGroupData = $this->userGroupModel->data();

        // 전체 회원 수
        $totalUserCount = $this->userModel->count();

        $userGroupIDs = [];
        if ($userGroupData->total > 0) {
            $num = 1;
            foreach ($userGroupData->list as $i => $row) {
                $row->num = $num++;
                $userGroupIDs[] = $row->id;
                $row->userCount = $row->user->count();
                $row->updatedAt = dateBr($row->updated_at, '-');
                $row->createdAt = dateBr($row->created_at, '-');
                $row->share = (($row->userCount > 0) ? round(($row->userCount / $totalUserCount) * 100) : 0);

                $userGroupData->list[$i] = $row;
            }
        }

        return view('admin.user.group.index', [
            'userGroupData' => $userGroupData,
            'totalUserCount' => $totalUserCount,
            'userGroupID' => implode(',', $userGroupIDs)
        ]);
    }

    /**
     * 회원그룹 저장
     * @method POST
     * @see /admin/user/group/list
     */
    public function store(Request $request)
    {
        $posts = $request->all();
        $oldUserGroupID = explode(',', $posts['old_user_group_id']); // 기존 회원그룹 PK
        $curUserGroupID = $request->input('user_group_id', []);
        $userID = UID;
        $today = now();

        if($curUserGroupID) {
            $nLoop = 1;
            foreach($curUserGroupID as $userGroupID => $pk) {
                $saveData = [
                    'user_group_id' => ($posts['user_group_id'][$userGroupID] ?? 0),
                    'sort' => ($posts['sort'][$userGroupID] ?? 0),
                    'kor_name' => ($posts['kor_name'][$userGroupID] ?? ''),
                    'eng_name' => ($posts['eng_name'][$userGroupID] ?? ''),
                    'description' => ($posts['description'][$userGroupID] ?? ''),
                    'is_default' => ($posts['is_default'][$userGroupID] ?? 0),
                    'is_use' => ($posts['is_use'][$userGroupID] ?? 0)
                ];

                $rules = [
                    'image' => 'nullable|mimes:jpg,jpeg,gif,png|max:2192',
                    'user_group_id' => 'required|numeric',
                    'sort' => 'required|numeric',
                    'kor_name' => 'required|string',
                    'eng_name' => 'required|string',
                    'description' => 'string|nullable',
                    'is_default' => 'nullable|numeric',
                    'is_use' => 'required|numeric|in:0,1'
                ];

                $attributes = [
                    'image' => '이미지',
                    'user_group_id' => '번호',
                    'sort' => '순서',
                    'kor_name' => '한글명',
                    'eng_name' => '영문명',
                    'description' => '설명',
                    'is_default' => '기본 그룹',
                    'is_use' => '사용 여부'
                ];

                $validator = Validator::make($saveData, $rules, [], $attributes);
                if($validator->fails()) {
                    return redirect()->route('admin.user.group.index')->withErrors($validator)->withInput();
                }

                // 파일 저장
                $groupImages = $request->file('image');
                if(isset($groupImages[$userGroupID])) {
                    $groupImages[$userGroupID]->store(UPLOAD_PATH_PUBLIC . DIRECTORY_SEPARATOR . USER_GROUP_IMAGE_PATH);
                    $saveData['image'] = (UPLOAD_PATH_STORAGE . DIRECTORY_SEPARATOR . USER_GROUP_IMAGE_PATH . DIRECTORY_SEPARATOR . $groupImages[$userGroupID]->hashName());

                }

                // 파일 삭제
                $groupImageDel = $request->get('image_del');
                if(isset($groupImageDel[$userGroupID])) {
                    if(file_exists($groupImageDel[$userGroupID])) {
                        unlink($groupImageDel[$userGroupID]);
                    }
                    $saveData['image'] = null;
                }

                unset($saveData['user_group_id']);

                if(!$pk) {
                    $saveData['id'] = $userGroupID;
                    $saveData['created_at'] = $today;
                    $this->userGroupModel->insert($saveData);
                }else{
                    $saveData['updated_user_id'] = $userID;
                    $saveData['updated_at'] = $today;
                    $this->userGroupModel->find($pk)->update($saveData);
                }

                $nLoop++;
            }
        }

        // 값이 없는 경우 삭제 처리
        if($oldUserGroupID) {
            foreach($oldUserGroupID as $userGroupID) {
                if(!in_array($userGroupID, $curUserGroupID)) {
                    $this->userGroupModel->find($userGroupID)->delete();
                }
            }
        }

        $message = '회원그룹 정보가 변경되었습니다.';
        return redirect()->route('admin.user.group.index')->with('message', $message);
    }
}
