<?php

namespace App\Http\Controllers\Admin;

use App\Models\Ptype;
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 PtypeController extends Controller
{
    public function list(Request $request)
    {
        $inputs = [
            'isMethodPost' => 0,
            'isExport' => 0,
            'sort' => $request->input('sort', ''),
            'sort_type' => $request->input('sort_type', ''),
            'page' => $request->get('page', 1),

        ];
        $inputs['isMethodPost'] = $request->isMethod('post');
        $inputs['list'] = Ptype::search($inputs);

        if ($inputs['list']->total() > 0 && $inputs['page'] > $inputs['list']->lastPage()) {
            return redirect()->route('ptypes');
        }

        return view('admin.ptypes.list', $inputs);
    }

    public function add(Request $request)
    {
        $inputs = [
            //TODO 駐輪分類ID not found in database specs
            'ptype_subject' => $request->input('ptype_subject'), // 駐輪分類名
            'ptype_remarks' => $request->input('ptype_remarks'), // 備考
        ];

        if ($request->isMethod('POST')) {
            $rules = [
                'ptype_subject' => 'required|string|max:255',
                'floor_sort' => 'nullable|integer',
                'ptype_remarks' => 'nullable|string|max:255',
            ];
            $messages = [
                'ptype_subject.required' => '駐輪分類名は必須です。',
            ];
            $validator = Validator::make($request->all(), $rules, $messages);
            if (!$validator->fails()) {
                \DB::transaction(function () use ($inputs, &$type) {
                    $new = new Ptype();
                    $new->fill($inputs);
                    if ($new->save()) {
                        $type = true;
                    }

                });
                if ($type) {
                    $request->session()->flash('success', __('データ新規作成しました。'));
                    return redirect()->route('ptypes');
                } else {
                    $request->session()->flash('error', __('新規作成に失敗しました'));
                }
            } else {
                $inputs['errorMsg'] = $this->__buildErrorMessasges($validator);
            }
        }

        return view('admin.ptypes.add', $inputs);
    }

    public function edit(Request $request, $pk, $view = '')
    {
        $ptype = Ptype::getByPk($pk);
        if (empty($pk) || empty($ptype)) {
            abort(404);
        }

        // 追加のドロップダウンなどがある場合
        $dataList = $this->getDataDropList();

        if ($request->isMethod('POST')) {
            $type = false;

            // バリデーションルール
            $rules = [
                'ptype_subject' => 'required|string|max:255',
                'floor_sort'    => 'nullable|integer',
                'ptype_remarks' => 'nullable|string|max:255',
            ];
            $messages = [
                'ptype_subject.required' => '駐輪分類名は必須です。',
            ];

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

            if (!$validator->fails()) {
                \DB::transaction(function () use ($request, &$type, $ptype) {
                    $ptype->fill($request->all());
                    $ptype->save();
                    $type = true;
                });
                if ($type) {
                    $request->session()->flash('success', __('更新に成功しました'));
                    return redirect()->route('ptypes');
                } else {
                    $request->session()->flash('error', __('更新に失敗しました'));
                }
            } else {
                return redirect()->back()
                                ->withErrors($validator)
                                ->withInput();
            }
        }

        // Blade に渡すときはモデルそのものを渡す
        if ($view != '') {
            return view($view, array_merge($dataList, ['item' => $ptype]));
        }
        return view('admin.ptypes.edit', array_merge($dataList, [
            'item' => $ptype,
            'ptype_id' => $ptype->ptype_id, 
        ]));
    }

    public function delete(Request $request)
    {
        $arr_pk = $request->get('pk');

        // 単体削除の場合 string が来るので配列に変換
        if (!is_array($arr_pk)) {
            $arr_pk = [$arr_pk];
        }

        if ($arr_pk && count($arr_pk) > 0) {
            if (Ptype::whereIn('ptype_id', $arr_pk)->delete()) {
                return redirect()->route('ptypes')->with('success', __("削除が完了しました。"));
            } else {
                return redirect()->route('ptypes')->with('error', __('削除に失敗しました。'));
            }
        }
        return redirect()->route('ptypes')->with('error', __('削除するデータを選択してください。'));
    }


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

    public function getDataDropList()
    {
        $data = [];
        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 = Ptype::search($inputs);
        $columns = array(
            __('駐輪分類ID'),
            __('駐輪分類名'),
            __('備考'),
        );
        $filename = "駐輪分類マスタ.csv";
        $file = fopen($filename, 'w+');
        fputcsv($file, $columns);
        foreach ($dataExport as $items) {
            fputcsv($file, array(
                $items->ptype_id,
                $items->ptype_subject,
                $items->ptype_remarks,
            ));
        }
        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 {
                Ptype::query()->delete();
                $col = 3;
                foreach ($data as $key => $items) {
                    $record = $key + 2;
                    if (count($items) == $col) {
                        $row = new Ptype();
                        $row->ptype_id = $items[0];
                        $row->ptype_subject = $items[1];
                        $row->ptype_remarks = $items[2];
                        if (!$row->save()) {
                            $type = 0;
                            $msg = '行:record型が一致しません。';
                            break;
                        }
                    } else {
                        $type = 0;
                        $msg = '行:record列数が一致しません。';
                        break;
                    }
                }
            } catch (\Exception $e) {
                dd($e);
                $msg = '行:record型が一致しません。';
                $type = 0;
            }
            if ($type) {
                DB::commit();
                return redirect()->route('ptypes')->with('success', __('輸入成功'));
            } else {
                DB::rollBack();
                return redirect()->route('ptypes')->with('error', __($msg, ['record' => $record]));
            }
        } else {
            return redirect()->route('ptypes')->with('error', __('あなたはcsvファイルを選択していません。'));
        }
    }

}