{{-- resources/views/admin/reserves/edit.blade.php --}}
@extends('layouts.app')
@section('title', '定期予約マスタ - 編集')

@section('content')
<style>
  .rv-edit,
  .rv-edit .card,
  .rv-edit .form-control,
  .rv-edit .btn,
  .rv-edit .breadcrumb{
    font-family:"Noto Sans JP","Hiragino Kaku Gothic ProN","Meiryo",system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
    font-size:13px;
    line-height:1.45;
  }
  .rv-form .field{
    display:flex;
    align-items:center;
    gap:1.25rem;
    margin-bottom:.75rem;
  }
  .rv-form .label{
    flex:0 0 180px;
    margin:0;
    color:#333;
    font-weight:600;
    white-space:nowrap;
  }
  .rv-form .label .req{
    color:#e3342f;
    margin-left:.35rem;
  }
  .rv-form .input{
    flex:1 1 auto;
    min-width:260px;
  }
  .rv-form .form-control{
    height:calc(2.0rem + 2px);
    padding:.25rem .5rem;
  }
  .rv-form .form-control[readonly],
  .rv-form .form-control:disabled{
    background:#f5f5f5;
    color:#444;
  }
  .rv-form .radio-inline{
    display:inline-flex;
    align-items:center;
    gap:.35rem;
    margin-right:1.25rem;
  }
  .breadcrumb-inline{
    white-space:nowrap;
    color:#666;
  }
  .rv-edit .card-header{
    display:flex;
    justify-content:flex-start;
    gap:.5rem;
    padding:1rem 1.25rem;
    border-bottom:1px solid #f1f1f1;
  }
  .rv-edit .card-footer{
    background:#fff;
    border-top:1px solid #f1f1f1;
    display:flex;
    justify-content:flex-start;
    gap:.5rem;
    padding:1rem 1.25rem;
  }
  @media (max-width: 576px){
    .rv-form .field{
      flex-direction:column;
      align-items:flex-start;
    }
    .rv-form .label{
      flex:none;
    }
    .rv-toolbar{
      flex-direction:column;
      align-items:stretch;
    }
    .rv-toolbar .btn{
      width:100%;
    }
  }
</style>

@php
  // 読み取り専用表示用：既存のオプションから名称を推定（コントローラを変更せず表示可能）
  $userName = '';
  if (!empty($row->user_id ?? null) && !empty($userOptions[$row->user_id] ?? null)) {
      // $userOptions 形如 "12345 山田太郎" → 去掉开头ID只留名字
      $userName = trim(preg_replace('/^\s*\d+\s*/', '', $userOptions[$row->user_id]));
  }
  $parkName = '';
  if (!empty($row->park_id ?? null) && !empty($parkOptions[$row->park_id] ?? null)) {
      $parkName = trim(preg_replace('/^\s*\d+\s*/', '', $parkOptions[$row->park_id]));
  }
@endphp

<div class="rv-edit">
  {{-- ヘッダ --}}
  <div class="content-header">
    <div class="container-fluid">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <h1 class="m-0 text-dark">編集</h1>
        <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"><a href="{{ route('reserves') }}">定期予約マスタ</a></li>
            <li class="breadcrumb-item active">編集</li>
          </ol>
        </div>
      </div>

      @if(session('success'))
        <div class="alert alert-success py-2 px-3 my-2">{{ session('success') }}</div>
      @endif
      @if($errors->any())
        <div class="alert alert-danger py-2 px-3 my-2">
          <ul class="mb-0">@foreach($errors->all() as $e)<li>{{ $e }}</li>@endforeach</ul>
        </div>
      @endif
    </div>
  </div>

  {{-- 本体 --}}
  <section class="content">
    <div class="container-fluid">
      <div class="card rv-form">
        <div class="card-header">
          <button type="submit" class="btn btn-default btn-sm js-confirm-submit" form="edit-form">登録</button>
          <button type="button" id="btnDeleteTop" class="btn btn-default btn-sm">削除</button>
          <a href="{{ route('reserves') }}" class="btn btn-default btn-sm">戻る</a>
        </div>

        {{-- GET と同一ルートで POST 更新 --}}
        <form id="edit-form" method="post" action="{{ route('reserves_edit', ['reserve_id'=>$row->reserve_id]) }}">
          @csrf
           <div class="card-body">
            <div class="field">
              <label class="label">定期予約ID</label>
              <div class="input">
                <input type="text" class="form-control" value="{{ $row->reserve_id }}" readonly>
              </div>
            </div>

            <div class="field">
              <label class="label">定期契約ID</label>
              <div class="input">
                <input type="text" name="contract_id" class="form-control" placeholder="定期契約ID"
                  value="{{ old('contract_id', $row->contract_id ?? '') }}" readonly>
              </div>
            </div>

            <div class="field">
              <label class="label">定期契約日時</label>
              <div class="input">
                <input type="text" name="contract_created_at" class="form-control" placeholder="yyyy/mm/dd hh:mm:ss"
                  value="{{ old('contract_created_at', $row->contract_created_at ?? '') }}">
              </div>
            </div>

            <div class="field">
              <label class="label">利用者分類ID</label>
              <div class="input">
                <select name="user_categoryid" class="form-control">
                  <option value="">全て</option>
                  @foreach(($userTypeOptions ?? []) as $k => $v)
                    <option value="{{ $k }}" {{ (string)old('user_categoryid', $row->user_categoryid ?? '') === (string)$k ? 'selected' : '' }}>
                      {{ $v }}
                    </option>
                  @endforeach
                </select>
              </div>
            </div>

            <div class="field">
              <label class="label">利用者ID<span class="req">*</span></label>
              <div class="input">
                @php
                  $selectedUserId = old('user_id', $row->user_id ?? '');
                  $selectedUserLabel = $selectedUserId !== '' ? ($userOptions[$selectedUserId] ?? $selectedUserId) : '';
                @endphp
                <input type="text" class="form-control" value="{{ $selectedUserLabel }}" readonly>
                <input type="hidden" name="user_id" value="{{ $selectedUserId }}">
              </div>
            </div>

            <div class="field">
              <label class="label">予約日時<span class="req">*</span></label>
              <div class="input">
                <input type="text" name="reserve_date" class="form-control" placeholder="yyyy/mm/dd hh:mm:ss"
                  value="{{ old('reserve_date', $row->reserve_date ?? '') }}">
              </div>
            </div>

            <div class="field">
              <label class="label">駐輪場ID<span class="req">*</span></label>
              <div class="input">
                <select name="park_id" class="form-control" required>
                  <option value="">選択してください</option>
                  @foreach(($parkOptions ?? []) as $k => $v)
                    <option value="{{ $k }}" {{ (string)old('park_id', $row->park_id ?? '') === (string)$k ? 'selected' : '' }}>
                      {{ $v }}
                    </option>
                  @endforeach
                </select>
              </div>
            </div>

            <div class="field">
              <label class="label">駐輪場所ID<span class="req">*</span></label>
              <div class="input">
                <select name="price_parkplaceid" class="form-control" required>
                  <option value="">選択してください</option>
                  @foreach(($parkplaceOptions ?? []) as $k => $v)
                    <option value="{{ $k }}" {{ (string)old('price_parkplaceid', $row->price_parkplaceid ?? '') === (string)$k ? 'selected' : '' }}>
                      {{ $v }}
                    </option>
                  @endforeach
                </select>
              </div>
            </div>

            <div class="field">
              <label class="label">車種区分ID</label>
              <div class="input">
                <select name="psection_id" class="form-control">
                  <option value="">選択してください</option>
                  @foreach(($psectionOptions ?? []) as $k => $v)
                    <option value="{{ $k }}" {{ (string)old('psection_id', $row->psection_id ?? '') === (string)$k ? 'selected' : '' }}>
                      {{ $v }}
                    </option>
                  @endforeach
                </select>
              </div>
            </div>

            <div class="field">
              <label class="label">駐輪分類ID</label>
              <div class="input">
                <select name="ptype_id" class="form-control">
                  <option value="">選択してください</option>
                  @foreach(($ptypeOptions ?? []) as $k => $v)
                    <option value="{{ $k }}" {{ (string)old('ptype_id', $row->ptype_id ?? '') === (string)$k ? 'selected' : '' }}>
                      {{ $v }}
                    </option>
                  @endforeach
                </select>
              </div>
            </div>

            <div class="field">
              <label class="label">減免措置</label>
              <div class="input">
                @php $reduction = old('reduction', $row->reduction ?? ''); @endphp
                <label class="radio-inline">
                  <input type="radio" name="reduction" value="1" {{ (string)$reduction === '1' ? 'checked' : '' }}> あり
                </label>
                <label class="radio-inline">
                  <input type="radio" name="reduction" value="0" {{ (string)$reduction === '0' ? 'checked' : '' }}> なし
                </label>
              </div>
            </div>

            <div class="field">
              <label class="label">自動リマインド日</label>
              <div class="input">
                <input type="text" name="auto_remind_date" class="form-control" placeholder="yyyy/mm/dd"
                  value="{{ old('auto_remind_date', $row->auto_remind_date ?? '') }}">
              </div>
            </div>

            <div class="field">
              <label class="label">手動リマインド日</label>
              <div class="input">
                <input type="text" name="manual_remind_date" class="form-control" placeholder="yyyy/mm/dd"
                  value="{{ old('manual_remind_date', $row->manual_remind_date ?? '') }}">
              </div>
            </div>

            <div class="field">
              <label class="label">８００Ｍ以内フラグ</label>
              <div class="input">
                @php $m800 = old('within_800m_flag', $row->within_800m_flag ?? ''); @endphp
                <label class="radio-inline">
                  <input type="radio" name="within_800m_flag" value="1" {{ (string)$m800 === '1' ? 'checked' : '' }}> ８００M以内
                </label>
                <label class="radio-inline">
                  <input type="radio" name="within_800m_flag" value="0" {{ (string)$m800 === '0' ? 'checked' : '' }}> ８００M以内ではない
                </label>
              </div>
            </div>

            <div class="field">
              <label class="label">解約日</label>
              <div class="input">
                <input type="text" name="contract_cancelday" class="form-control" placeholder="yyyy/mm/dd"
                  value="{{ old('contract_cancelday', $row->contract_cancelday ?? '') }}">
              </div>
            </div>

            <div class="field">
              <label class="label">有効フラグ</label>
              <div class="input">
                @php $valid = old('valid_flag', $row->valid_flag ?? ''); @endphp
                <label class="radio-inline">
                  <input type="radio" name="valid_flag" value="1" {{ (string)$valid === '1' ? 'checked' : '' }}> 有効
                </label>
                <label class="radio-inline">
                  <input type="radio" name="valid_flag" value="0" {{ (string)$valid === '0' ? 'checked' : '' }}> 無効
                </label>
              </div>
            </div>

            <div class="field">
              <label class="label">空き待ちメール送信日時</label>
              <div class="input">
                <input type="text" name="mail_sent_at" class="form-control" placeholder="yyyy/mm/dd hh:mm:ss"
                  value="{{ old('mail_sent_at', $row->mail_sent_at ?? '') }}">
              </div>
            </div>

            <div class="field">
              <label class="label">手動通知</label>
              <div class="input">
                @php $mnotice = old('manual_notice', $row->manual_notice ?? ''); @endphp
                <label class="radio-inline">
                  <input type="radio" name="manual_notice" value="0" {{ (string)$mnotice === '0' ? 'checked' : '' }}> 手動通知
                </label>
                <label class="radio-inline">
                  <input type="radio" name="manual_notice" value="1" {{ (string)$mnotice === '1' ? 'checked' : '' }}> メール通知
                </label>
              </div>
            </div>

            <div class="field">
              <label class="label">手動通知方法</label>
              <div class="input">
                @php $mhow = old('manual_notice_method', $row->manual_notice_method ?? ''); @endphp
                <label class="radio-inline">
                  <input type="radio" name="manual_notice_method" value="tel" {{ $mhow === 'tel' ? 'checked' : '' }}> 電話
                </label>
                <label class="radio-inline">
                  <input type="radio" name="manual_notice_method" value="post" {{ $mhow === 'post' ? 'checked' : '' }}> 郵送
                </label>
              </div>
            </div>

            <div class="field">
              <label class="label">空き待ち順</label>
              <div class="input">
                <input type="number" name="waitlist_order" class="form-control" min="0" step="1" placeholder="空き待ち順"
                  value="{{ old('waitlist_order', $row->waitlist_order ?? '') }}">
              </div>
            </div>
          </div>

          {{-- 下部操作（参照画面の下部にも登録/削除ボタンあり） --}}
          <div class="card-footer">
            <button type="submit" class="btn btn-default btn-sm js-confirm-submit">登録</button>
            <button type="button" id="btnDeleteBottom" class="btn btn-default btn-sm">削除</button>
            <a href="{{ route('reserves') }}" class="btn btn-default btn-sm">戻る</a>
           </div>
         </form>

        {{-- 削除POST（confirmed + ids[]） --}}
        <form id="del-form" method="post" action="{{ route('reserves_delete') }}" style="display:none;">
          @csrf
          <input type="hidden" name="confirmed" value="1">
          <input type="hidden" name="ids[]" value="{{ $row->reserve_id }}">
        </form>
      </div>
    </div>
  </section>
</div>

<script>
  (function(){
    var editForm = document.getElementById('edit-form');

    function handleSubmitConfirm(event){
      event.preventDefault();
      var formAttr = this.getAttribute('form');
      var targetForm = this.form || (formAttr ? document.getElementById(formAttr) : editForm);
      if (!targetForm) { return; }
      var submitAction = function(){ targetForm.submit(); };

      if (window.jQuery && typeof window.jQuery.confirm === 'function') {
        window.jQuery.confirm({
          title: '確認ダイアログ。',
          content: '！登録してよろしいですか？　はい/いいえ',
          buttons: {
            ok: { text: 'はい', btnClass: 'btn-primary', keys: ['enter'], action: submitAction },
            いいえ: function () {}
          }
        });
      } else if (window.confirm('！登録してよろしいですか？　はい/いいえ')) {
        submitAction();
      }
    }

    var submitButtons = document.querySelectorAll('.js-confirm-submit');
    Array.prototype.forEach.call(submitButtons, function(btn){
      btn.addEventListener('click', handleSubmitConfirm);
    });

    function handleDelete(){
      if(window.confirm('削除してよろしいですか？　はい/いいえ')){
        document.getElementById('del-form').submit();
      }
    }
    var topBtn = document.getElementById('btnDeleteTop');
    var bottomBtn = document.getElementById('btnDeleteBottom');
    if(topBtn){ topBtn.addEventListener('click', handleDelete); }
    if(bottomBtn){ bottomBtn.addEventListener('click', handleDelete); }
  })();
</script>
@endsection
