<?php

namespace App\Http\Controllers\Admin\Sms\Book;

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

class UserController extends Controller
{
    private ?int $book;

    private User $userModel;
    private UserGroup $userGroupModel;
    private UserGrade $userGradeModel;
    private SmsUser $smsUserModel;

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

        $this->book = request()->input('book');
        if(!$this->book) {
            return redirect()->route('admin.sms.book.list.index')->with('message', 'Book ID는 필수 입니다.');
        }
    }

    /**
     * 연락처 관리 - 목록
     * @method GET
     * @see /admin/sms/book/user
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $params->userGroupID = $request->get('user_group_id', []);
        $params->userGradeID = $request->get('user_grade_id', []);
        $params->smsBookID = $this->book;

        $smsUserData = $this->smsUserModel->data($params);

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

                $row->searchURL = route('admin.user.list.index') . '?' . http_build_query([
                    'field' => 'users.id',
                    'keyword' => $row->user_id
                ]);

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

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

    /**
     * 주소록 회원 등록
     * @method GET
     * @see /admin/sms/book/user/create
     */
    public function create()
    {
        return view('admin.sms.book.user.write', [
            'actionURL' => route('admin.sms.book.user.store'),
            'book' => $this->book
        ]);
    }

    /**
     * 주소록 회원 저장
     * @method POST
     * @see /admin/sms/book/user
     */
    public function store(Request $request)
    {
        $rules = [
            'users' => 'required|string'
        ];

        $attributes = [
            'users' => '회원 ID'
        ];

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

        $users = explode(',', $posts['users']);
        foreach($users as $sid) {
            $user = $this->userModel->findByUserID($sid);
            if(!$user->exists) {
                return back()->withErrors(['sid' => "{$sid} 는 존재하지 않는 회원입니다."])->withInput();
            }else{

                // 이미 추가된 회원이면 무시
                if($this->smsUserModel->where([
                    ['sms_book_id', $this->book],
                    ['user_id', $user->id]
                ])->exists()) {
                   continue;
                }

                $this->smsUserModel->insert([
                    'sms_book_id' => $this->book,
                    'user_id' => $user->id,
                    'created_at' => $today
                ]);
            }
        }

        $message = '주소록에 회원이 등록되었습니다.';
        return redirect()->route('admin.sms.book.user.index', [
            'book' => $this->book
        ])->with('message', $message);
    }

    /**
     * 주소록 회원 삭제
     * @method DELETE
     * @see /admin/sms/book/users
     */
    public function destroy(Request $request)
    {
        $chk = $request->post('chk');

        if ($chk) {
            foreach ($chk as $smsUserID) {
                $this->smsUserModel->find($smsUserID)->delete();
            }
        }

        $message = '주소록에서 회원 정보가 삭제되었습니다.';
        return redirect()->route('admin.sms.book.user.index', [
            'book' => $this->book
        ])->with('message', $message);
    }
}
