<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\UsertypeRequest;
use App\Models\Usertype;
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 UsertypeController 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'] = Usertype::search($inputs);
        if ($inputs['list']->total() > 0 && $inputs['page'] > $inputs['list']->lastPage()) {
            return redirect()->route('usertypes');
        }
        return view('admin.usertypes.list', $inputs);
    }

    public function add(Request $request)
    {
        // 画面に戻すための初期値
        $viewData = [
            'sort_order' => old('sort_order', ''),
            'category_name1' => old('category_name1', ''),
            'category_name2' => old('category_name2', ''),
            'category_name3' => old('category_name3', ''),
            'print_name' => old('print_name', ''),
            'usertype_money' => old('usertype_money', ''),
            'usertype_remarks' => old('usertype_remarks', ''),
            'isEdit' => 0,
            'isInfo' => 0,
        ];

        if ($request->isMethod('post')) {
            // 入力値をまとめる
            $inputs = [
                'sort_order' => $request->input('sort_order'),
                'category_name1' => $request->input('category_name1'),
                'category_name2' => $request->input('category_name2'),
                'category_name3' => $request->input('category_name3'),
                'print_name' => $request->input('print_name'),
                'usertype_money' => $request->input('usertype_money'),
                'usertype_remarks' => $request->input('usertype_remarks'),
            ];

            // バリデーションルール（最小限）
            $rules = [
                'sort_order' => 'nullable|integer',
                'category_name1' => 'nullable|string|max:255',
                'category_name2' => 'nullable|string|max:255',
                'category_name3' => 'nullable|string|max:255',
                'print_name' => 'required|string|max:255',
                'usertype_money' => 'nullable|string|max:255',
                'usertype_remarks' => 'nullable|string|max:255',
            ];
            $messages = [
                'print_name.required' => '印字名は必須です。',
                'sort_order.integer' => 'ソートオーダーは数値で入力してください。',
            ];

            $validator = Validator::make($inputs, $rules, $messages);

            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }

            // 登録処理
            $ok = false;
            \DB::transaction(function () use ($inputs, &$ok) {
                $new = new Usertype();
                $new->fill($inputs);
                $ok = $new->save();
            });

            if ($ok) {
                return redirect()->route('usertypes')->with('success', '登録しました。');
            }
            return back()->with('error', '登録に失敗しました。')->withInput();
        }

        // GET: 画面表示
        return view('admin.usertypes.add', $viewData);
    }


    public function edit(Request $request, $id)
    {
        $usertype = Usertype::findOrFail($id);

        // 画面に渡す初期データ（既存の構成に合わせて attributes を使う）
        $data = $usertype->getAttributes();
        if (method_exists($this, 'getDataDropList')) {
            $dataList = $this->getDataDropList();
            $data = array_merge($data, $dataList);
        }

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

            // ▼ 内蔵バリデーション（FormRequest を使わない）
            $rules = [
                'sort_order' => 'nullable|integer',
                'category_name1' => 'nullable|string|max:255',
                'category_name2' => 'nullable|string|max:255',
                'category_name3' => 'nullable|string|max:255',
                'print_name' => 'required|string|max:255',
                'usertype_money' => 'nullable|string|max:255',
                'usertype_remarks' => 'nullable|string|max:255',
            ];
            $messages = [
                'print_name.required' => '印字名は必須です。',
                'sort_order.integer' => 'ソートオーダーは数値で入力してください。',
            ];

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

            // 入力値を $data にマージ（既存ロジック踏襲）
            $requestAll = $request->all();
            $data = array_merge($data, $requestAll);

            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }

            \DB::transaction(function () use ($data, &$type, $usertype) {
                // fill するフィールドだけを明示したい場合は only(...) で絞ってもOK
                $usertype->fill([
                    'sort_order' => $data['sort_order'] ?? null,
                    'category_name1' => $data['category_name1'] ?? null,
                    'category_name2' => $data['category_name2'] ?? null,
                    'category_name3' => $data['category_name3'] ?? null,
                    'print_name' => $data['print_name'] ?? null,
                    'usertype_money' => $data['usertype_money'] ?? null,
                    'usertype_remarks' => $data['usertype_remarks'] ?? null,
                ]);
                $usertype->save();
                $type = true;
            });

            if ($type) {
                return redirect()->route('usertypes')->with('success', '更新しました。');
            }
            return back()->with('error', '更新に失敗しました。')->withInput();
        }

        // GET: 画面表示（既存のビューに合わせて返す）
        return view('admin.usertypes.edit', $data);
    }


    public function delete(Request $request)
    {
        // pk[] が無ければ ids[] を見る（両対応）
        $arr_pk = $request->input('pk');
        if (empty($arr_pk)) {
            $arr_pk = $request->input('ids', []);
        }
        if (!is_array($arr_pk)) {
            $arr_pk = [$arr_pk];
        }
        if (empty($arr_pk)) {
            return redirect()->route('usertypes')->with('error', '削除するユーザーを選択してください。');
        }

        if (Usertype::deleteByPk($arr_pk)) {
            return redirect()->route('usertypes')->with('success', '削除が完了しました。');
        }
        return redirect()->route('usertypes')->with('error', '削除に失敗しました。');
    }


    public function info(Request $request, $id)
    {
        return $this->edit($request, $id, 'admin.usertypes.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 = Usertype::search($inputs);
        $columns = array(
            __('利用者分類ID'),// 0
            __('分類名'),// 1
            __('適用料率'),// 2
            __('備考'),// 3
        );
        $filename = "利用者分類マスタ.csv";
        $file = fopen($filename, 'w+');
        fputcsv($file, $columns);
        foreach ($dataExport as $items) {
            fputcsv(
                $file,
                array(
                    $items->user_categoryid,
                    $items->print_name,
                    $items->usertype_money,
                    $items->usertype_remarks, // 3
                )
            );
        }
        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 {
                Usertype::query()->delete();
                $col = 4;
                foreach ($data as $key => $items) {
                    $record = $key + 2;
                    if (count($items) == $col) {
                        $row = new Usertype();
                        $row->user_categoryid = $items[0];
                        $row->print_name = $items[1];
                        $row->usertype_money = $items[2];
                        $row->usertype_remarks = $items[3];
                        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('usertypes')->with('success', __('輸入成功'));
            } else {
                DB::rollBack();
                return redirect()->route('usertypes')->with('error', __($msg, ['record' => $record]));
            }
        } else {
            return redirect()->route('usertypes')->with('error', __('あなたはcsvファイルを選択していません。'));
        }
    }


}