@extends('layouts.app')

@section('title', '利用者マスタ')

@section('content')
    @php
        $curSort = $sort ?? request('sort', 'user_seq');
        $curDir = strtolower($dir ?? request('dir', $sort_type ?? 'desc'));
        if (!in_array($curDir, ['asc', 'desc'], true)) {
            $curDir = 'desc';
        }

        $thClass = function (string $key) use ($curSort, $curDir) {
            if ($curSort !== $key) {
                return 'sorting';
            }
            return $curDir === 'asc' ? 'sorting_asc' : 'sorting_desc';
        };

        $urlFor = function (string $key) use ($curSort, $curDir) {
            $next = ($curSort === $key && $curDir === 'asc') ? 'desc' : 'asc';
            return route('users', keepUserListQuery([
                'sort' => $key,
                'dir' => $next,
            ]));
        };
    @endphp
    {{-- ▼ コンテンツヘッダー（パンくず） --}}
    <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>

    <section class="content">
        <div class="container-fluid">

            @if (session('success'))
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    {{ session('success') }}
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            @endif
            @if (session('error'))
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    {{ session('error') }}
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            @endif

            {{-- ===================== 案内文（図2 準拠） ===================== --}}
            <p class="text-muted small mb-2">
                <i class="fa fa-info-circle mr-1"></i>この画面のデータ修正等の必要はありません。
            </p>

            {{-- ===================== 絞り込みフィルター ===================== --}}
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">絞り込みフィルター</h3>
                </div>
                <div class="card-body">
                    <form action="{{ route('users') }}" method="get" id="filter-form">
                        {{-- ▼ ソート保持 --}}
                        <input type="hidden" name="sort" id="sort" value="{{ $sort }}">
                        <input type="hidden" name="dir" id="sort_type" value="{{ $curDir }}">

                        {{-- ▼ 1段目（左右2カラム） --}}
                        <div class="row">
                            {{-- 左カラム --}}
                            <div class="col-lg-6">
                                <div class="form-group d-flex align-items-center mb-2">
                                    <label class="filter-label">利用者ID</label>
                                    <input type="text" class="form-control filter-input" name="user_id"
                                        value="{{ $user_id ?? '' }}" placeholder="利用者ID">
                                </div>

                                {{-- 分類名１ --}}
                                <div class="form-group d-flex align-items-center mb-2">
                                    <label class="filter-label">分類名１</label>
                                    <select class="form-control filter-input" name="user_category1">
                                        <option value="">全て</option>
                                        @foreach($category1Options as $val)
                                            <option value="{{ $val }}" @selected(($user_category1 ?? '') === $val)>
                                                {{ $val }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                {{-- 分類名２ --}}
                                <div class="form-group d-flex align-items-center mb-2">
                                    <label class="filter-label">分類名２</label>
                                    <select class="form-control filter-input" name="user_category2">
                                        <option value="">全て</option>
                                        @foreach($category2Options as $val)
                                            <option value="{{ $val }}" @selected(($user_category2 ?? '') === $val)>
                                                {{ $val }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                {{-- 分類名３ --}}
                                <div class="form-group d-flex align-items-center mb-2">
                                    <label class="filter-label">分類名３</label>
                                    <select class="form-control filter-input" name="user_category3">
                                        <option value="">全て</option>
                                        @foreach($category3Options as $val)
                                            <option value="{{ $val }}" @selected(($user_category3 ?? '') === $val)>
                                                {{ $val }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                <div class="form-group d-flex align-items-center mb-2">
                                    <label class="filter-label">タグシリアル</label>
                                    <input type="text" class="form-control filter-input" name="user_tag_serial"
                                        value="{{ $user_tag_serial ?? '' }}" placeholder="タグシリアル">
                                </div>

                                <div class="form-group d-flex align-items-center mb-2">
                                    <label class="filter-label">退会フラグ</label>
                                    <select class="form-control filter-input" name="quit_flag">
                                        <option value="">全て</option>
                                        <option value="1" @if(($quit_flag ?? '') === '1') selected @endif>はい</option>
                                        <option value="0" @if(($quit_flag ?? '') === '0') selected @endif>いいえ</option>
                                    </select>
                                </div>
                            </div>

                            {{-- 右カラム --}}
                            <div class="col-lg-6">
                                <div class="form-group d-flex align-items-center mb-2">
                                    <label class="filter-label">フリガナ</label>
                                    <input type="text" class="form-control filter-input" name="user_phonetic"
                                        value="{{ $user_phonetic ?? '' }}" placeholder="フリガナ">
                                </div>

                                <div class="form-group d-flex align-items-center mb-2">
                                    <label class="filter-label">電話番号</label>
                                    <input type="text" class="form-control filter-input" name="phone"
                                        value="{{ $phone ?? '' }}" placeholder="電話番号">
                                </div>

                                <div class="form-group d-flex align-items-center mb-2">
                                    <label class="filter-label">メールアドレス</label>
                                    <input type="text" class="form-control filter-input" name="email"
                                        value="{{ $email ?? '' }}" placeholder="メールアドレス">
                                </div>

                                <div class="form-group d-flex align-items-center mb-2">
                                    <label class="filter-label">タグ・QR</label>
                                    <select class="form-control filter-input" name="tag_qr_flag">
                                        <option value="">全て</option>
                                        <option value="0" @if(($tag_qr_flag ?? '') === '0') selected @endif>タグ</option>
                                        <option value="1" @if(($tag_qr_flag ?? '') === '1') selected @endif>QR</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        {{-- ▼ 2段目：退会日 From〜To --}}
                        <div class="row">
                            <div class="col-lg-6">
                                <div class="form-group d-flex align-items-center mb-2">
                                    <label class="filter-label">退会日</label>
                                    <div class="d-flex flex-grow-1" style="max-width:600px;">
                                        <input type="date" class="form-control filter-input" name="quit_from"
                                            value="{{ $quit_from ?? '' }}">
                                        <span class="mx-2 align-self-center">〜</span>
                                        <input type="date" class="form-control filter-input" name="quit_to"
                                            value="{{ $quit_to ?? '' }}">
                                    </div>
                                </div>
                            </div>
                        </div>

                        {{-- ▼ 実行/解除 --}}
                        <div class="mt-2">
                            <button type="submit" class="btn btn btn-success">絞り込み</button>
                            <button type="button" class="btn btn btn-outline-secondary" id="btn-reset">解除</button>
                        </div>
                    </form>
                </div>
            </div>

            {{-- ▼ 見た目調整（ラベル間隔/入力高さ） --}}
            <style>
                /* ラベルと入力の水平方向の間隔を拡大 */
                .filter-label {
                    width: 150px;
                    margin: 0 14px 0 0;
                    font-weight: 600;
                    color: #555;
                }

                .filter-input {
                    max-width: 280px;
                }

                .card .form-control,
                .card .input-group-text,
                .card select.form-control {
                    height: calc(1.9rem + 2px);
                    padding: .25rem .5rem;
                    font-size: .9rem;
                }
            </style>

            {{-- ▼ 解除ボタン（hidden以外をリセットして送信） --}}
            <script>
                document.getElementById('btn-reset')?.addEventListener('click', function () {
                    const f = document.getElementById('filter-form');
                    if (!f) return;
                    Array.from(f.elements).forEach(el => {
                        if (el.tagName === 'INPUT') {
                            if (['text', 'date', 'number', 'email', 'tel', 'search'].includes(el.type)) el.value = '';
                        } else if (el.tagName === 'SELECT') {
                            el.selectedIndex = 0;
                        }
                    });
                    f.submit();
                });
            </script>

            {{-- ▼ CSV出力用の隠しフォーム（現在の絞り込み条件を同送） --}}
            <form id="csvForm" method="post" action="{{ route('users_export') }}" class="d-inline">
                @csrf
                {{-- 絞り込みのhidden（listのフォームnameと合わせる） --}}
                <input type="hidden" name="user_id" value="{{ $user_id ?? '' }}">
                <input type="hidden" name="user_categoryid" value="{{ $user_categoryid ?? '' }}">
                <input type="hidden" name="user_tag_serial" value="{{ $user_tag_serial ?? '' }}">
                <input type="hidden" name="quit_flag" value="{{ $quit_flag ?? '' }}">
                <input type="hidden" name="user_phonetic" value="{{ $user_phonetic ?? '' }}">
                <input type="hidden" name="phone" value="{{ $phone ?? '' }}">
                <input type="hidden" name="email" value="{{ $email ?? '' }}">
                <input type="hidden" name="tag_qr_flag" value="{{ $tag_qr_flag ?? '' }}">
                <input type="hidden" name="quit_from" value="{{ $quit_from ?? '' }}">
                <input type="hidden" name="quit_to" value="{{ $quit_to ?? '' }}">
            </form>

            <div class="text-right mb-2">
                全 {{ $list->total() }} 件中 {{ $list->firstItem() }}〜{{ $list->lastItem() }} 件を表示
            </div>

            <div class="d-flex align-items-center mb-2">
                <div>
                    <a href="{{ route('users_add', keepUserListQuery()) }}"class="btn btn-primary">新規</a>
                    {{-- ▼ クリックで隠しフォーム送信 --}}
                    <button type="button" class="btn btn-outline-success"
                        onclick="document.getElementById('csvForm').submit();">CSV出力</button>
                </div>
                <div class="ml-auto">
                    {{ $list->appends(keepUserListQuery())->links('pagination') }}
                </div>
            </div>

            {{-- ===================== 一覧 ===================== --}}
            <form action="{{ route('users_delete') }}" method="post" id="form_delete">
                @csrf

                <div id="users-list" class="table-responsive">
                    <table class="table table-bordered table-hover text-nowrap table-users dataTable"
                        style="min-width:1200px;">
                        <thead class="thead-light">
                            <tr>
                                <th style="width:110px;" class="{{ $thClass('user_id') }}">
                                    <a href="{{ $urlFor('user_id') }}" class="header-link">利用者ID</a>
                                </th>
                                <th style="width:110px;">タグ／ＱＲフラグ</th>
                                <th style="width:140px;">利用者分類１</th>
                                <th style="width:140px;">利用者分類２</th>
                                <th style="width:140px;">利用者分類３</th>
                                <th style="width:160px;">利用者名</th>
                                <th style="width:160px;" class="{{ $thClass('user_phonetic') }}">
                                    <a href="{{ $urlFor('user_phonetic') }}" class="header-link">フリガナ</a>
                                </th>
                                <th style="width:160px;">生年月日</th>
                                <th style="width:80px;">年齢</th>
                                <th style="width:140px;" class="{{ $thClass('user_mobile') }}">
                                    <a href="{{ $urlFor('user_mobile') }}" class="header-link">携帯電話番号</a>
                                </th>
                                <th style="width:140px;" class="{{ $thClass('user_homephone') }}">
                                    <a href="{{ $urlFor('user_homephone') }}" class="header-link">自宅電話番号</a>
                                </th>
                                <th style="width:220px;">メールアドレス</th>
                                <th style="width:140px;">本人確認書類</th>
                                <th style="width:150px;">本人確認チェック済</th>
                                <th style="width:160px;">本人確認日時</th>
                                <th style="width:110px;">退会フラグ</th>
                                <th style="width:110px;">退会日</th>
                                <th style="width:140px;">親権者氏名</th>
                                <th style="width:140px;">親権者フリガナ</th>
                                <th style="width:140px;">親権者生年月日</th>
                                <th style="width:140px;">親権者住所</th>
                                <th style="width:140px;">親権者電話番号</th>
                                <th style="width:140px;">親権者予備電話番号</th>
                                <th style="width:140px;">親権者メールアドレス</th>
                                <th style="width:140px;">通知方法</th>
                                <th style="width:140px;">個人情報同意フラグ</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($list as $item)
                                @php
                                    $userEditUrl = Route::has('users_edit')
                                        ? route('users_edit', ['seq' => $item->user_seq])
                                        : (Route::has('user_edit')
                                            ? route('user_edit', ['seq' => $item->user_seq])
                                            : url('/users/edit/' . $item->user_seq));
                                    $chk = (string) ($item->user_idcard_chk_flag ?? '0');
                                    $categoryDisplay = collect([
                                        $item->usertype_subject1 ?? '',
                                        $item->usertype_subject2 ?? '',
                                        $item->usertype_subject3 ?? '',
                                    ])->filter(fn($v) => $v !== '')->implode('/');
                                   @endphp
                                <tr>
                                    {{-- 利用者ID（リンク） --}}
                                    <td class="text-nowrap">
                                        <a href="{{ route('users_edit',array_merge(['seq' => $item->user_seq], keepUserListQuery())) }}">
                                            {{ $item->user_id }} {{ $item->user_name }}
                                        </a>
                                    </td>
                                    {{-- タグ／QR --}}
                                    <td>{{ $item->tag_qr_flag ? 'ＱＲ' : 'タグ' }}</td>
                                    {{-- 利用者分類ID／氏名／フリガナ --}}
                                    <td>{{ $item->usertype_subject1  }}</td>
                                    <td>{{ $item->usertype_subject2  }}</td>
                                    <td>{{ $item->usertype_subject3  }}</td>
                                    <td>{{ $item->user_name }}</td>
                                    <td>{{ $item->user_phonetic }}</td>
                                    {{-- 生年月日／年齢 --}}
                                    <td class="text-right">
                                        {{ $item->user_birthdate ? \Illuminate\Support\Str::limit($item->user_birthdate, 10, '') : '' }}
                                    </td>
                                    <td class="text-right">{{ $item->user_age }}</td>
                                    {{-- 連絡先 --}}
                                    <td class="text-right">{{ $item->user_mobile }}</td>
                                    <td class="text-right">{{ $item->user_homephone }}</td>
                                    <td class="text-nowrap">{{ $item->user_primemail }}</td>
                                    {{-- 本人確認（書類／チェック／日時） --}}
                                    <td>{{ __($item->user_idcard) }}</td>
                                    <td class="text-nowrap">{{ $chk === '1' ? '手動チェックOK' : '未チェック' }}</td>
                                    <td class="text-right">
                                        {{ $item->user_chk_day ? \Illuminate\Support\Str::limit($item->user_chk_day, 10, '') : '' }}
                                    </td>
                                    {{-- 退会 --}}
                                    <td>{{ $item->user_quit_flag ? 'はい' : 'いいえ' }}</td>
                                    <td>{{ $item->user_quitday ? \Illuminate\Support\Str::limit($item->user_quitday, 10, '') : '' }}
                                    </td>
                                    <td>{{ ''  }}</td>
                                    <td>{{ ''  }}</td>
                                    <td>{{ ''  }}</td>
                                    <td>{{ ''  }}</td>
                                    <td>{{ ''  }}</td>
                                    <td>{{ ''  }}</td>
                                    <td>{{ ''  }}</td>
                                    <td>{{ ''  }}</td>
                                    <td>{{ ''  }}</td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="15" class="text-center text-muted">データがありません。</td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </form>

            {{-- ▼ 一覧の背景色（グレー）を完全無効化：このページだけ適用 --}}
            <style>
                #users-list tbody td,
                #users-list tfoot th {
                    background: #fff !important;
                }

                .table-users thead th .header-link {
                    color: #495057 !important;
                    text-decoration: underline !important;
                    display: block;
                    white-space: nowrap;
                    padding-right: 1.8rem;
                }

                .table-users.dataTable thead th.sorting,
                .table-users.dataTable thead th.sorting_asc,
                .table-users.dataTable thead th.sorting_desc {
                    background-repeat: no-repeat;
                    background-position: right .6rem center !important;
                    padding-right: 1.8rem;
                }

                /* 斑馬柄などの行背景も抑止 */
                #users-list .table-striped tbody tr:nth-of-type(odd),
                #users-list .dataTable tbody tr:nth-of-type(odd) {
                    background: #fff !important;
                }

                /* hover 色を薄くする（必要なら） */
                #users-list .table-hover tbody tr:hover {
                    background-color: rgba(0, 0, 0, 0.02) !important;
                }
            </style>

        </div> {{-- /.container-fluid --}}
    </section>
@endsection