<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Station;

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';
        }

        // 必要カラムのみ取得
        $stations = Station::select([
            'station_id',
            'station_neighbor_station',
            'station_name_ruby',
            'station_route_name',
            'park_id',
            'operator_id'
        ])->orderBy($sort, $sort_type)->paginate(20);

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

    /**
     * 新規登録
     */
    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $validated = $request->validate([
                'station_neighbor_station' => 'required|string|max:255',
                'station_name_ruby'       => 'nullable|string|max:255',
                'station_route_name'      => 'nullable|string|max:255',
                'park_id'                 => 'nullable|integer',
                'operator_id'             => 'nullable|integer',
            ]);

            Station::create($validated);
            return redirect()->route('stations')->with('success', '近傍駅が登録されました');
        }

        return view('admin.stations.add');
    }

    /**
     * 編集
     */
    public function edit(Request $request, $id)
    {
        $station = Station::findOrFail($id);

        if ($request->isMethod('post')) {
            $validated = $request->validate([
                'station_neighbor_station' => 'required|string|max:255',
                'station_name_ruby'       => 'nullable|string|max:255',
                'station_route_name'      => 'nullable|string|max:255',
                'park_id'                 => 'nullable|integer',
                'operator_id'             => 'nullable|integer',
            ]);

            $station->update($validated);
            return redirect()->route('stations')->with('success', '更新しました');
        }

        return view('admin.stations.edit', compact('station'));
    }

    /**
     * 詳細
     */
    public function info($id)
    {
        $station = Station::findOrFail($id);
        return view('admin.stations.info', compact('station'));
    }

    /**
     * 削除
     */
    public function delete(Request $request)
    {
        $ids = $request->input('pk'); // 複数ID対応

        if (!empty($ids)) {
            Station::destroy($ids);
            return redirect()->route('stations')->with('success', '削除しました');
        }

        return redirect()->route('stations')->with('error', '削除対象が見つかりません');
    }

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

    /**
     * CSVエクスポート
     */
    public function export()
    {
        return response()->streamDownload(function () {
            // Excel用のUTF-8 BOM
            echo "\xEF\xBB\xBF";
            echo "station_id,station_neighbor_station,station_name_ruby,station_route_name,park_id,operator_id\n";

            foreach (Station::all() as $station) {
                echo "{$station->station_id},{$station->station_neighbor_station},{$station->station_name_ruby},{$station->station_route_name},{$station->park_id},{$station->operator_id}\n";
            }
        }, 'stations.csv');
    }
}
