<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;

class ParkingSearchController extends Controller
{
    // 初期表示
    public function index()
    {
        $result = $this->getParkData('', '', '');
        return view('general.swo5_1', $result);
    }

    // プルダウン選択
    public function search(Request $request)
    {
        $result = $this->getParkData(
            $request->input('conditions_city'),
            $request->input('conditions_station'), 
            $request->input('conditions_park')
        );

        return view('general.search', $result);
    }

    // 検索処理
    public function getParkData($city_name, $station_neighbor_station, $park_name)
    {
        // 駐輪場情報検索
        $park = \DB::table('park as p')
            ->select(
                'p.park_id',
                'p.park_name',
                'p.park_adrs',
                'p.price_memo',
                'p.park_latitude',
                'p.park_longitude',
                'p.update_grace_period_start_date',
                'p.update_grace_period_start_time',
                'p.update_grace_period_end_date',
                'p.update_grace_period_end_time',
                'c.city_name',
                's.station_neighbor_station'
            )
            ->leftJoin('city as c', 'p.city_id', '=', 'c.city_id')
            ->leftJoin(\DB::raw(
                '(SELECT park_id, station_neighbor_station FROM station WHERE station_id IN (SELECT MAX(station_id) FROM station GROUP BY park_id)) as s'
            ),'p.park_id','=','s.park_id');

        // プルダウン指定の条件でwhere句を付与
        if (!empty($city_name)) {
            $park = $park->where('c.city_name', $city_name);
        }
        if (!empty($station_neighbor_station)) {
            $park = $park->where('s.station_neighbor_station', $station_neighbor_station);
        }
        if (!empty($park_name)) {
            $park = $park->whereRaw("LEFT(p.park_ruby, 1) REGEXP '^[".$park_name."]'");
        }
        $park = $park->orderBy('p.park_ruby')->get();

        // 各マスタから追加情報を取得し、各ボタンの表示有無を判定する
        $form_data = [];
        $now = date('Y-m-d H:i:s');
        foreach ($park as $row) {

            // ゾーンマスタの情報を取得する
            $zoneInfo = \DB::table('zone as z')
                ->select(
                    'z.psection_id',
                    'z.ptype_id',
                    \DB::raw('SUM(z.zone_standard) as zone_standard'),
                    \DB::raw('SUM(z.zone_number) as zone_number'),
                    \DB::raw('SUM(z.zone_tolerance) as zone_tolerance'),
                    'ps.psection_subject',
                    'pt.ptype_subject'
                )
                ->join('ptype as pt', 'z.ptype_id', '=', 'pt.ptype_id')
                ->leftJoin('psection as ps', 'z.psection_id', '=', 'ps.psection_id')
                ->where('z.park_id', $row->park_id)
                ->groupBy('z.park_id', 'z.ptype_id', 'z.psection_id', 'ps.psection_subject', 'pt.ptype_subject')
                ->get();

            // ゾーンマスタが0件の場合、次のデータへ
            if ($zoneInfo->isEmpty()) {
                $form_data[] = [
                    'park_name' => $row->park_name,
                    'park_adrs' => $row->park_adrs,
                    'price_memo' => $row->price_memo,
                    'park_latitude' => $row->park_latitude,
                    'park_longitude' => $row->park_longitude,
                    'city_name' => $row->city_name,
                    'station_neighbor_station' => $row->station_neighbor_station,
                    'zone_data' => []
                ];
                continue;
            }
            
            // 更新期間内判定
            $update_start = $row->update_grace_period_start_date . ' ' . $row->update_grace_period_start_time;
            $update_end = $row->update_grace_period_end_date . ' ' . $row->update_grace_period_end_time;
            $is_update_period = ($now >= $update_start && $now <= $update_end);

            // ゾーンマスタの件数分だけループする
            $zone_data = [];
            foreach ($zoneInfo as $zone) {

                // 予約中件数取得
                $reservedCount = \DB::table('reserve')
                    ->where('park_id', $row->park_id)
                    ->where('psection_id', $zone->psection_id)
                    ->where('ptype_id', $zone->ptype_id)
                    ->where('valid_flag', 1)
                    ->count();

                // ステータス(表示ボタン)判定
                $status = 0; // 0:非表示, 1:定期契約, 2:空き待ち予約, 3:販売期間外
                $zone_vacant = $zone->zone_tolerance - $zone->zone_number - $reservedCount;
                if ($zone_vacant > 0 && $is_update_period) {          // 定期契約ボタン     (空き台数が1台以上かつ更新期間内)
                    $status = 1;
                } elseif ($zone_vacant <= 0 && $is_update_period) {   // 空き待ち予約ボタン (空き台数が0台以下かつ更新期間内)
                    $status = 2;
                } elseif ($zone_vacant <= 0 && !$is_update_period) {  // 販売期間外ボタン   (空き台数が0台以下かつ更新期間外)
                    $status = 3;
                }

                // 返却用データに追加
                $zone_data[] = [
                    'psection_subject' => $zone->psection_subject,
                    'ptype_subject' => $zone->ptype_subject,
                    'zone_standard' => $zone->zone_standard,
                    'zone_vacant' => $zone_vacant,
                    'status' => $status
                ];
            }

            // $zone_dataを並び替え
            usort($zone_data, function($a, $b) {
                // 第一優先: ptype_subject昇順
                $ptypeCmp = strcmp($a['ptype_subject'], $b['ptype_subject']);
                if ($ptypeCmp !== 0) {
                    return $ptypeCmp;
                }
                // 第二優先: psection_subject昇順
                $psectionCmp = strcmp($a['psection_subject'], $b['psection_subject']);
                if ($psectionCmp !== 0) {
                    return $psectionCmp;
                }
                // 第三優先: status昇順
                return $a['status'] <=> $b['status'];
            });

            // 画面返却用データに追加
            $form_data[] = [
                'park_name' => $row->park_name,
                'park_adrs' => $row->park_adrs,
                'price_memo' => $row->price_memo,
                'park_latitude' => $row->park_latitude,
                'park_longitude' => $row->park_longitude,
                'city_name' => $row->city_name,
                'station_neighbor_station' => $row->station_neighbor_station,
                'zone_data' => $zone_data
            ];
        }

        // プルダウン用データ取得
        $conditions = [$city_name, $station_neighbor_station, $park_name];
        $cities = \DB::table('city')->select('city_name')->orderBy('city_id')->get();
        $stations = \DB::table('station')->select('station_neighbor_station')->distinct()->orderBy('station_neighbor_station')->get();
        $parks = [
            '全て'=>'',
            'あ行'=>'あいうえおアイウエオ',
            'か行'=>'かきくけこがぎぐげごカキクケコガギグゲゴ',
            'さ行'=>'さしすせそざじずぜぞサシスセソザジズゼゾ',
            'た行'=>'たちつてとだぢづでどタチツテトダヂヅデド',
            'な行'=>'なにぬねのナニヌネノ',
            'は行'=>'はひふへほばびぶべぼぱぴぷぺぽハヒフヘホバビブベボパピプペポ',
            'ま行'=>'まみむめもマミムメモ',
            'や行'=>'やゆよヤユヨ',
            'ら行'=>'らりるれろラリルレロ',
            'わ行'=>'わをんワヲン   '
        ];

        // 車種区分リスト取得
        $psections = \DB::table('psection')->select('psection_subject')->orderBy('psection_id', 'asc')->limit(4)->get();

        // 情報返却
        return ['form_data' => $form_data, 'conditions' => $conditions, 'cities' => $cities, 'stations' => $stations, 'parks' => $parks, 'psections' => $psections];
    }
}