@extends('admin.layouts.app')

@section('content')
<div class="container-fluid">
    <h2>회원그룹 관리</h2>
    <hr/>
    @include('admin.messages')

    <div class="form-text text-muted">
        <dl>
            <dd>기본 그룹을 선택하시면, 회원가입시 해당 그룹에 자동으로 추가됩니다. 그룹 삭제시, 복구가 불가하므로 주의하여 주시기 바랍니다.</dd>
            <dd><span class="text-info">그룹 이미지의 확장자는 gif, jpeg, png 만 사용 가능합니다.</span></dd>
            <dd>그룹 이미지는 202 x 205 에 최적화 되어있습니다. 지정된 크기의 이미지를 사용해주세요.</dd>
            <dd>저장된 그룹 정보는 회원등급 관리에 사용되며 쿠폰관리, 적립금 등의 혜택에 적용됩니다.</dd>
            <dd><span class="text-danger">그룹은 반드시 하나 이상 존재하여야 하며 기본그룹으로 설정된 그룹은 삭제가 불가능합니다.</span></dd>
        </dl>
    </div>
    <br/>

    <div class="row mb-2">
        <div class="col align-self-center">
            <label>전체 : {{ $userGroupData->total }}</label>
        </div>
        <div class="col text-end">
            <button type="submit" class="btn btn-success" form="fAdminList">저장하기</button>
        </div>
    </div>

    <form name="f_admin_list" id="fAdminList" method="post" action="{{ route('admin.user.group.store') }}" enctype="multipart/form-data">
        @csrf
        <input type="hidden" name="old_user_group_id" id="oldUserGroupID" value="{{ $userGroupID }}" />
        <div class="table-responsive-lg">
            <table class="table table-bordered table-nowrap">
                <thead>
                    <tr>
                        <th>순서</th>
                        <th>PK</th>
                        <th>이미지</th>
                        <th>한글명 / 영문명 / 설명</th>
                        <th>회원 수</th>
                        <th>회원 점유율</th>
                        <th>기본 그룹</th>
                        <th>사용 여부</th>
                        <th>수정일시</th>
                        <th>등록일시</th>
                        <th><button type="button" class="btn btn-info btn-sm text-white btn-add-rows">추가</button></th>
                    </tr>
                </thead>
                <tbody id="sortable">
                    @if($userGroupData->total > 0)
                        @foreach($userGroupData->list as $row)
                        <tr>
                            <td>
                                <i class="fas fa-arrows-alt"></i>
                                <input type="hidden" name="user_group_id[{{ $row->id }}]" class="user-group-id" value="{{ $row->id }}" />
                                <input type="hidden" name="order[{{ $row->id }}]" class="order" value="{{ $row->num }}" />
                            </td>
                            <td>
                                {{ $row->num }}
                                @if($row->userCount > 0)
                                    <br/><span class="badge bg-danger">삭제 불가</span>
                                @endif
                            </td>
                            <td>
                                @if($row->image)
                                    <figure class="figure mt-2 mb-0">
                                        <img src="{{ asset($row->image) }}" alt="{{ $row->kor_name }}" class="figure-img" width="104" height="103"/>
                                        <figcaption class="figure-caption">
                                            <div class="form-check form-check-inline">
                                                <input type="checkbox" name="image_del[{{ $row->id }}]" id="chk_{{ $row->id }}" class="form-check-input" value="{{ $row->id }}"/>
                                                <label for="{{ $chk }}" class="form-check-label"> 삭제</label>
                                            </div>
                                        </figcaption>
                                    </figure>
                                @else
                                    <input type="file" name="image[{{ $row->id }}]" id="image_{{ $row->id }}" class="user-group-image" accept="image/gif,image/jpeg,image/png"/>
                                @endif
                            </td>
                            <td>
                                <table class="table table-borderless m-0">
                                    <tr>
                                        <td>
                                            <input type="text" name="kor_name[{{ $row->id }}]" class="form-control" value="{{ $row->kor_name }}" />
                                        </td>
                                        <td>
                                            <input type="text" name="eng_name[{{ $row->id }}]" class="form-control" value="{{ $row->eng_name }}" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2">
                                            <input type="text" name="description[{{ $row->id }}]" class="form-control" value="{{ $row->description }}" />
                                        </td>
                                    </tr>
                                </table>
                            </td>
                            <td>
                                {{ number_format($row->userCount) }}
                                <span class="user-group-count-{{ $row->num }} d-none">{{ $row->userCount }}</span>
                            </td>
                            <td>{{ $row->share }}%</td>
                            <td>
                                <input type="checkbox" name="is_default[{{ $row->id }}]" class="form-check-input is-default" value="1" @if($row->is_default) checked @endif/>
                            </td>
                            <td>
                                <input type="checkbox" name="is_use[{{ $row->id }}]" class="form-check-input is-use" value="1" @if($row->is_use) checked @endif />
                            </td>
                            <td>
                                {!! $row->updatedAt !!}
                            </td>
                            <td>
                                {!! $row->createdAt !!}
                            </td>
                            <td>
                                <button type="button" class="btn btn-outline-danger btn-sm btn-delete-row" data-index="{{ $row->num }}">삭제</button>
                            </td>
                        </tr>
                        @endforeach
                    @else
                        <tr>
                            <td colspan="11">
                                No data.
                            </td>
                        </tr>
                    @endif
                </tbody>
            </table>
        </div>
    </form>
</div>

<script type="module">
// 이미지 크기 재확인
const _URL = window.URL || window.webkitURL;

$("input:file.user-group-image").change(function () {
    let file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onLoad = function () {
            if (this.width > 202 || this.height > 205) {
                alert('이미지 크기가 초과되었습니다. 202x205 크기의 이미지를 사용 해주세요. 크기가 자동으로 변환됩니다.');
                return false;
            }
        };
        img.onError = function () {
            alert("Not a valid file: " + file.type);
        };
        img.src = _URL.createObjectURL(file);
    }
});

// 체크박스 하나만 선택
$(document).on('change', 'input:checkbox.is-default', function(e)
{
    $('input:checkbox.user-group-is-default').not(this).prop("checked", false);
    e.preventDefault();
});

// 새로추가
$(document).on('click', '.btn-add-rows', function()
{
    let order = parseInt($("tr.ui-sortable-handle").length + 1);
    let html = '<tr>\
                    <td>\
                        <i class="fas fa-arrows-alt"></i>\
                        <input type="hidden" name="user_group_id[]" class="user-group-id" value="" />\
                        <input type="hidden" name="order[]" class="order" value="' + order + '" />\
                    </td>\
                    <td>-</td>\
                    <td>\
                        <input type="file" name="image[]" class="image" accept="image/gif, image/jpeg, image/png" />\
                    </td>\
                    <td>\
                        <table class="table table-borderless m-0">\
                            <tr>\
                                <td>\
                                    <input type="text" name="kor_name[]" class="form-control" />\
                                </td>\
                                <td>\
                                    <input type="text" name="eng_name[]" class="form-control" />\
                                </td>\
                            </tr>\
                            <tr>\
                                <td colspan="2">\
                                    <input type="text" name="description[]" class="form-control" />\
                                </td>\
                            </tr>\
                        </table>\
                    </td>\
                    <td>0</td>\
                    <td>0</td>\
                    <td>\
                        <input type="checkbox" name="is_default[]" class="form-check-input is-default" value="1" />\
                    </td>\
                    <td>\
                        <input type="checkbox" name="is_use[]" class="form-check-input is-use" value="1" />\
                    </td>\
                    <td>-</td>\
                    <td>-</td>\
                    <td>\
                        <button type="button" class="btn btn-outline-dark btn-sm btn-delete-row" >삭제</button>\
                    </td>\
                </tr>';

    $("#sortable").append(html);
});

$(document).on('click', '.btn-delete-row', function() {
    let index = this.dataset.index;
    let userGroupCount = $("span.user-group-count-" + index).text();

    if (userGroupCount > 0) {
        alert("소속된 회원이 있어 삭제가 불가능 합니다.");
    } else {
        $(this).parent().parent().remove();
    }
});

$(function () {
    $("#sortable").sortable({
        containment: 'parent',
        axis: 'y',
        helper: function (e, ui) {
            ui.children().each(function () {
                $(this).width($(this).width());
            });
            return ui;
        },
        update: function (event, ui) {
            let order = ui.item.index();
            ui.item.find(".order").val(order);
        }
    });
});
</script>
@endsection
