@extends('layouts.general')
@section('content')
    <main role="main" id="" class="">
      <section id="" class="container mt20 mb20">
        <div class="row">
          <div class="col-12 col-lg-10 offset-0 offset-lg-1 mt20 mb20">
            <div class="card border-success">
              <div class="card-header border-success">
                <h5 class="card-title text-success">駐輪場をお選びください。</h5>
              </div>
              <div class="card-body">
                <form class="row form" method="post" action="{{ route('swo5_2') }}">
                  <div class="w-100 alert alert-success">
                    <h6><a class="text-success" data-toggle="collapse" href="#search-option" role="button" aria-expanded="false" aria-controls="search-option">絞込み条件を追加する</a></h6>
                    <div class="collapse row" id="search-option">
                      <div class="col-3">市町村名</div>
                      <div class="col-9 mb10">
                        <select class="form-control form-control-lg" name="conditions_city">
                          <option value="">市町村を選択してください</option>
                          @foreach($cities as $city)
                            @if(isset($conditions) && $conditions[0] == $city->city_name) {
                              <option value="{{ $city->city_name }}" selected>{{ $city->city_name }}</option>
                            @else
                              <option value="{{ $city->city_name }}">{{ $city->city_name }}</option>
                            @endif
                          @endforeach
                        </select>
                      </div>
                      <div class="col-3">駅名</div>
                      <div class="col-9 mb10">
                        <select class="form-control form-control-lg" name="conditions_station">
                          <option value="">駅名を選択してください</option>
                          @foreach($stations as $station)
                            @if(isset($conditions) && $conditions[1] == $station->station_neighbor_station) {
                              <option value="{{ $station->station_neighbor_station }}" selected>{{ $station->station_neighbor_station }}</option>
                            @else
                              <option value="{{ $station->station_neighbor_station }}">{{ $station->station_neighbor_station }}</option>
                            @endif
                          @endforeach
                        </select>
                      </div>
                      <div class="col-3">駐車場名</div>
                      <div class="col-9 mb10">
                        <select class="form-control form-control-lg" name="conditions_park">
                          @foreach($parks as $key => $value)
                            @if(isset($conditions) && $conditions[2] == $value) {
                              <option value="{{ $value }}" selected>{{ $key }}</option>
                            @else
                              <option value="{{ $value }}">{{ $key }}</option>
                            @endif
                          @endforeach
                        </select>
                      </div>
                    </div>
                  </div>
                  <script>
                  $(function() {
                    $('select[name="conditions_city"], select[name="conditions_station"], select[name="conditions_park"]').on('change', function() {
                      $(this).closest('form').submit();
                    });
                  });
                  </script>
                  @csrf
                </form>
                <table id="searchTable" class="tablesorter table table-striped">
                  <thead>
                    <tr>
                      <th width="20%">駐輪場名</th>
                      <th width="30%">市町村名</th>
                      <th width="20%">駅名</th>
                      @foreach($psections as $psection)
                        <th width="10%">{{ $psection->psection_subject }}</th>
                      @endforeach
                    </tr>
                  </thead>
                  <tbody>
                    @php
                      $perPage = 10;
                      $page = request()->get('page', 1);
                      $total = count($form_data);
                      $start = ($page - 1) * $perPage;
                      $pagedData = array_slice($form_data, $start, $perPage);
                      $lastPage = ceil($total / $perPage);
                    @endphp
                    @foreach($pagedData as $data)
                    <tr>
                      <td>
                        <a href="#placeModal"
                          data-toggle="modal"
                          data-target="#placeModal"
                          data-park_name="{{ $data['park_name'] }}"
                          data-park_adrs="{{ $data['park_adrs'] ?? '' }}"
                          data-price_memo="{{ $data['price_memo'] ?? '' }}"
                          data-park_latitude="{{ $data['park_latitude'] ?? '' }}"
                          data-park_longitude="{{ $data['park_longitude'] ?? '' }}"
                          data-city_name="{{ $data['city_name'] }}"
                          data-station="{{ $data['station_neighbor_station'] }}"
                          data-zone_data='@json($data["zone_data"])'>
                          {{ $data['park_name'] }}
                        </a>
                      </td>
                      <td>{{ $data['city_name'] }}</td>
                      <td>{{ $data['station_neighbor_station'] }}</td>
                      @foreach($psections as $psection)
                        <td>
                          @foreach($data['zone_data'] as $zone)
                            @if($zone['psection_subject'] == $psection->psection_subject)
                              @if($zone['status'] == 1)
                                <a href="{{route('user.info')}}" class="btn btn-block btn-sm btn-outline-success">定期契約</a>
                              @elseif($zone['status'] == 2)
                                <a href="{{route('park_waitlist.index')}}" class="btn btn-block btn-sm btn-outline-primary">空き待ち予約</a>
                              @elseif($zone['status'] == 3)
                                <a href="{{route('park_waitlist.index')}}" class="btn btn-block btn-sm btn-secondary">販売期間外</a>
                              @endif
                              @break;
                            @endif
                          @endforeach
                        </td>
                      @endforeach
                    </tr>
                    @endforeach
                  </tbody>
                </table>
                <nav aria-label="searchTable-pager">
                  <ul class="pagination justify-content-center">
                    @if($lastPage > 1)
                      {{-- 前へ --}}
                      <li class="page-item {{ $page == 1 ? 'disabled' : '' }}">
                        <a class="page-link text-success" href="?page={{ $page - 1 }}" aria-label="前">
                          <span aria-hidden="true">&laquo;</span><span class="sr-only">前</span>
                        </a>
                      </li>
                      {{-- ページ番号 --}}
                      @for($i = 1; $i <= $lastPage; $i++)
                        <li class="page-item {{ $page == $i ? 'active' : '' }}">
                          <a class="page-link text-success" href="?page={{ $i }}">{{ $i }}</a>
                        </li>
                      @endfor
                      {{-- 次へ --}}
                      <li class="page-item {{ $page == $lastPage ? 'disabled' : '' }}">
                        <a class="page-link text-success" href="?page={{ $page + 1 }}" aria-label="次">
                          <span aria-hidden="true">&raquo;</span><span class="sr-only">次</span>
                        </a>
                      </li>
                    @endif
                  </ul>
                </nav>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>

    <!-- Modal -->
    <div class="modal fade" id="placeModal" tabindex="-1" role="dialog" aria-hidden="true">
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <script>
            $('#placeModal').on('show.bs.modal', function (event) {
              var button = $(event.relatedTarget);
              var parkName = button.data('park_name') || '';
              var parkAdrs = button.data('park_adrs') || '';
              var parkMemo = button.data('price_memo') || '';
              var lat = button.data('park_latitude') || '';
              var lng = button.data('park_longitude') || '';
              $('#parkName').text(parkName).attr('data-park_name', parkName);
              $('#parkAdrs').text('住所：' + parkAdrs).attr('data-park_adrs', parkAdrs);
              $('#parkmemo').text(parkMemo).attr('data-price_memo', parkMemo);
              $('#parkMap').attr('src', 'https://www.google.com/maps?q=' + lat + ',' + lng + '&z=15&output=embed');

              // zone_dataはJSON文字列として渡されているのでパース
              var zoneData = button.data('zone_data') || [];

              // psection_subjectごとの標準収容台数を集計
              var standardMap = {};
              if (zoneData && Array.isArray(zoneData)) {
                zoneData.forEach(function(zone) {
                  if (!standardMap[zone.psection_subject]) {
                  standardMap[zone.psection_subject] = 0;
                  }
                  standardMap[zone.psection_subject] += parseInt(zone.zone_standard, 10) || 0;
                });
                }
                // 表示用文字列を生成
                var standardText = '';
                var keys = Object.keys(standardMap);
                if (keys.length > 0) {
                standardText = '【標準収容台数】';
                standardText += keys.map(function(key) {
                  return key + '：' + standardMap[key] + '台';
                }).join(' / ');
              }
              $('#parkStandard').text(standardText);
              
              // 各ゾーンの空き台数・ボタンを表示
              var html = '';
              if (zoneData && Array.isArray(zoneData)) {
                var grouped = {};
                zoneData.forEach(function(zone) {
                  if (!grouped[zone.ptype_subject]) grouped[zone.ptype_subject] = [];
                  grouped[zone.ptype_subject].push(zone);
                });
                Object.keys(grouped).forEach(function(ptype) {
                  html += '<h4 class="mt-3">' + ptype + '</h4>';
                  grouped[ptype].forEach(function(zone) {
                  html += '<div class="d-flex align-items-center mb-2">';
                  html += '<span>' + zone.psection_subject + ':空き' + zone.zone_vacant + '台</span>';
                  if (zone.status == 1) {
                    html += '<a href="{{route('regular_contract.create')}}" class="btn btn-sm btn-outline-success ml-2">定期契約</a>';
                  } else if (zone.status == 2) {
                    html += '<a href="{{route('park_waitlist.index')}}" class="btn btn-sm btn-outline-primary ml-2">空き待ち予約</a>';
                  } else if (zone.status == 3) {
                    html += '<a href="{{route('park_waitlist.index')}}" class="btn btn-sm btn-outline-secondary ml-2">販売期間外</a>';
                  }
                  html += '</div>';
                  });
                });
              }
              $('#zoneData').html(html);
            });
            </script>
          <div class="modal-header">
            <h5 class="modal-title" id="parkName" data-park_name=""></h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="閉じる"><span aria-hidden="true">&times;</span></button>
          </div>
          <div class="modal-body">
            <iframe id="parkMap" src="" width="100%" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
            <p class="small">
              <span id="parkAdrs"> </span>
              <span id="parkStandard"></span><br />
              <span id="parkmemo"></span>
            </p>
            <span id="zoneData"></span>
            <div class="text-right"><button type="button" class="btn btn-outline-secondary" data-dismiss="modal">閉じる</button></div>
          </div>
        </div>
        <div class="modal-footer"></div>
      </div>
    </div>
@endsection