<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
use App\Mail\ReservationCancelledMail;

class ParkWaitlistController extends Controller
{
    // 空き待ち状況一覧画面
    public function index(Request $request)
    {
        $user_id = session('user_id');
        if (!$user_id) {
            return redirect('/login');
        }
        $user = DB::table('user')->where('user_id', $user_id)->first();

        // 空き待ち予約状況データ取得
        $waitlists = DB::table('reserve')
            ->where('reserve.user_id', $user_id)
            ->where('reserve.valid_flag', 1)
            ->leftJoin('park', 'reserve.park_id', '=', 'park.park_id')
            ->leftJoin('station', 'park.park_id', '=', 'station.park_id')
            ->leftJoin('ptype', 'reserve.ptype_id', '=', 'ptype.ptype_id')
            ->leftJoin('psection', 'reserve.psection_id', '=', 'psection.psection_id')
            ->select(
                'reserve.reserve_id',
                'reserve.reserve_date',
                'park.park_name',
                'station.station_neighbor_station',
                'ptype.ptype_subject',
                'psection.psection_subject'
            )
            ->orderBy('reserve.reserve_date', 'desc')
            ->get();

        \Log::info('空き待ち状況確認画面にアクセス', [
            'user_id' => $user_id,
        ]);

        return view('park_waitlist.index', [
            'active_menu' => 'SWC-11-1', // この画面のID
            'user_name' => $user ? $user->user_name : '', // ユーザー名（ヘッダー用）
            'waitlists' => $waitlists,
        ]);
    }

    public function check(Request $request)
    {
        $user_id = session('user_id');
        if (!$user_id) {
            return redirect('/login');
        }

        $park_id = $request->input('park_id');
        $psection_id = $request->input('psection_id');
        $ptype_id = $request->input('ptype_id');

        $existingReservation = DB::table('reserve')
            ->where('user_id', $user_id)
            ->where('park_id', $park_id)
            ->where('psection_id', $psection_id)
            ->where('ptype_id', $ptype_id)
            ->where('valid_flag', 1)
            ->first();

        if ($existingReservation) {
            return response()->json(['status' => 'exists']);
        } else {
            return response()->json(['status' => 'ok']);
        }
    }

    public function create(Request $request)
    {
        $user_id = session('user_id');
        if (!$user_id) {
            return redirect('/login');
        }
        $user = DB::table('user')->where('user_id', $user_id)->first();

        $park_id = $request->input('park_id');
        $psection_id = $request->input('psection_id');
        $ptype_id = $request->input('ptype_id');

        // 予約順を決定
        $reserve_order = DB::table('reserve')
            ->where('park_id', $park_id)
            ->where('psection_id', $psection_id)
            ->where('ptype_id', $ptype_id)
            ->where('valid_flag', 1)
            ->count() + 1;

        // 予約情報を追加
        DB::table('reserve')->insert([
            'created_at' => now(),
            'updated_at' => now(),
            'user_categoryid' => $user->user_categoryid,
            'user_id' => $user_id,
            'park_id' => $park_id,
            'psection_id' => $psection_id,
            'reserve_date' => now(),
            'valid_flag' => 1,
            'ptype_id' => $ptype_id,
            'reserve_order' => $reserve_order
        ]);

        return redirect()->route('park_waitlist.index');
    }

    public function cancelConfirm($reserve_id)
    {
        $user_id = session('user_id');
        if (!$user_id) {
            return redirect('/login');
        }
        $user_name = DB::table('user')->where('user_id', $user_id)->value('user_name');

        \Log::info('空き待ち状況確認 - キャンセル確認画面にアクセス', [
            'user_id' => $user_id,
        ]);
        
        return view('park_waitlist.cancel', [
            'active_menu' => 'SWC-11-1', // この画面のID
            'user_name' => $user_name, // ユーザー名（ヘッダー用）
            'reserve_id' => $reserve_id,
        ]);
    }

    public function cancel($reserve_id)
    {
        $user_id = session('user_id');
        if (!$user_id) {
            return redirect('/login');
        }
        $user = DB::table('user')->where('user_id', $user_id)->first();

        // 定期予約をキャンセル
        DB::table('reserve')->where('reserve_id', $reserve_id)->update([
            'valid_flag' => 0,
            'updated_at' => now(),
            'reserve_cancelday' => date('Y-m-d'),
        ]);

        // メール送信用データ取得
        $reserve = DB::table('reserve')
            ->leftJoin('park', 'reserve.park_id', '=', 'park.park_id')
            ->leftJoin('psection', 'reserve.psection_id', '=', 'psection.psection_id')
            ->leftJoin('ptype', 'reserve.ptype_id', '=', 'ptype.ptype_id')
            ->select(
                'park.park_name',
                'psection.psection_subject',
                'ptype.ptype_subject'
            )
            ->where('reserve.reserve_id', $reserve_id)
            ->first();

        // メール送信処理
        try {
            Mail::to($user->user_primemail)->send(
                new ReservationCancelledMail(
                    $user->user_name,
                    $reserve
                )
            );
        } catch (\Exception $e) {
            Log::error('予約キャンセルメール送信エラー: ' . $e->getMessage());
        }

        \Log::info('空き待ち状況確認 - キャンセル完了画面にアクセス', [
            'user_id' => $user_id,
        ]);

        return view('park_waitlist.cancel_complete', [
            'reserve' => $reserve,
            'active_menu' => 'SWC-11-1', // この画面のID
            'user_name' => $user ? $user->user_name : '', // ユーザー名（ヘッダー用）
        ]);
    }
}
