<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Term;
use App\Models\City;

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

        $allowedSorts = ['terms_id', 'terms_revision', 'start_date', 'use_flag'];
        if (!in_array($sort, $allowedSorts)) {
            $sort = 'terms_id';
        }

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

        $terms = Term::select([
            'terms_id',
            'terms_revision',
            'terms_text',
            'start_date',
            'use_flag',
            'memo',
            'city_id',
            'operator_id'
        ])->orderBy($sort, $sort_type)->paginate(20);

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

    // 新規登録画面・登録処理
    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $validated = $request->validate([
                'city_id' => 'required|integer',
                'terms_revision' => 'required|string|max:255',
                'terms_text' => 'required|string',
                'start_date' => 'nullable|date',
                'use_flag' => 'required|in:0,1',
                'memo' => 'nullable|string|max:255',
                'terms_created_at' => 'nullable|date',
               
                'operator_id' => 'nullable|integer',
            ]);

            Term::create($validated);
            return redirect()->route('terms')->with('success', '登録しました。');
        }
        // 都市の選択肢を取得
        $cities = City::pluck('city_name', 'city_id');

        return view('admin.terms.add', compact('cities'));
    }


    public function edit(Request $request, $id)
    {
        $term = Term::findOrFail($id);
        $cities = City::pluck('city_name', 'city_id');

        if ($request->isMethod('post')) {
            $validated = $request->validate([
                'city_id'         => 'required|integer',
                'terms_revision'  => 'required|string|max:255',
                'terms_text'      => 'required|string',
                'start_date'      => 'nullable|date',
                'use_flag'        => 'required|in:0,1',
                'memo'            => 'nullable|string|max:255',
                'terms_created_at'=> 'nullable|date',
                'operator_id'     => 'nullable|integer',
            ]);

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

        return view('admin.terms.edit', compact('term', 'cities'));
    }




    // 詳細表示
    public function info($id)
    {
        $term = Term::findOrFail($id);
        return view('admin.terms.info', compact('term'));
    }

    // 削除処理（単一・複数対応）
    public function delete(Request $request)
    {
        $request->validate([
            'pk'   => 'required',
            'pk.*' => 'integer', // 配列なら中身は整数
        ]);

        $arr_pk = $request->input('pk');
        $ids = is_array($arr_pk) ? $arr_pk : [$arr_pk];

        $deleted = Term::destroy($ids);

        if ($deleted > 0) {
            return redirect()->route('terms')->with('success', __('削除しました。'));
        } else {
            return redirect()->route('terms')->with('error', __('削除に失敗しました。'));
        }
    }

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

    // CSVエクスポート（fputcsv使用）
    public function export()
    {
        return response()->streamDownload(function () {
            $handle = fopen('php://output', 'w');
            fputcsv($handle, ['terms_id', 'terms_revision', 'terms_text', 'start_date', 'use_flag']);

            foreach (Term::all() as $term) {
                fputcsv($handle, [
                    $term->terms_id,
                    $term->terms_revision,
                    $term->terms_text,
                    $term->start_date,
                    $term->use_flag,
                ]);
            }

            fclose($handle);
        }, 'terms.csv');
    }
}
