<?php

namespace App\Http\Controllers\Admin;

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


class StationController extends Controller
{
    /**
     * 一覧表示
     */
    public function list(Request $request)
    {
        $sort = $request->input('sort', 'station_id');
        $sort_type = $request->input('sort_type', 'asc');

        $allowedSorts = [
            'station_id',
            'park_id',
            'station_neighbor_station',
            'station_name_ruby',
            'station_route_name'
        ];
        if (!in_array($sort, $allowedSorts)) {
            $sort = 'station_id';
        }

        if (!in_array($sort_type, ['asc', 'desc'])) {
            $sort_type = 'asc';
        }

        $list = Station::select([
                'station_id',
                'station_neighbor_station',
                'station_name_ruby',
                'station_route_name',
                'park_id',
                'operator_id',
                'station_latitude',
                'station_longitude',
            ])
            ->orderBy($sort, $sort_type)
            ->paginate(20);

        return view('admin.stations.list', compact('list', 'sort', 'sort_type'));
    }


    public function add(Request $request)
    {
        if ($request->isMethod('get')) {
            // 駐車場リストを取得（プルダウン用）
            $parks = Park::orderBy('park_name')->pluck('park_name', 'park_id');

            // 新規時：空レコードを渡す
            return view('admin.stations.add', [
                'isEdit' => false,
                'record' => new Station(),
                'parks'  => $parks, // ← これを追加
            ]);
        }

        // POST時：バリデーション
        $rules = [
            'station_neighbor_station' => 'required|string|max:255',
            'station_name_ruby'        => 'required|string|max:255',
            'station_route_name'       => 'required|string|max:255',
            'station_latitude'         => 'required|numeric',
            'station_longitude'        => 'required|numeric',
            'operator_id'              => 'nullable|integer',
            'park_id'                  => 'required|integer',
        ];

        $messages = [
            'station_latitude.required'  => '緯度は必須項目です。',
            'station_longitude.required' => '経度は必須項目です。',
        ];

        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        DB::transaction(function () use ($request) {
            Station::create($request->only([
                'station_neighbor_station',
                'station_name_ruby',
                'station_route_name',
                'station_latitude',
                'station_longitude',
                'park_id',
                'operator_id',
            ]));
        });

        return redirect()->route('stations')->with('success', '登録しました。');
    }

    /**
     * 編集（画面／処理）
     */
    public function edit(Request $request, $id)
    {
        $record = Station::findOrFail($id);

        if ($request->isMethod('get')) {
            // 駐車場リストを取得（プルダウン用）
            $parks = Park::orderBy('park_name')->pluck('park_name', 'park_id');

            return view('admin.stations.edit', [
                'isEdit' => true,
                'record' => $record,
                'parks'  => $parks, // ← ここを追加
            ]);
        }

        // ▼ POST時：バリデーション
        $rules = [
            'station_neighbor_station' => 'required|string|max:255',
            'station_name_ruby'        => 'required|string|max:255',
            'station_route_name'       => 'required|string|max:255',
            'station_latitude'         => 'required|numeric',
            'station_longitude'        => 'required|numeric',
            'operator_id'              => 'nullable|integer',
            'park_id'                  => 'required|integer',
        ];

        $messages = [
            'station_latitude.required'  => '緯度は必須項目です。',
            'station_longitude.required' => '経度は必須項目です。',
        ];

        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        DB::transaction(function () use ($request, $record) {
            $record->update($request->only([
                'station_neighbor_station',
                'station_name_ruby',
                'station_route_name',
                'park_id',
                'operator_id',
                'station_latitude',
                'station_longitude',
            ]));
        });

        return redirect()->route('stations')->with('success', '更新しました。');
    }


    /**
     * 削除（単一／複数対応）
     */
    public function delete(Request $request)
    {
        $ids = [];

        if ($request->filled('id')) {
            $ids[] = (int) $request->input('id');
        }

        if (is_array($request->input('pk'))) {
            $ids = array_merge($ids, $request->input('pk'));
        }

        $ids = array_values(array_unique(array_map('intval', $ids)));

        if (empty($ids)) {
            return back()->with('error', '削除対象が選択されていません。');
        }

        Station::whereIn('station_id', $ids)->delete();

        return redirect()->route('stations')->with('success', '削除しました');
    }


    /**
     * CSVインポート（仮）
     */
    public function import(Request $request)
    {
        // TODO: 実装予定
        return redirect()->route('stations')->with('info', 'CSVインポートは未実装です');
    }

    /**
     * CSVエクスポート（日本語ヘッダー付き）
     */
    public function export()
    {
        // ファイル名
        $filename = '近傍駅マスタ_' . now()->format('YmdHis') . '.csv';

        return response()->streamDownload(function () {
            // Excel用 UTF-8 BOM
            echo "\xEF\xBB\xBF";

            // 日本語ヘッダー行
            echo "近傍駅ID,駐車場ID,近傍駅,近傍駅ふりがな,路線名,近傍駅座標（緯度）,近傍駅座標（経度）\n";

            // データ行
            foreach (\App\Models\Station::all() as $station) {
                echo implode(',', [
                    $station->station_id,
                    $station->park_id,
                    $station->station_neighbor_station,
                    $station->station_name_ruby,
                    $station->station_route_name,
                    $station->station_latitude,
                    $station->station_longitude,
                    // $station->operator_id,
                ]) . "\n";
            }
        }, $filename);
    }

}
