<?php

namespace App\Http\Controllers\Admin\Popup;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserGroup;
use App\Models\UserGrade;
use App\Models\DTO\SearchData;

class UserController extends Controller
{
    private User $userModel;
    private UserGroup $userGroupModel;
    private UserGrade $userGradeModel;

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

    /**
     * AJAX 회원 검색
     * @method GET
     * @see /admin/popup/user
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $params->activated = $request->get('activated');
        $params->isAdmin = $request->get('is_admin');
        $params->isDenied = $request->get('is_denied');
        $params->isWithdraw = $request->get('is_withdraw');
        $params->userGroupID = $request->get('user_group_id', []);
        $params->userGradeID = $request->get('user_grade_id', []);

        $userData = $this->userModel->data($params);

        if ($userData->rows > 0) {
            $num = listNum($userData->total, $params->page, $params->perPage);
            foreach ($userData->list as $i => $row) {
                $row->num = $num--;
                $row->point = number_format($row->point);

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

        return view('admin.popup.user.index', [
            'userGroupData' => $this->userGroupModel->all(),
            'userGradeData' => $this->userGradeModel->all(),
            'userData' => $userData,
            'params' => $params
        ]);
    }

    /**
     * AJAX 회원그룹 검색
     * @method GET
     * @see /admin/popup/user/group
     */
    public function group()
    {
        $userGroupData = $this->userGroupModel->data();
        $userTotalCount = $this->userModel->count(); // 전체 회원 수

        if($userGroupData->rows > 0) {
            $num = 1;
            foreach($userGroupData->list as $i =>$row) {
                $row->num = $num++;
                $row->userGroupCount = $row->user->count();
                $row->strName = ($row->kor_name . ($row->eng_name ? ' (' . $row->eng_name . ')' : ''));
                $row->strShare = (($row->userGroupCount > 0) ? round(($row->userGroupCount / $userTotalCount) * 100) : 0);

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

        return view('admin.popup.user.group', [
            'userGroupData' => $userGroupData
        ]);
    }
}
