<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ContractAllowableCity;
use App\Models\City;
use App\Models\Park;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ContractAllowableCityController extends Controller
{
    /**
     * 一覧表示
     */
    public function list(Request $request)
{
    $inputs = $request->all();
    $inputs['isMethodPost'] = $request->isMethod('post');

    // 解除処理
    if ($request->isMethod('post') && $request->input('action') === 'unlink') {
        $query = ContractAllowableCity::query();

        if ($request->filled('contract_allowable_city_id')) {
            $query->where('contract_allowable_city_id', $request->contract_allowable_city_id);
        }
        if ($request->filled('city_id')) {
            $query->where('city_id', $request->city_id);
        }
        if ($request->filled('contract_allowable_city_name')) {
            $query->where('contract_allowable_city_name', 'like', '%' . $request->contract_allowable_city_name . '%');
        }
        if ($request->filled('park_id')) {
            $query->where('park_id', $request->park_id);
        }

        $records = $query->get();
        foreach ($records as $record) {
            $record->delete(); 
        }

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

    // 通常の絞り込み処理
    $list = ContractAllowableCity::search($inputs);

    return view('admin.contract_allowable_cities.list', [
        'list' => $list,
        'inputs' => $inputs,
        'sort' => $inputs['sort'] ?? '',
        'sort_type' => $inputs['sort_type'] ?? '',
        'cityList' => City::getList(),
        'parkList' => Park::getList(),
    ]);
}


    /**
     * 新規登録
     */
    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $request->validate([
                'city_id' => 'required|integer',
                'contract_allowable_city_name' => 'required|string|max:20',
                'park_id' => 'required|integer',
                'same_district_flag' => 'required|integer',
            ]);

            $data = $request->all();
            $data['operator_id'] = Auth::user()->ope_id;

            ContractAllowableCity::create($data);

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

            return view('admin.contract_allowable_cities.add', [
                'record' => null,
                'cityList' => City::getList(),
                'parkList' => Park::getList(),
                'contractAllowableCityList' => ContractAllowableCity::getList(),
                'mode' => 'add'
        ]);
    }

    /**
     * 編集
     */
    public function edit(Request $request, $id)
    {
        $record = ContractAllowableCity::getByPk($id);
        if (!$record) {
            return redirect()->route('contract_allowable_cities')->with('error', 'データが存在しません');
        }

        if ($request->isMethod('post')) {
            $request->validate([
                'city_id' => 'required|integer',
                'contract_allowable_city_name' => 'required|string|max:20',
                'park_id' => 'required|integer',
                'same_district_flag' => 'required|integer',
            ]);

            $record->fill($request->all());
            $record->operator_id = Auth::user()->ope_id;
            $record->save();

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

        return view('admin.contract_allowable_cities.edit', [
            'record' => $record,
            'cities' => City::getList(),
            'parks' => Park::getList(),
            'mode' => 'edit'
        ]);
    }

    /**
     * 詳細参照（表示のみ）
     */
    public function info($id)
    {
        $record = ContractAllowableCity::getByPk($id);
        if (!$record) {
            return redirect()->route('contract_allowable_cities')->with('error', 'データが存在しません');
        }

        return view('admin.contract_allowable_cities.edit', [
            'record' => $record,
            'cityList' => City::getList(),
            'parkList' => Park::getList(),
            'mode' => 'info'
        ]);
    }

    /**
     * 一括削除
     */
    public function delete(Request $request)
    {
        if ($request->has('id')) {
            ContractAllowableCity::deleteByPk($request->id);
            return redirect()->route('contract_allowable_cities')->with('success', '削除しました');
        }

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

    /**
     * CSVエクスポート
     */
    public function export(Request $request)
    {
        $filename = 'contract_allowable_cities_' . now()->format('Ymd_His') . '.csv';

        $list = ContractAllowableCity::search($request->all());

        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"$filename\"",
        ];

        return new StreamedResponse(function () use ($list) {
            $handle = fopen('php://output', 'w');

            // ヘッダー
            fputcsv($handle, ['契約許容市区ID', '市区ID', '許容市区名', '駐輪場ID', '隣接区フラグ']);

            foreach ($list as $item) {
                fputcsv($handle, [
                    $item->contract_allowable_city_id,
                    $item->city_id,
                    $item->contract_allowable_city_name,
                    $item->park_id,
                    $item->same_district_flag == 0 ? '隣接市' : 'その他'
                ]);
            }

            fclose($handle);
        }, 200, $headers);
    }

}