<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Park;
use App\Models\ParkingRegulation;

class ParkingRegulationsController extends Controller
{
    /**
     * 一覧表示
     */
    public function list(Request $request)
    {
        // park_id 検証
        $request->validate([
            'park_id' => 'required|integer|exists:park,park_id',
        ], [
            'park_id.required' => '駐輪場IDは必須です。',
            'park_id.integer' => '駐輪場IDは整数である必要があります。',
            'park_id.exists' => '指定された駐輪場が見つかりません。',
        ]);

        $parkId = (int) $request->input('park_id');

        // 駐輪場情報取得
        $park = Park::where('park_id', $parkId)->firstOrFail();

        // parking_regulations を取得し、psection / ptype 名を JOIN して表示
        $data = DB::table('parking_regulations')
            ->leftJoin('psection', 'parking_regulations.psection_id', '=', 'psection.psection_id')
            ->leftJoin('ptype', 'parking_regulations.ptype_id', '=', 'ptype.ptype_id')
            ->where('parking_regulations.park_id', $parkId)
            ->select(
                'parking_regulations.parking_regulations_seq',
                'parking_regulations.park_id',
                'parking_regulations.psection_id',
                'parking_regulations.ptype_id',
                'parking_regulations.regulations_text',
                'psection.psection_subject as psection_subject',
                'ptype.ptype_subject as ptype_subject'
            )
            ->orderBy('parking_regulations.psection_id')
            ->orderBy('parking_regulations.ptype_id')
            ->paginate(50);

        return view('admin.parking_regulations.list', [
            'park' => $park,
            'parkId' => $parkId,
            'regulations' => $data,
        ]);
    }

    /**
     * 新規作成フォーム表示／登録
     */
    public function add(Request $request)
    {
        $parkId = $request->input('park_id');

        // 駐輪場存在確認
        if (!$parkId) {
            return redirect()->back()->withErrors(['park_id' => '駐輪場IDが指定されていません。']);
        }

        $park = Park::where('park_id', $parkId)->firstOrFail();

        // マスタの選択肢取得
        $psections = DB::table('psection')->orderBy('psection_id')->get();
        $ptypes = DB::table('ptype')->orderBy('ptype_id')->get();

        if ($request->isMethod('post')) {
            // 登録処理
            $validated = $request->validate([
                'park_id' => 'required|integer|exists:park,park_id',
                'psection_id' => 'required|integer',
                'ptype_id' => 'required|integer',
                'regulations_text' => 'nullable|string',
            ], [
                'park_id.required' => '駐輪場IDは必須です。',
                'psection_id.required' => '車種区分は必須です。',
                'ptype_id.required' => '駐輪分類は必須です。',
            ]);

            // 重複チェック
            $exists = DB::table('parking_regulations')
                ->where('park_id', $validated['park_id'])
                ->where('psection_id', $validated['psection_id'])
                ->where('ptype_id', $validated['ptype_id'])
                ->exists();

            if ($exists) {
                return back()->withErrors(['duplicate' => '同じ組み合わせの規定が既に存在します。'])->withInput();
            }

            ParkingRegulation::create([
                'park_id' => $validated['park_id'],
                'psection_id' => $validated['psection_id'],
                'ptype_id' => $validated['ptype_id'],
                'regulations_text' => $validated['regulations_text'] ?? null,
            ]);

            return redirect()->route('parking_regulations_list', ['park_id' => $validated['park_id']])->with('success', '登録しました。');
        }

        return view('admin.parking_regulations.add', [
            'park' => $park,
            'parkId' => $parkId,
            'psections' => $psections,
            'ptypes' => $ptypes,
        ]);
    }

    /**
     * 編集フォーム表示
     */
    public function edit($seq, Request $request)
    {
        $record = DB::table('parking_regulations')->where('parking_regulations_seq', $seq)->first();
        if (!$record) {
            return redirect()->back()->withErrors(['not_found' => '指定の規定が見つかりません。']);
        }

        $park = Park::where('park_id', $record->park_id)->firstOrFail();

        $psections = DB::table('psection')->orderBy('psection_id')->get();
        $ptypes = DB::table('ptype')->orderBy('ptype_id')->get();

        return view('admin.parking_regulations.edit', [
            'park' => $park,
            'record' => $record,
            'psections' => $psections,
            'ptypes' => $ptypes,
        ]);
    }

    /**
     * 更新処理
     */
    public function update($seq, Request $request)
    {
        $validated = $request->validate([
            'psection_id' => 'required|integer',
            'ptype_id' => 'required|integer',
            'regulations_text' => 'nullable|string',
        ], [
            'psection_id.required' => '車種区分は必須です。',
            'ptype_id.required' => '駐輪分類は必須です。',
        ]);

        // 対象レコード取得
        $record = DB::table('parking_regulations')->where('parking_regulations_seq', $seq)->first();
        if (!$record) {
            return back()->withErrors(['not_found' => '指定の規定が見つかりません。']);
        }

        // 重複チェック（自分自身は除外）
        $exists = DB::table('parking_regulations')
            ->where('park_id', $record->park_id)
            ->where('psection_id', $validated['psection_id'])
            ->where('ptype_id', $validated['ptype_id'])
            ->where('parking_regulations_seq', '<>', $seq)
            ->exists();

        if ($exists) {
            return back()->withErrors(['duplicate' => '同じ組み合わせの規定が既に存在します。'])->withInput();
        }

        DB::table('parking_regulations')->where('parking_regulations_seq', $seq)->update([
            'psection_id' => $validated['psection_id'],
            'ptype_id' => $validated['ptype_id'],
            'regulations_text' => $validated['regulations_text'] ?? null,
            'updated_at' => now(),
        ]);

        return redirect()->route('parking_regulations_list', ['park_id' => $record->park_id])->with('success', '更新しました。');
    }

    /**
     * 削除処理
     */
    public function delete(Request $request)
    {
        $validated = $request->validate([
            'parking_regulations_seq' => 'required|integer',
        ], [
            'parking_regulations_seq.required' => '削除対象が指定されていません。',
        ]);

        $seq = (int) $validated['parking_regulations_seq'];

        $record = DB::table('parking_regulations')->where('parking_regulations_seq', $seq)->first();
        if (!$record) {
            return back()->withErrors(['not_found' => '指定の規定が見つかりません。']);
        }

        DB::table('parking_regulations')->where('parking_regulations_seq', $seq)->delete();

        return redirect()->route('parking_regulations_list', ['park_id' => $record->park_id])->with('success', '削除しました。');
    }
}
