@extends('layouts.app')
@section('title', '利用者分類マスタ')
@section('content')
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-lg-6">
                    <h1 class="m-0 text-dark">{{__('利用者分類マスタ')}}</h1>
                </div>
                <div class="col-lg-6">
                    <ol class="breadcrumb float-sm-right text-sm">
                        <li class="breadcrumb-item"><a href="{{route('home')}}">ホーム</a></li>
                        <li class="breadcrumb-item active">{{__('利用者分類マスタ')}}</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
    <style>
        .rv-filter-card .form-label{font-weight:600;color:#555;font-size:.85rem;}
        .rv-filter-card .form-control-sm{border-radius:.25rem;}
        .rv-toolbar .btn{min-width:82px;}
        .rv-table-wrapper{background:#fff;border:1px solid #dee2e6;border-radius:.25rem;}
        .rv-table tbody tr td{vertical-align:middle;}
        .rv-table .op-cell{background:#f8f1e4;min-width:140px;}
        .rv-table thead th{
            white-space:nowrap;
            background:#eeeeee;
            text-decoration:none;
        }
        .rv-table thead th span,
        .rv-table thead th .rv-sort-arrows,
        .rv-table thead th .rv-sort-arrows .rv-arrow{
            text-decoration:none !important;
        }
        .rv-table thead th.sortable{cursor:pointer;}
        .rv-sort-arrows{
            display:inline-flex;
            align-items:center;
            margin-left:4px;
            gap:0;
            letter-spacing:-3px; /* ↑↓を詰める */
            font-size:16px;
        }
        .rv-sort-arrows .rv-arrow{
            color:#b5b5b5;
            font-size:16px;
            line-height:1;
            display:inline-block;
        }
        .rv-sort-arrows .rv-arrow.is-active{color:#000;}
        .rv-table thead th a{color:#000 !important;}
        @media (max-width: 767.98px){
            .rv-toolbar{flex-direction:column;align-items:flex-start;gap:.5rem;}
        }
    </style>
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <form action="{{ route('usertypes') }}" method="post" id="list-form" class="w-100">
                    @csrf
                    <input type="hidden" name="sort" id="sort" value="{{ $sort }}">
                    <input type="hidden" name="sort_type" id="sort_type" value="{{ $sort_type }}">
                    <div class="card rv-filter-card mb-3">
                        <div class="card-header bg-white font-weight-bold text-muted">
                            {{ __('絞り込み') }}
                        </div>
                        <div class="card-body pt-3 pb-2">
                            <div class="form-row">
                                <div class="form-group col-xl-4 col-lg-4 col-md-6">
                                     <label class="form-label">{{ __('ソートオーダー') }}</label>
                                     <input type="text" name="filter_sort_order" class="form-control form-control-sm"
                                         value="{{ $filter_sort_order ?? '' }}" placeholder="123456">
                                 </div>
                                <div class="form-group col-xl-4 col-lg-4 col-md-6">
                                     <label class="form-label">{{ __('分類名1') }}</label>
                                     <input type="text" name="filter_usertype_subject1" class="form-control form-control-sm"
                                         value="{{ $filter_usertype_subject1 ?? '' }}" placeholder="{{ __('キーワード...') }}">
                                 </div>
                                <div class="form-group col-xl-4 col-lg-4 col-md-6">
                                     <label class="form-label">{{ __('分類名2') }}</label>
                                     <input type="text" name="filter_usertype_subject2" class="form-control form-control-sm"
                                         value="{{ $filter_usertype_subject2 ?? '' }}" placeholder="{{ __('キーワード...') }}">
                                 </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group col-xl-4 col-lg-4 col-md-6">
                                    <label class="form-label">{{ __('分類名3') }}</label>
                                    <input type="text" name="filter_usertype_subject3" class="form-control form-control-sm"
                                        value="{{ $filter_usertype_subject3 ?? '' }}" placeholder="{{ __('キーワード...') }}">
                                </div>
                            </div>
                            <div class="d-flex justify-content-start">
                                <button type="submit" class="btn btn-default btn-sm mr-2" id="btnFilterSubmit">{{ __('絞り込み') }}</button>
                                <button type="button" class="btn btn-default btn-sm" id="btnFilterReset">{{ __('解除') }}</button>
                            </div>
                        </div>
                    </div>
                </form>
                <form action="{{ route('usertypes_export') }}" method="post" id="form_export" class="d-none">
                    @csrf
                    <input type="hidden" name="sort" value="{{ $sort }}">
                    <input type="hidden" name="sort_type" value="{{ $sort_type }}">
                    <input type="hidden" name="filter_sort_order" value="{{ $filter_sort_order ?? '' }}">
                    <input type="hidden" name="filter_usertype_subject1" value="{{ $filter_usertype_subject1 ?? '' }}">
                    <input type="hidden" name="filter_usertype_subject2" value="{{ $filter_usertype_subject2 ?? '' }}">
                    <input type="hidden" name="filter_usertype_subject3" value="{{ $filter_usertype_subject3 ?? '' }}">
                </form>
                <div class="w-100 rv-toolbar mb-3 d-flex justify-content-between align-items-center">
                    <div class="btn-group" role="group" aria-label="toolbar-actions">
                        <a href="{{ route('usertype_add') }}" class="btn btn-default mr-2">{{ __('新規') }}</a>
                        <button type="button" class="btn btn-default mr-2" id="btnDeleteSelected">{{ __('削除') }}</button>
                        <button type="button" class="btn btn-default" id="btnExportCsv">{{ __('CSV出力') }}</button>
                    </div>
                    <div class="pagination-wrapper">
                        {{ $list->appends([
                            'sort' => $sort,
                            'sort_type' => $sort_type,
                            'filter_sort_order' => $filter_sort_order ?? '',
                            'filter_usertype_subject1' => $filter_usertype_subject1 ?? '',
                            'filter_usertype_subject2' => $filter_usertype_subject2 ?? '',
                            'filter_usertype_subject3' => $filter_usertype_subject3 ?? '',
                        ])->links('pagination') }}
                    </div>
                </div>
                <div class="form col-lg-12">
                    @if(Session::has('success'))
                        <div class="alert alert-success alert-dismissible" role="alert">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            {{ Session::get('success') }}
                        </div>
                    @elseif(Session::has('error'))
                        <div class="alert alert-danger alert-dismissible">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            <h4><i class="icon fa fa-ban"></i> {{__('誤差')}}:</h4>
                            {!! Session::get('error') !!}
                        </div>
                    @elseif(isset($errorMsg))
                        <div class="alert alert-danger alert-dismissible">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            <h4><i class="icon fa fa-ban"></i> {{__('誤差')}}:</h4>
                            {!! $errorMsg !!}
                        </div>
                    @endif
                </div>
                <div class="col-lg-12 sample03-wrapper no_padding_right mb20">
                    <form action="{{route('usertypes_delete')}}" method="post" id="form_delete">
                        @csrf
                        <div class="table-responsive rv-table-wrapper">
                            @php
                                $currentSort = $sort ?? '';
                                $currentDir = strtolower($sort_type ?? 'asc');
                                if (!in_array($currentDir, ['asc', 'desc'], true)) {
                                    $currentDir = 'asc';
                                }

                                $sortClass = static function (string $key) use ($currentSort, $currentDir): string {
                                    return $currentSort === $key
                                        ? 'sortable sorting_' . $currentDir
                                        : 'sortable sorting';
                                };

                                $arrowState = static function (string $key) use ($currentSort, $currentDir): array {
                                    $state = ['up' => '', 'down' => ''];
                                    if ($currentSort === $key) {
                                        if ($currentDir === 'asc') {
                                            $state['up'] = 'is-active';
                                        } elseif ($currentDir === 'desc') {
                                            $state['down'] = 'is-active';
                                        }
                                    }
                                    return $state;
                                };

                                $renderSortIcon = static function (array $state): string {
                                    $up = $state['up'] ?? '';
                                    $down = $state['down'] ?? '';
                                    return '<span class="rv-sort-arrows"><span class="rv-arrow ' . $up . '">↑</span><span class="rv-arrow ' . $down . '">↓</span></span>';
                                };
                                $queryParams = [
                                    'filter_sort_order' => $filter_sort_order ?? null,
                                    'filter_usertype_subject1' => $filter_usertype_subject1 ?? null,
                                    'filter_usertype_subject2' => $filter_usertype_subject2 ?? null,
                                    'filter_usertype_subject3' => $filter_usertype_subject3 ?? null,
                                ];
                                $queryParams = array_filter($queryParams, static function ($value) {
                                    return !is_null($value) && $value !== '';
                                });
                                $buildSortUrl = static function (string $column, string $currentSort, string $currentDir, array $baseParams): string {
                                    $nextDir = ($currentSort === $column && $currentDir === 'asc') ? 'desc' : 'asc';
                                    return route('usertypes', array_merge($baseParams, [
                                        'sort' => $column,
                                        'sort_type' => $nextDir,
                                        'page' => 1,
                                    ]));
                                };
                            @endphp
                            <table class="table table-striped table-hover rv-table mb-0 text-nowrap">
                                <thead>
                                    <tr>
                                        <th style="width:80px;">
                                            <input type="checkbox" id="chkAll">
                                            <span class="ml-1"></span>
                                        </th>
                                        @php $state = $arrowState('user_categoryid'); @endphp
                                        <th class="{{ $sortClass('user_categoryid') }}">
                                            <a href="{{ $buildSortUrl('user_categoryid', $currentSort, $currentDir, $queryParams) }}" class="d-inline-flex align-items-center text-reset">
                                                <span>{{ __('利用者分類ID') }}</span>
                                                {!! $renderSortIcon($state) !!}
                                            </a>
                                        </th>
                                        @php $state = $arrowState('sort_order'); @endphp
                                        <th class="{{ $sortClass('sort_order') }}">
                                            <a href="{{ $buildSortUrl('sort_order', $currentSort, $currentDir, $queryParams) }}" class="d-inline-flex align-items-center text-reset">
                                                <span>{{ __('ソートオーダー') }}</span>
                                                {!! $renderSortIcon($state) !!}
                                            </a>
                                        </th>
                                        @php $state = $arrowState('usertype_subject1'); @endphp
                                        <th class="{{ $sortClass('usertype_subject1') }}">
                                            <a href="{{ $buildSortUrl('usertype_subject1', $currentSort, $currentDir, $queryParams) }}" class="d-inline-flex align-items-center text-reset">
                                                <span>{{ __('分類名１') }}</span>
                                                {!! $renderSortIcon($state) !!}
                                            </a>
                                        </th>
                                        @php $state = $arrowState('usertype_subject2'); @endphp
                                        <th class="{{ $sortClass('usertype_subject2') }}">
                                            <a href="{{ $buildSortUrl('usertype_subject2', $currentSort, $currentDir, $queryParams) }}" class="d-inline-flex align-items-center text-reset">
                                                <span>{{ __('分類名２') }}</span>
                                                {!! $renderSortIcon($state) !!}
                                            </a>
                                        </th>
                                        @php $state = $arrowState('usertype_subject3'); @endphp
                                        <th class="{{ $sortClass('usertype_subject3') }}">
                                            <a href="{{ $buildSortUrl('usertype_subject3', $currentSort, $currentDir, $queryParams) }}" class="d-inline-flex align-items-center text-reset">
                                                <span>{{ __('分類名３') }}</span>
                                                {!! $renderSortIcon($state) !!}
                                            </a>
                                        </th>
                                        @php $state = $arrowState('print_name'); @endphp
                                        <th class="{{ $sortClass('print_name') }}">
                                            <a href="{{ $buildSortUrl('print_name', $currentSort, $currentDir, $queryParams) }}" class="d-inline-flex align-items-center text-reset">
                                                <span>{{ __('印字名') }}</span>
                                                {!! $renderSortIcon($state) !!}
                                            </a>
                                        </th>
                                        <th>
                                            <span>{{__('適用料率')}}</span>
                                        </th>
                                        <th>
                                            <span>{{__('備考')}}</span>
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @forelse($list as $item)
                                        <tr>
                                            <td class="op-cell">
                                                <div class="d-flex align-items-center">
                                                    <input type="checkbox" class="mr-2 chkRow" name="pk[]" value="{{ $item->user_categoryid }}">
                                                    <a href="{{ route('usertype_edit', ['id' => $item->user_categoryid]) }}" class="btn btn-xs btn-default">{{ __('編集') }}</a>
                                                </div>
                                            </td>
                                            <td class="text-left">{{ $item->user_categoryid }}</td>
                                            <td class="text-left">{{ $item->sort_order }}</td>
                                            <td class="text-left">{{ $item->usertype_subject1 }}</td>
                                            <td class="text-left">{{ $item->usertype_subject2 }}</td>
                                            <td class="text-left">{{ $item->usertype_subject3 }}</td>
                                             <td class="text-left">{{ $item->print_name }}</td>
                                             <td class="text-right">{{ $item->usertype_money }}</td>
                                             <td class="text-left">{{ $item->usertype_remarks }}</td>
                                        </tr>
                                    @empty
                                        <tr>
                                            <td colspan="9" class="text-center text-muted py-4">{{ __('データが存在しません。') }}</td>
                                        </tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>

    <script>
        (function () {
            var chkAll = document.getElementById('chkAll');
            var chks = document.getElementsByClassName('chkRow');
            if (chkAll) {
                chkAll.addEventListener('change', function () {
                    Array.prototype.forEach.call(chks, function (c) { c.checked = chkAll.checked; });
                });
            }

            var filterReset = document.getElementById('btnFilterReset');
            if (filterReset) {
                filterReset.addEventListener('click', function () {
                    var form = document.getElementById('list-form');
                    if (!form) { return; }
                    Array.prototype.forEach.call(form.querySelectorAll('input[type="text"]'), function (input) {
                        input.value = '';
                    });
                    form.submit();
                });
            }

            var deleteBtn = document.getElementById('btnDeleteSelected');
            if (deleteBtn) {
                deleteBtn.addEventListener('click', function () {
                    var anyChecked = false;
                    Array.prototype.forEach.call(chks, function (c) { if (c.checked) { anyChecked = true; } });
                    if (!anyChecked) {
                        alert('削除対象の行を選択してください。');
                        return;
                    }
                    if (window.jQuery && typeof window.jQuery.confirm === 'function') {
                        window.jQuery.confirm({
                            title: '確認ダイアログ。',
                            content: '削除してよろしいですか？はい/いいえ',
                            buttons: {
                                ok: {
                                    text: 'はい',
                                    btnClass: 'btn-primary',
                                    keys: ['enter'],
                                    action: function () {
                                        document.getElementById('form_delete').submit();
                                    }
                                },
                                いいえ: function () {}
                            }
                        });
                    } else if (window.confirm('削除してよろしいですか？')) {
                        document.getElementById('form_delete').submit();
                    }
                });
            }

            var exportBtn = document.getElementById('btnExportCsv');
            if (exportBtn) {
                exportBtn.addEventListener('click', function () {
                    var exportForm = document.getElementById('form_export');
                    var filterForm = document.getElementById('list-form');
                    if (!exportForm || !filterForm) { return; }
                    ['filter_sort_order', 'filter_usertype_subject1', 'filter_usertype_subject2', 'filter_usertype_subject3', 'sort', 'sort_type'].forEach(function (name) {
                        var source = filterForm.querySelector('[name="' + name + '"]');
                        var target = exportForm.querySelector('[name="' + name + '"]');
                        if (source && target) {
                            target.value = source.value;
                        }
                    });
                    exportForm.submit();
                });
            }
        })();
    </script>


@endsection