@extends('admin.layouts.app')

@section('content')
<div class="container-fluid">
    <h2>SMS 문자 발송하기</h2>
    <hr/>
    @include('admin.messages')

    <div class="row">
        <div class="col col-sm-3 border-end">
            <form name="f_admin_write" id="fAdminWrite" method="post" action="{{ $actionURL }}">
                @csrf
                <input type="hidden" name="user_ids" id="userIDs" value="" />
                <div class="row">
                    <div class="col">
                        <h5 class="mb-3">자주 보내는 문자</h5>
                    </div>
                    <div class="col-auto text-end">
                        <button type="button" id="btnSmsFavorite" class="btn btn-sm btn-primary">찾기</button>
                    </div>
                </div>
                <div class="mb-3">
                    <label for="smsSubject" class="form-label">제목</label>
                    <input type="text" name="sms_subject" id="smsSubject" class="form-control" value="{{ old('sms_subject') }}" />
                    <div class="form-text text-muted">LMS 용 제목, 미입력 시 `제목 없음` 으로 전송됨, SMS 사용안함</div>
                </div>
                <div class="mb-3">
                    <label for="smsContent" class="form-label">내용</label>
                    <textarea name="sms_content" id="smsContent" class="form-control" rows="8">{{ old('sms_content') }}</textarea>
                    <div class="row mt-2 mb-2">
                        <div class="col">
                            <div class="form-text text-muted">
                                <span id="contentByte">0</span> / 2000 byte
                            </div>
                        </div>
                        <div class="col text-end">
                            <div class="btn-group btn-group-sm">
                                <button type="button" class="btn btn-dark rounded-start dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">특수문자</button>
                                <div class="dropdown-menu">
                                    <button type="button" class="btn btn-sm" onclick="sms.add('■');">■</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('□');">□</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('▣');">▣</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('◈');">◈</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('◆');">◆</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('◇');">◇</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('♥');">♥</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('♡');">♡</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('●');">●</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('○');">○</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('▲');">▲</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('▼');">▼</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('▶');">▶</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('▷');">▷</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('◀');">◀</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('◁');">◁</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('☎');">☎</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('☏');">☏</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('♠');">♠</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('♤');">♤</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('♣');">♣</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('♧');">♧</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('★');">★</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('☆');">☆</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('☞');">☞</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('☜');">☜</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('▒');">▒</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('⊙');">⊙</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('㈜');">㈜</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('№');">№</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('㉿');">㉿</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('♨');">♨</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('™');">™</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('℡');">℡</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('∑');">∑</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('∏');">∏</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('♬');">♬</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('♪');">♪</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('♩');">♩</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('♭');">♭</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('*^^*');">*^^*</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('♡.♡');">♡.♡</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('@_@');">@_@</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('☞_☜');">☞_☜</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('ㅠ ㅠ');">ㅠ ㅠ</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('Θ.Θ');">Θ.Θ</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('^_~♥');">^_~♥</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('~o~');">~o~</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('★.★');">★.★</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('(!.!)');">(!.!)</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('⊙.⊙');">⊙.⊙</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('q.p');">q.p</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('┏( \'\')┛');">┏( \'\')┛</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('@)-)--');">@)-)--')</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('↖(^-^)↗');">↖(^-^)↗</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('(*^-^*)');">(*^-^*)</button>
                                </div>
                                <button type="button" class="btn btn-dark rounded-end dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">이모티콘</button>
                                <div class="dropdown-menu">
                                    <button type="button" class="btn btn-sm" onclick="sms.add('*^^*');">*^^*</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('♡.♡');">♡.♡</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('@_@');">@_@</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('☞_☜');">☞_☜</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('ㅠ ㅠ');">ㅠ ㅠ</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('Θ.Θ');">Θ.Θ</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('^_~♥');">^_~♥</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('~o~');">~o~</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('★.★');">★.★</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('(!.!)');">(!.!)</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('⊙.⊙');">⊙.⊙</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('q.p');">q.p</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('┏( \'\')┛');">┏( \'\')┛</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('@)-)--');">@)-)--')</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('↖(^-^)↗');">↖(^-^)↗</button>
                                    <button type="button" class="btn btn-sm" onclick="sms.add('(*^-^*)');">(*^-^*)</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-text text-muted mt-3">
                        전송할 내용입니다. 90 byte 이내는 SMS, 90 ~ 2000 byte 는 LMS 그 이상은 절삭 되어 LMS 로 전송됩니다. 개행은 ‘\n’으로 처리합니다.
                    </div>
                </div>
                <div class="mb-3">
                    <div class="row">
                        <label for="smsTel" class="col col-form-label">받는 사람</label>
                        <div class="col text-end">
                            <button type="button" id="btnDelReceiver" class="btn btn-sm btn-danger btn-del-receiver">삭제</button>
                        </div>
                    </div>
                    <select name="sms_tel" id="smsTel" class="form-select" multiple size="7"></select>
                    <textarea name="sms_per_tel" id="smsPerTel" class="form-control mt-2" rows="4" placeholder="개인 번호(쉼표 구분)">{{ old('sms_per_tel') }}</textarea>
                </div>
                <div class="mb-3 form-check">
                    <input type="checkbox" name="sms_is_reserve" id="smsIsReserve" class="form-check-input" value="1" @if(old('sms_is_reserve')) checked @endif />
                    <label for="smsIsReserve" class="form-check-label">예약 전송</label>
                </div>
                <div id="inputSmsReserve" class="mb-3" style="display: {{ old('sms_reserve_at') ? 'block' : 'none' }}">
                    <input type="datetime-local" name="sms_reserve_at" id="smsReserveAt" class="form-control" value="{{ old('sms_reserve_at') }}">
                    <div class="form-text text-muted">
                        12자리 예약일시입니다. ‘yyyyMMddHHmm’형태이며 null 이거나 내용이 없으 면 즉시전송, 현시간 5분전보다 오래된 시간이라면 형식오류로 처리됩니다.
                    </div>
                </div>
                <button type="submit" class="btn btn-success w-100 mb-3">전송하기</button>
            </form>
        </div>
        <div class="col col-sm-9">
            <h5 class="mb-3">휴대폰 번호 목록</h5>
            <span class="form-text text-muted">SMS 수신을 허용한 회원님만 출력됩니다.</span>
            <hr/>
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="sms_book_id" id="smsBookID_0" value="0" checked/>
                <label class="form-check-label" for="smsBookID_0">
                    전체
                </label>
            </div>
            @foreach($smsGroups as $row)
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="sms_book_id" id="smsBookID_{{ $row->id }}" value="{{ $row->id }}"/>
                <label class="form-check-label" for="smsBookID_{{ $row->id }}">
                    {{ $row->name }}
                </label>
            </div>
            @endforeach
            <hr/>
            <div id="smsRectList"></div>
        </div>
    </div>
</div>

<script type="module">
var $smsTel = $("#smsTel");
var arrKeys = {};

$(function() {
    $("#fAdminWrite").validate({
        rules: {
            sms_subject: {required: true, maxlength: 30},
            sms_content: {required: true, maxlength: 2000},
            sms_tel: {required: function() {
                return ($("#smsPerTel").val().length <= 0);
            }},
            sms_per_tel: {required: function() {
                return ($("#smsTel > option").length <= 0)
            }},
            sms_is_reserve: {required: false},
            sms_reserve_at: {required: "#smsIsReserve:checked"}
        },
        submitHandler: function(form) {
            if(confirm("문자를 전송하시겠습니까?")) {
                // 수신 회원 PK 저장
                $("#userIDs").val(JSON.stringify(arrKeys));
                form.submit();
            }
            return false;
        }
    });

    sms.viewUserAllList();
});

// 번호 추가 (개별)
$(document).on("click", ".btn-add-receiver", function() {
    $smsTel.append(sms.getOption(this.dataset.target));
});

// 번호 삭제
$(document).on("click", ".btn-del-receiver", function() {
    return sms.delReceiver();
});

// 예약 전송 날짜 노출
$(document).on("change", "#smsIsReserve", function() {
    let $target = $("#inputSmsReserve");
    if(this.checked) {
        $target.show();
    }else{
        $target.hide();
    }
});

// 번호 추가 (전체)
$(document).on("click", ".btn-add-all-receiver", function() {
    return sms.addAllReceiver();
});

// 페이징 처리를 load 이벤트로 전환
$(document).on("click", "a.page-link", function() {
    document.forms['fAdminSearch'].elements['page'].value = $(this).text();
    return sms.viewUserAllList();
});

var contents = "smsContent";
var contentByte = "contentByte";
var $popupSpecialChar = $(".popup-special-char");

// 특수문자 내용
$(document).on('focus keydown', '#' + contents, function() {
    $popupSpecialChar.hide();
});

// 특수문자 입력창 열기
$(document).on('click', '.btn-special-char', function() {
    $popupSpecialChar.hide();
    $(this).next().show();
});

// 문자 내용 입력 시
$(document).on('keydown keyup', '#' + contents, function() {
    byteCheck(contents, contentByte);
});

// 특수문자 닫기
$(document).on('click', '.btn-close', function() {
    $(this).parent().parent().hide();
});

// 자주 보내는 문자 찾기
$(document).on("click", "#btnSmsFavorite", function() {
    popupCenter(ADMIN_URL + "/popup/sms/favorite", "자주 보내는 문자", 1024, 570);
});

// 휴대폰 번호 목록 검색
$(document).on("submit", "#fAdminSearch", function() {
    return sms.viewUserAllList();
});

// 휴대폰 번호 목록 변경
$(document).on("change", "input[name='sms_book_id']", function() {
    if(this.value === "0") {
        return sms.viewUserAllList();
    }else{
        return sms.viewUserGroupList(this.value);
    }
});

const sms =
{
    delReceiver: function() {
        let $selected = $smsTel.find("option:selected");
        if($selected.length > 0) {
            if(confirm("삭제하시겠습니까?")) {
                $.each($selected, function (i, o) {
                    delete arrKeys[o.dataset.id];
                    $(o).remove();
                });
            }
            return true;
        }else{
            alert("삭제하실 회원을 선택해 주세요.");
            return false;
        }
    },

    addAllReceiver: function() {
        let $checked = $("input.list-check-box:checked");
        if($checked.length > 0) {
            let option;
            $.each($checked, function (i, item) {
                option += sms.getOption(item.dataset.target);
            });
            $smsTel.append(option);
            return true;
        }else{
            alert("추가하실 회원을 선택해 주세요.");
            return false;
        }
    },

    // 휴대폰 번호 목록 전체 검색
    viewUserAllList: function()
    {
        let formData = $("#fAdminSearch").serialize();
        $.get(ADMIN_URL + "/sms/send/user", formData, function(html) {
            document.getElementById("smsRectList").innerHTML = html;
        });
        return false;
    },

    // 휴대폰 번호 목록 그룹 검색
    viewUserGroupList: function(book)
    {
        let formData = $("#fAdminSearch").serialize() + '&book=' + book;
        $.get(ADMIN_URL + "/sms/send/book", formData, function(html) {
            document.getElementById("smsRectList").innerHTML = html;
        });
        return false;
    },

    // 연락처 데이터
    getOption: function(target)
    {
        let $this = document.getElementById(target);
        let id = $this.dataset.id;
        let name = $this.dataset.name;
        let nickname = $this.dataset.nickname;
        let phone = $this.dataset.phone;

        if(!name) {
            name = nickname;
        }

        let value = [id, name, phone].join(",");

        if(typeof arrKeys[id] == "undefined") {
            arrKeys[id] = phone;
        }else{
            alert(name + "은 이미 추가된 회원 입니다.");
            return false;
        }

        return '<option value="' + phone + '" data-user-id="' + id + '" selected>' + value + '</option>';
    },

    // 특수문자 추가
    add: function(str) {
        let content = document.getElementById(contents);
        content.focus();
        content.value += str;
        byteCheck(contents, contentByte);
    },
};
</script>
@endsection
