@extends('layouts.app')
@section('title', 'タグ発行キュー処理、履歴表示')

@section('content')
    <div class="container-fluid">
        @if(session('success'))
            <div class="alert alert-success" style="margin-top:10px;">
                {{ session('success') }}
            </div>
        @endif
        @if(session('error'))
            <div class="alert alert-danger" style="margin-top:10px;">
                {{ session('error') }}
            </div>
        @endif
        <div class="d-flex justify-content-between align-items-center mb-2">
            <h3 class="m-0 text-dark">タグ発行キュー処理、履歴表示</h3>
            <nav aria-label="breadcrumb" class="mb-0" style="background: transparent;">
                <ol class="breadcrumb px-2 py-2 mb-0" style="background: transparent;">
                    <li class="breadcrumb-item"><a href="{{ route('home') }}">ホーム</a></li>
                    <li class="breadcrumb-item active" aria-current="page">タグ発行キュー処理、履歴表示</li>
                </ol>
            </nav>
        </div>

        <!-- 絞り込み -->
        <div class="card mb-3">
            <div class="card-body">
                <!-- 1行目：印刷処理 -->
                <div class="row mb-2">
                    <div class="col-md-12 font-weight-bold mb-1">印刷処理</div>
                    <div class="col-md-12">
                        <div class="row g-1">
                            <div class="col-md-2 mb-1">
                                <button type="button" class="btn btn-outline-secondary btn-xs w-100 py-1 px-2"
                                    style="font-size:0.85rem;" onclick="handlePrintLabels()">タグ発送宛名印刷</button>
                                <script>
                                    function handlePrintLabels() {
                                        var checkboxes = document.querySelectorAll('input[name="ids[]"]:checked');
                                        if (checkboxes.length === 0) {
                                            alert('1件以上選択してください。');
                                            return;
                                        }
                                        if (confirm('未発送のタグ発送用宛名を印刷してよろしいですか？')) {
                                            // 送信用form生成
                                            var form = document.createElement('form');
                                            form.method = 'POST';
                                            form.action = '/tagissue/print-unissued-labels';
                                            form.target = '_blank';
                                            // CSRF
                                            var csrf = document.createElement('input');
                                            csrf.type = 'hidden';
                                            csrf.name = '_token';
                                            csrf.value = '{{ csrf_token() }}';
                                            form.appendChild(csrf);
                                            // ids
                                            checkboxes.forEach(function(cb) {
                                                var input = document.createElement('input');
                                                input.type = 'hidden';
                                                input.name = 'ids[]';
                                                input.value = cb.value;
                                                form.appendChild(input);
                                            });
                                            document.body.appendChild(form);
                                            form.submit();
                                            document.body.removeChild(form);
                                        }
                                    }
                                </script>
                            </div>
                            <div class="col-md-10 mb-1"></div>
                        </div>
                    </div>
                </div>
                <!-- 2行目：絞り込みフィルター -->
                <div class="row mb-2">
                    <div class="col-md-12 font-weight-bold mb-1">絞り込みフィルター</div>
                    <div class="col-md-12">
                        <div class="row g-1">
                            <div class="col-md-2 mb-1">
                                <form method="GET" style="display:inline;">
                                    @if(request('filter_type') == 'unissued_toggle')
                                        <button type="submit" class="btn btn-warning btn-xs w-100 py-1 px-2" style="font-size:0.85rem;">タグ未発送解除</button>
                                    @else
                                        <input type="hidden" name="filter_type" value="unissued_toggle">
                                        <button type="submit" class="btn btn-outline-secondary btn-xs w-100 py-1 px-2" style="font-size:0.85rem;">タグ発送未発送</button>
                                    @endif
                                </form>
                            </div>
                            <div class="col-md-2 mb-1">
                                    <form method="GET" style="display:inline;">
                                        @if(request('filter_type') == 'issued_toggle')
                                            <button type="submit" class="btn btn-warning btn-xs w-100 py-1 px-2" style="font-size:0.85rem;">タグ発送済み解除</button>
                                        @else
                                            <input type="hidden" name="filter_type" value="issued_toggle">
                                            <button type="submit" class="btn btn-outline-secondary btn-xs w-100 py-1 px-2" style="font-size:0.85rem;">タグ発送済み</button>
                                        @endif
                                    </form>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 3行目：タグシリアルフィルター -->
                <div class="row mb-2">
                    <div class="col-md-12 font-weight-bold mb-1">タグシリアルフィルター</div>
                    <div class="col-md-12">
                        <form method="GET" class="mb-0">
                            <div class="row align-items-center g-1">
                                <div class="col-auto font-weight-bold" style="padding-right:4px;">タグシリアル</div>
                                <div class="col-auto" style="min-width:140px;">
                                    <input type="text" name="tag_serial" value="{{ request('tag_serial') }}" class="form-control form-control-sm" style="font-size:0.85rem; padding:2px 6px;" placeholder="キーワード…">
                                </div>
                                <div class="col-auto font-weight-bold" style="padding-right:4px; padding-left:8px;">タグシリアル64進</div>
                                <div class="col-auto" style="min-width:140px;">
                                    <input type="text" name="tag_serial_64" value="{{ request('tag_serial_64') }}" class="form-control form-control-sm" style="font-size:0.85rem; padding:2px 6px;" placeholder="キーワード…">
                                </div>
                                <div class="col-auto text-end" style="padding-left:8px;">
                                    <button type="submit" class="btn btn-default btn-xs py-1 px-2 me-1" style="font-size:0.85rem; min-width:60px;">絞り込み</button>
                                    <a href="{{ route('tagissue') }}" class="btn btn-default btn-xs py-1 px-2" style="font-size:0.85rem; min-width:60px;">全表示</a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <!-- 4行目：タグ発送ステータス変更 -->
                <div class="row mb-2">
                    <div class="col-md-12 font-weight-bold mb-1">タグ発送ステータス変更</div>
                    <div class="col-md-12">
                        <form id="statusForm" method="POST" action="{{ route('tagissue.status') }}">
                            @csrf
                            <input type="hidden" name="action" id="statusAction" value="">
                            <div class="row g-1">
                                <div class="col-md-2 mb-1">
                                    <button type="button" class="btn btn-outline-secondary btn-xs w-100 py-1 px-2"
                                        style="font-size:0.85rem;" onclick="handleStatusChange('to_issued')">タグ発送済み</button>
                                </div>
                                <div class="col-md-2 mb-1">
                                    <button type="button" class="btn btn-outline-secondary btn-xs w-100 py-1 px-2"
                                        style="font-size:0.85rem;" onclick="handleStatusChange('to_unissued')">タグ未発送</button>
                                </div>
                                <div class="col-md-8 mb-1"></div>
                            </div>
                            <div class="mt-2">
                                <div style="overflow-x: auto;">
                                    <table class="table table-bordered dataTable text-nowrap">
                                        <thead class="thead-light">
                                            <tr>
                                                <th style="width:40px;background-color:"><input type="checkbox" onclick="document.querySelectorAll('input[name=\'ids[]\']').forEach(cb => cb.checked = this.checked);"></th>
                                                <th class="sorting {{ ($sort=='que_id') ? ($sortType=='asc'?'sorting_asc':'sorting_desc') : '' }}" sort="que_id" style="color:#212529;cursor:pointer;"><span>キューID</span></th>
                                                <th class="sorting {{ ($sort=='user_tag_serial') ? ($sortType=='asc'?'sorting_asc':'sorting_desc') : '' }}" sort="user_tag_serial" style="color:#212529;cursor:pointer;"><span>タグシリアル</span></th>
                                                <th class="sorting {{ ($sort=='user_tag_serial_64') ? ($sortType=='asc'?'sorting_asc':'sorting_desc') : '' }}" sort="user_tag_serial_64" style="color:#212529;cursor:pointer;"><span>タグシリアル64進</span></th>
                                                <th class="sorting {{ ($sort=='user_tag_issue') ? ($sortType=='asc'?'sorting_asc':'sorting_desc') : '' }}" sort="user_tag_issue" style="color:#212529;cursor:pointer;"><span>タグ発送ステータス</span></th>
                                                <th class="sorting {{ ($sort=='user_name') ? ($sortType=='asc'?'sorting_asc':'sorting_desc') : '' }}" sort="user_name" style="color:#212529;cursor:pointer;"><span>利用者名</span></th>
                                                <th><span>携帯電話番号</span></th>
                                                <th><span>自宅電話番号</span></th>
                                                <th><span>居住所：郵便番号</span></th>
                                                <th><span>居住所：都道府県</span></th>
                                                <th><span>居住所：市区郡</span></th>
                                                <th><span>居住所：住所</span></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($users as $user)
                                                <tr>
                                                    <td style="background-color:#faebd7;">
                                                        <input type="checkbox" name="ids[]" value="{{ $user->user_id }}">
                                                    </td>
                                                    @php
                                                        $que = \App\Models\OperatorQue::where('user_id', $user->user_id)->first();
                                                    @endphp
                                                    <td>{{ $que ? $que->que_id : '' }}</td>
                                                    <td>{{ $user->user_tag_serial }}</td>
                                                    <td>{{ $user->user_tag_serial_64 }}</td>
                                                    <td>{{ $user->user_tag_issue }}</td>
                                                    <td>
                                                        @if(!empty($user->user_seq))
                                                            <a href="{{ route('user_edit', ['seq' => $user->user_seq]) }}" target="_blank">
                                                                {{ $user->user_name }}
                                                            </a>
                                                        @else
                                                            {{ $user->user_name }}
                                                        @endif
                                                    </td>
                                                    <td>{{ $user->user_mobile }}</td>
                                                    <td>{{ $user->user_homephone }}</td>
                                                    <td>{{ $user->user_regident_zip }}</td>
                                                    <td>{{ $user->user_regident_pre }}</td>
                                                    <td>{{ $user->user_regident_city }}</td>
                                                    <td>{{ $user->user_regident_add }}</td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                                <div class="d-flex align-items-center mb-2">
                                    <div class="ms-auto">
                                        {{ $users->appends(request()->except('page'))->links('pagination') }}
                                    </div>
                                </div>
                            </div>
                        </form>
                        <script>
                            function handleStatusChange(actionType) {
                                var form = document.getElementById('statusForm');
                                document.getElementById('statusAction').value = actionType;
                                var checkboxes = document.querySelectorAll('input[name="ids[]"]:checked');
                                if (checkboxes.length === 0) {
                                    alert('1件以上選択してください。');
                                    return;
                                }
                                var ids = Array.from(checkboxes).map(cb => cb.value);
                                var ajaxType = (actionType === 'to_issued') ? 'issued' : 'unissued';
                                fetch('/tagissue/check-status', {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json',
                                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                                    },
                                    body: JSON.stringify({ ids: ids, type: ajaxType })
                                })
                                .then(response => response.json())
                                .then(data => {
                                    if (ajaxType === 'issued' && data.alreadyIssued.length > 0) {
                                        alert('以下のユーザーはすでにタグ発送済みです:\n' + data.alreadyIssued.join('\n'));
                                        return;
                                    }
                                    if (ajaxType === 'unissued' && data.alreadyUnissued && data.alreadyUnissued.length > 0) {
                                        alert('以下のユーザーはすでにタグ未発送です:\n' + data.alreadyUnissued.join('\n'));
                                        return;
                                    }
                                    var confirmMsg = (ajaxType === 'issued') ? 'ステータスをタグ発送済に変更してよろしいですか？' : 'ステータスをタグ未発送に変更してよろしいですか？';
                                    if (confirm(confirmMsg)) {
                                        form.submit();
                                    }
                                })
                                .catch(() => {
                                    alert('ステータス確認に失敗しました。');
                                });
                            }
                        </script>
                    </div>
                </div>
            </div>
        </div>
    </div>
<script>
// ソート挙動
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('th.sorting').forEach(function(th) {
        th.addEventListener('click', function() {
            var sort = th.getAttribute('sort');
            var currentSort = new URLSearchParams(window.location.search).get('sort');
            var currentType = new URLSearchParams(window.location.search).get('sort_type');
            var nextType = 'asc';
            if (currentSort === sort) {
                nextType = (currentType === 'asc') ? 'desc' : 'asc';
            }
            var params = new URLSearchParams(window.location.search);
            params.set('sort', sort);
            params.set('sort_type', nextType);
            window.location.search = params.toString();
        });
    });
});
</script>
@endsection