<?= $this->extend('layouts/main') ?>

<?= $this->section('content') ?>
<style>
    .swal2-cancel {
        background-color: #ff0000 !important;
        color: #fff !important;
    }
</style>

<h1>SMS 발송하기</h1>

<div class="col-md-12 col-xl-8">
    <div class="main-card mb-3 card">
        <div class="card-header">
            <h5 class="card-title mb-0">SMS 발송</h5>
        </div>
        <div class="card-body">
            <form id="frm_sms_info" method="post" onsubmit="return false;">
                <input type="hidden" name="msg_type" value="0" />
                <input type="hidden" name="dest_phone" />
                <input type="hidden" name="send_phone" />

                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label mb-1">수신번호</label>
                        <div class="input-group">
                            <select name="dest_phone1" class="form-select" style="max-width: 120px;" required>
                                <option value="">-선택-</option>
                                <option value="010" selected>010</option>
                                <option value="011">011</option>
                                <option value="016">016</option>
                                <option value="017">017</option>
                                <option value="018">018</option>
                                <option value="019">019</option>
                                <option value="070">070</option>
                                <option value="02">02</option>
                            </select>
                            <input type="text" name="dest_phone2" class="form-control" maxlength="8" required />
                        </div>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label mb-1">수신자명</label>
                        <div class="input-group">
                            <select name="dest_type" class="form-select" style="max-width: 120px;" required>
                                <option value="중개인">중개인</option>
                                <option value="거주인">거주인</option>
                                <option value="의뢰인">의뢰인</option>
                                <option value="기타">기타</option>
                            </select>
                            <input type="text" name="dest_name" class="form-control" />
                        </div>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label mb-1">발신번호</label>
                        <div class="input-group">
                            <select name="send_phone1" class="form-select" style="max-width: 120px;"
                                onchange="chgPhoneNum(this.value);" required>
                                <option value="">-선택-</option>
                                <option value="010" selected>010</option>
                                <option value="011">011</option>
                                <option value="016">016</option>
                                <option value="017">017</option>
                                <option value="018">018</option>
                                <option value="019">019</option>
                                <option value="070">070</option>
                                <option value="02">02</option>
                                <option value="999">대표번호</option>
                                <option value="998">대표번호2</option>
                            </select>
                            <input type="text" name="send_phone2" class="form-control" maxlength="8" required />
                        </div>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label mb-1">발신자명</label>
                        <input type="text" class="form-control" name="send_name_view" placeholder="발신자명을 입력하세요"
                            value=<?= session('usr_nm') ?> required />
                    </div>

                    <div class="col-12">
                        <label class="form-label mb-1">메세지</label>
                        <textarea name="msg_body" class="form-control" rows="5" style="resize: none;"
                            required></textarea>
                    </div>

                    <div class="col-12">
                        <label class="form-label mb-1">메모</label>
                        <textarea name="memo" class="form-control" rows="4" style="resize: none;"></textarea>
                    </div>
                </div>
            </form>
        </div>
        <div class="card-footer d-flex justify-content-end align-items-center gap-3">
            <button type="button" class="btn btn-primary" id="btnSend">
                발송
            </button>
        </div>
    </div>
</div>


<script type="text/javascript">


    $(function () {

        // 발송 btn click
        $("#btnSend").on("click", function () {


            const form = document.getElementById('frm_sms_info');

            let isValid = true;

            if (!form.checkValidity()) {
                isValid = false;
            }

            if (!isValid) {
                form.classList.add('was-validated');
                return;
            }

            const destPhone = $("#frm_sms_info [name=dest_phone1]").val() + "" + $("#frm_sms_info [name=dest_phone2]").val()
            if (!isValidKoreanMobileAll(destPhone)) {
                Swal.fire({
                    title: "수신번호를 확인해 주세요.",
                    icon: "warning"
                });
                return;
            }

            const sendPhone = $("#frm_sms_info [name=send_phone1]").val() + "" + $("#frm_sms_info [name=send_phone2]").val()
            if (!isValidKoreanMobileAll(sendPhone)) {
                Swal.fire({
                    title: "발신번호를 확인해 주세요.",
                    icon: "warning"
                });
                return;
            }

            $("#frm_sms_info [name=dest_phone]").val(destPhone)
            $("#frm_sms_info [name=send_phone]").val(sendPhone)


            swal.fire({
                text: "SMS를 발송 하시겠습니까?",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "예",
                cancelButtonText: "아니오",
                closeOnConfirm: false,
                closeOnCancel: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '/manage/sms/sendSms',
                        contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                        method: 'POST',
                        data: $("#frm_sms_info").serialize(),
                        beforeSend: function () {
                            blockUI.blockPage({
                                message: tpl
                            })
                        },
                        complete: function () {
                            blockUI.unblockPage()
                        },
                        error: function (xhr, error, thrown) {
                            blockUI.unblockPage()
                            var msg = "";
                            if (xhr.responseText != null) {
                                msg = xhr.responseText
                            } else {
                                msg = "잠시후 다시 시도해 주세요."
                            }

                            Swal.fire({
                                title: msg,
                                icon: "error"
                            })
                        },
                        success: function (result) {

                            if (result.code == '0') {
                                clearForm()
                                Swal.fire({
                                    title: '정상 처리되었습니다.',
                                    icon: "success"

                                })
                            } else {
                                Swal.fire({
                                    title: result.msg,
                                    icon: "error"
                                })
                            }
                        }
                    });
                }
            })

        });


    });


    // form 초기화
    function clearForm() {
        $("#frm_sms_info")[0].reset()
        document.querySelectorAll("#frm_sms_info input[type='hidden']").forEach(el => {
            el.value = "";
        })
    }


    // 연락처 유효성 검사
    function isValidKoreanMobileAll(number) {
        const digits = String(number).replace(/[^\d]/g, '');

        // 01로 시작 + (0,1,6,7,8,9) + 7~8자리
        // 예: 01012345678, 0111234567
        const regex = /^01[016789]\d{7,8}$/;
        return regex.test(digits);
    }


</script>

<?= $this->endSection() ?>