<?php

namespace App\Http\Controllers\Admin;

use App\Models\City;
use App\Http\Requests\ParkRequest;
use App\Models\Park;
use App\Utils;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Response;

class ParkController extends Controller
{
    public function list(Request $request)
    {
        $query = \DB::table('park as p')
            ->leftJoin('city as c', 'p.city_id', '=', 'c.city_id')
            ->select([
                'p.park_id',
                'c.city_name',
                'p.park_name',
                'p.park_ruby',
                'p.park_syllabary',
                'p.park_adrs',
                'p.park_close_flag',
                'p.park_day',
                'p.alert_flag',
                'p.print_number',
                'p.keep_alive',
                'p.operator_id',
            ]);

        if ($request->filled('park_name')) {
            $query->where('p.park_name', 'like', '%' . $request->input('park_name') . '%');
        }
        if ($request->filled('city_id')) {
            $query->where('p.city_id', $request->input('city_id'));
        }
        if ($request->filled('sort')) {
            $query->orderBy($request->input('sort'), $request->input('sort_type', 'asc'));
        } else {
            $query->orderBy('p.park_id', 'asc');
        }

    $parks = $query->paginate(20);
    $cities = \DB::table('city')->orderBy('city_id')->get();

    $sort = $request->input('sort', 'p.park_id');
    $sort_type = $request->input('sort_type', 'asc');
    return view('admin.parks.list', compact('parks', 'cities', 'sort', 'sort_type'));
    }

    public function add(Request $request)
    {
        $cities = \DB::table('city')->orderBy('city_id')->get();

        if ($request->isMethod('post')) {
            // バリデーション（必要な項目だけ例示）
            $validated = $request->validate([
                'city_id' => 'required|integer',
                'park_name' => 'required|string|max:255',
                // 他の項目も必要に応じて追加
            ]);

            // 保存処理
            $park = new \App\Models\Park();
            $park->fill($validated);
            $park->save();

            return redirect()->route('parks')->with('success', '新規登録に完了しました。');
        }

        return view('admin.parks.add', [
            'cities' => $cities,
        ]);
    }

    public function edit(Request $request, $pk, $view = '')
    {
    $park = Park::find($pk);
        if (empty($pk) || empty($park)) {
            abort('404');
        }
        $data = $park->getAttributes();
        $dataList = $this->getDataDropList();
        $data = array_merge($data, $dataList);
    if ($request->isMethod('POST') || $request->isMethod('PUT')) {
            // ここをaddと同じバリデーションに変更
            $validated = $request->validate([
                'city_id' => 'required|integer',
                'park_name' => 'required|string|max:255',
                // 他の項目も必要に応じて追加
            ]);

            \DB::transaction(function () use ($validated, &$type, $park) {
                $park->fill($validated);
                $park->save();
                $type = true;
            });
            $request->session()->flash('success', __('更新に成功しました'));
            return redirect()->route('parks');
        }
        if ($view != '') {
            return view($view, $data);
        }
        return view('admin.parks.edit', [
            'park' => $park,
            'cities' => $dataList['cities'] ?? [],
            // 必要な他の変数もここで渡す
        ]);
    }

    public function delete(Request $request)
    {
        $arr_pk = $request->get('pk');
        if ($arr_pk) {
            if (Park::destroy($arr_pk)) {
                return redirect()->route('parks')->with('success', __("削除が完了しました。"));
            } else {
                return redirect()->route('parks')->with('error', __('削除に失敗しました。'));
            }
        }
        return redirect()->route('parks')->with('error', __('削除するユーザーを選択してください。'));
    }

    public function info(Request $request, $id)
    {
        return $this->edit($request, $id, 'admin.parks.info');
    }

    public function getDataDropList()
    {
        $data['cities'] = City::orderBy('city_id')->get();
        return $data;
    }

    public function export(Request $request)
    {

        $headers = array(
            "Content-type" => "text/csv;charset=UTF-8",
            'Content-Encoding: UTF-8',
            "Content-Disposition" => "attachment; filename=file.csv",
            "Pragma" => "no-cache",
            "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
            "Expires" => "0"
        );
        $inputs = [
            'isMethodPost' => 0,
            'isExport' => 1,
            'sort' => $request->input('sort', ''),
            'sort_type' => $request->input('sort_type', ''),

        ];

        $dataExport = \DB::table('park as p')
            ->leftJoin('city as c', 'p.city_id', '=', 'c.city_id')
            ->select([
                'p.park_id',
                'c.city_name',
                'p.park_name',
                'p.park_ruby',
                'p.park_syllabary',
                'p.park_adrs',
                'p.park_close_flag',
                'p.park_day',
                'p.alert_flag',
                'p.print_number',
                'p.keep_alive',
            ])
            ->orderBy('p.park_id', 'asc')
            ->get();
        $columns = array(
            __('駐輪場ID　'),// 0
            __('市区ID'),// 1
            __('市区'),// 2
            __('駐輪場名'),// 3
            __('駐輪場ふりがな'),// 4
            __('駐輪場五十音'),// 5
            __('住所'),// 6
            __('閉設フラグ'),// 7
            __('閉設フラグ'),// 8
            __('閉設日'),// 9
            __('残警告チェックフラグ'),// 10
            __('印字数'),// 11
            __('最新キープアライブ')// 12
        );
        $filename = "駐輪場マスタ.csv";
        $file = fopen($filename, 'w+');
        fputcsv($file, $columns);
        foreach ($dataExport as $items) {
            fputcsv(
                $file,
                array(
                    $items->park_id,// 0
                    null, // city_id（selectで取得していないので空欄）
                    $items->city_name ?? '',// 2
                    $items->park_name, // 3
                    $items->park_ruby, // 4
                    $items->park_syllabary, // 5
                    $items->park_adrs, // 6
                    $items->park_close_flag,// 7
                    ($items->park_close_flag == 1 ? '閉設' : '開設'),// 8
                    $items->park_day,// 9
                    $items->alert_flag,// 10
                    $items->print_number,// 11
                    $items->keep_alive// 12
                )
            );
        }
        fclose($file);
        return Response::download($filename, $filename, $headers);
    }

    public function import(Request $request)
    {
        $file = $request->file('file');
        if (!empty($file)) {
            $data = Utils::csvToArray($file);
            $type = 1;
            $msg = '';
            $record = 0;
            DB::beginTransaction();
            try {
                Park::query()->delete();
                $col = 13;
                foreach ($data as $key => $items) {
                    $record = $key + 2;
                    if (count($items) == $col) {
                        $row = new Park();
                        $row->park_id = $items[0];
                        $row->city_id = $items[1];
                        $row->park_name = $items[3];
                        $row->park_ruby = $items[4];
                        $row->park_syllabary = $items[5];
                        $row->park_adrs = $items[6];
                        $row->park_close_flag = $items[7];
                        $row->park_day = $items[9];
                        $row->alert_flag = $items[10];
                        $row->print_number = $items[11];
                        $row->keep_alive = $items[12];
                        if (!$row->save()) {
                            $type = 0;
                            $msg = '行:record型が一致しません。';
                            break;
                        }
                    } else {
                        $type = 0;
                        $msg = '行:record列数が一致しません。';
                        break;
                    }
                }
            } catch (\Exception $e) {
                $msg = '行:record型が一致しません。';
                $type = 0;
            }
            if ($type) {
                DB::commit();
                return redirect()->route('parks')->with('success', __('輸入成功'));
            } else {
                DB::rollBack();
                return redirect()->route('parks')->with('error', __($msg, ['record' => $record]));
            }
        } else {
            return redirect()->route('parks')->with('error', __('あなたはcsvファイルを選択していません。'));
        }
    }

    public function checkDuplicate(\Illuminate\Http\Request $request)
    {
        $parkName = $request->input('park_name');
        $duplicate = Park::where('park_name', $parkName)->first();
        if ($duplicate) {
            return response()->json([
                'duplicate' => true,
                'park_id' => $duplicate->park_id,
                'park_name' => $duplicate->park_name,
            ]);
        }
        return response()->json(['duplicate' => false]);
    }
}