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

<?= $this->section('content') ?>
<style>
    th {
        font-size: 11px;
    }

    #phoneList tbody tr {
        cursor: pointer;
    }

    .blockUI {
        z-index: 1500 !important;
    }

    .swal2-cancel {
        background-color: #ff0000 !important;
        color: #fff !important;
    }
</style>

<h1>전화확인 관리</h1>

<div class="row">
    <div class="col-md-12 col-xl-12">
        <div class="main-card mb-3 card">
            <div class="card-body">
                <form class="row align-items-end" id="frm_srch_info" onsubmit="return false;">

                    <div class="col-md-1">
                        <label class="form-label mb-1">매체사</label>
                        <select class="form-control" name="cpid">
                            <option value="">선택</option>
                            <?php foreach ($code as $c): ?>
                                <option value="<?= $c['cd'] ?>"><?= $c['cd_nm'] ?></option>

                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <label class="form-label mb-1">등록기간</label>
                        <div class="row g-2">
                            <div class="col-5">
                                <input type="date" class="form-control" name="s_date">
                            </div>
                            <div class="col-1" style="text-align: center;line-height: 35px;">
                                -
                            </div>
                            <div class="col-5">
                                <input type="date" class="form-control" name="e_date">
                            </div>
                        </div>
                    </div>

                    <div class="col-md-2">
                        <label class="form-label mb-1">연락처</label>
                        <input type="text" class="form-control" name="phone_number">
                    </div>

                    <div class="col-md-1">
                        <label class="form-label mb-1">사용여부</label>
                        <select class="form-control" name="useYn">
                            <option value="">선택</option>
                            <option value="Y">사용</option>
                            <option value="N">미사용</option>
                        </select>
                    </div>

                    <!-- 검색 버튼 -->
                    <div class="col-md-1 d-grid">
                        <button type="button" class="btn btn-primary" id="btnSearch">
                            검색
                        </button>
                    </div>

                    <div class="col-md-2">
                        <button type="button" class="btn btn-outline-success" id="btnExcel">
                            <i class="fa fas fa-file-excel-o"></i> 엑셀 다운로드
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>


    <div class="col-md-12 col-xl-12">
        <div class="main-card mb-3 card">
            <div class="card-header">조직 관리</div>
            <div class="card-body">
                <table id="phoneList" class="table table-hover table-striped table-bordered">
                    <thead>
                        <tr>
                            <th></th>
                            <th>연락처</th>
                            <th>등록일자</th>
                            <th>만료일자</th>
                            <th>매체사</th>
                            <th>주소</th>
                            <th>소유자</th>
                            <th>신청인</th>
                            <th>관계</th>
                            <th>사용유무</th>
                            <th>메모</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 여기는 비워둠: AJAX로 채움 -->
                    </tbody>
                </table>
            </div>
            <div class="card-footer">
                <button type="button" class="btn btn-primary" id="addPhone">
                    등록
                </button>
            </div>
        </div>
    </div>
</div>

<?= $this->section('modals') ?>
<div class="modal fade" id="deptModal" tabindex="-1" aria-labelledby="deptModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="deptModalLabel">연락처 정보</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="frm_phone_info" class="needs-validation" onsubmit="return false;" novalidate>
                    <input type="hidden" name="type" value="create">
                    <!-- 1 row -->
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label class="form-label">연락처</label>
                            <input type="text" name="phone_number" id="phone_number" placeholder="(-)을 포함해 주세요"
                                class="form-control" required>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">매체사</label>
                            <select name="cpid" id="cpid" class="form-select" required>
                                <option value="">-전체-</option>
                                <?php foreach ($code as $c): ?>
                                    <option value="<?= $c['cd'] ?>"><?= $c['cd_nm'] ?></option>

                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">사용유무</label>
                            <select name="use_yn" id="use_yn" class="form-select">
                                <option value="Y" selected>사용</option>
                                <option value="N">미사용</option>
                            </select>
                        </div>
                    </div>

                    <!-- 2 row -->
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label class="form-label">소유주</label>
                            <input type="text" name="owner" id="owner" class="form-control" required>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">신청인</label>
                            <input type="text" name="applicant" id="applicant" class="form-control" required>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">관계</label>
                            <input type="text" name="relation" id="relation" class="form-control" required>
                        </div>
                    </div>

                    <!-- 3 row -->
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label">주소</label>
                            <input type="text" name="address" id="address" class="form-control">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">등록기간</label>
                            <div class="row g-2">
                                <div class="col-5">
                                    <input type="date" class="form-control" name="s_date" required>
                                </div>
                                <div class="col-1" style="text-align: center;line-height: 35px;">
                                    -
                                </div>
                                <div class="col-5">
                                    <input type="date" class="form-control" name="e_date" required>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 4 row -->
                    <div class="row mb-3">
                        <div class="col">
                            <label class="form-label">메모</label>
                            <textarea name="memo" id="memo" class="form-control" rows="2"></textarea>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">닫기</button>
                <button type="button" class="btn btn-primary" id="phoneSave">저장</button>
            </div>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css" />
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script defer src="/architectui/assets/js/datatable.kor.js"></script>
<script type="text/javascript">

    // const tpl = document.querySelector('.my-loader-template');


    $(function () {

        $("#srchBonbu").on("change", function (e) {

            var dept_sq = e.target.value

            $("#srchTeam").empty()

            var str = "<option value=''>선택</option>"
            if (teamArr != null) {

                for (var i = 0; i < teamArr.length; i++) {
                    if (dept_sq === teamArr[i].pdept_sq) {
                        str += "<option value='" + teamArr[i].dept_sq + "'>" + teamArr[i].dept_nm + "</option>"
                    }
                }
            }

            $("#srchTeam").append(str)

        });


        let table = $('#phoneList').DataTable({
            language: lang_kor,
            processing: true,
            serverSide: false,
            ajax: {
                url: '/manage/dupl_phone/getDuplPhoneList',
                type: 'GET',
                data: function (d) {
                    d.cpid = $("#frm_srch_info [name=cpid]").val()
                    d.s_date = $("#frm_srch_info [name=s_date]").val()
                    d.e_date = $("#frm_srch_info [name=e_date]").val()
                    d.phone = $("#frm_srch_info [name=phone_number]").val()
                    d.useYn = $("#frm_srch_info [name=useYn]").val()

                    d.srchType = $("#frm_srch_info [name=srchType]").val()
                    d.srchTxt = $("#frm_srch_info [name=srchTxt]").val()

                    d.start = d.start || 0
                    d.length = d.length || 10
                }
            },
            "columnDefs": [
                { 'targets': '_all', "defaultContent": "" },
                // { 'className': 'text-center', 'targets': [0, 2, 3, 4] },
            ],
            columns: [
                {
                    "data": null,
                    "width": "50px",
                    "render": function (data, type, row, meta) {
                        return meta.row + meta.settings._iDisplayStart + 1;
                    }
                },
                { data: 'phone_number' },
                { data: 's_date' },
                { data: 'e_date' },
                { data: 'cpid_nm' },
                { data: 'address' },
                { data: 'owner' },
                { data: 'applicant' },
                { data: 'relation' },
                { data: 'use_yn_nm', "width": "50px" },
                { data: 'memo', "width": "200px" },
            ],
            // 옵션들 예시
            paging: true,
            searching: false,
            ordering: false,
            serverSide: true,
        });


        $('#phoneList tbody').on('click', 'tr', function () {
            const row = table.row(this).data()
            if (!row) return

            const modalEl = document.getElementById('deptModal');
            const myModal = new bootstrap.Modal(modalEl);

            $("#frm_phone_info")[0].reset()
            $("#frm_phone_info [name=type]").val("update")

            $("#frm_phone_info [name=phone_number]").val(row.phone_number)
            $("#frm_phone_info [name=phone_number]").prop("readonly", true)
            $("#frm_phone_info [name=cpid]").val(row.cpid)
            $("#frm_phone_info [name=use_yn]").val(row.use_yn)
            $("#frm_phone_info [name=owner]").val(row.owner)
            $("#frm_phone_info [name=applicant]").val(row.applicant)
            $("#frm_phone_info [name=relation]").val(row.relation)
            $("#frm_phone_info [name=address]").val(row.address)
            $("#frm_phone_info [name=s_date]").val(row.s_date)
            $("#frm_phone_info [name=e_date]").val(row.e_date)
            $("#frm_phone_info [name=memo]").val(row.memo)


            myModal.show();

        });

        // [검색] 버튼 눌렀을 때 다시 조회
        $('#btnSearch').on('click', function () {
            table.ajax.reload()
        });

        // 유저 등록 모달
        $("#addPhone").on("click", function () {
            $("#frm_phone_info")[0].reset()

            $("#frm_phone_info [name=type]").val("create")
            $("#frm_phone_info [name=phone_number]").prop("readonly", false)

            const modalEl = document.getElementById('deptModal');
            const myModal = new bootstrap.Modal(modalEl);
            myModal.show();
        });


        // 유저정보저장
        $("#phoneSave").on("click", function () {

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

            let isValid = true;

            // Bootstrap5 기본 validation 적용
            if (!form.checkValidity()) {
                isValid = false;
            }

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

            swal.fire({
                text: "저장 하시겠습니까?",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "예",
                cancelButtonText: "아니오",
                closeOnConfirm: false,
                closeOnCancel: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '/manage/dupl_phone/savePhone',
                        contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                        method: 'POST',
                        data: $("#frm_phone_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') {
                                deptModalHide()
                                $("#btnSearch").trigger('click')
                                Swal.fire({
                                    title: '정상 처리되었습니다.',
                                    icon: "success"

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


        // 엑셀다운 click
        $("#btnExcel").on("click", function () {

            $.ajax({
                url: "/manage/dupl_phone/excel",
                method: "GET",
                dataType: "json",
                data: $("#frm_srch_info").serialize(),
                beforeSend: function () {
                    blockUI.blockPage({
                        message: tpl
                    })
                },
                complete: function () {
                    blockUI.unblockPage()
                },
                success: function (result) {
                    downloadExcel(result.data);
                }
            });

        });

    });

    function deptModalHide() {
        const modalEl = document.getElementById('deptModal');
        const modal = bootstrap.Modal.getInstance(modalEl); // 기존 인스턴스 가져오기

        if (modal) {
            modal.hide();
        }
    }

    // 엑셀 다운로드
    function downloadExcel(data) {
        const ws = XLSX.utils.json_to_sheet(data);
        ws['!cols'] = [
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 130 },
            { wpx: 80 },
            { wpx: 200 },
        ];

        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });

        const blob = new Blob([wbout], { type: 'application/octet-stream' });

        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "전화확인관리" + getDateTimeString() + ".xlsx";
        link.click();
        URL.revokeObjectURL(link.href);
    }

    function getDateTimeString() {
        const d = new Date();
        const yyyy = d.getFullYear();
        const mm = String(d.getMonth() + 1).padStart(2, '0');
        const dd = String(d.getDate()).padStart(2, '0');
        const hh = String(d.getHours()).padStart(2, '0');
        const mi = String(d.getMinutes()).padStart(2, '0');
        const ss = String(d.getSeconds()).padStart(2, '0');
        return `${yyyy}${mm}${dd}${hh}${mi}${ss}`;
    }

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