<?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)
    {
        $sort = $request->input('sort', 'user_categoryid');
        $allowSort = [
            'user_categoryid',
            'sort_order',
            'usertype_subject1',
            'usertype_subject2',
            'usertype_subject3',
            'print_name',
        ];
        if (!in_array($sort, $allowSort, true)) {
            $sort = 'user_categoryid';
        }
        $sortType = strtolower($request->input('sort_type', 'asc'));
        if (!in_array($sortType, ['asc', 'desc'], true)) {
            $sortType = 'asc';
        }
        $inputs = [
            'isMethodPost' => $request->isMethod('post') ? 1 : 0,
            'isExport' => 0,
            'sort' => $sort,
            'sort_type' => $sortType,
            'page' => (int) $request->get('page', 1),
        ];
        $filters = [
            'filter_sort_order' => $request->input('filter_sort_order', ''),
            'filter_usertype_subject1' => $request->input('filter_usertype_subject1', ''),
            'filter_usertype_subject2' => $request->input('filter_usertype_subject2', ''),
            'filter_usertype_subject3' => $request->input('filter_usertype_subject3', ''),
        ];
        $searchParams = array_merge($inputs, $filters);
        $viewData = $searchParams;
        $viewData['list'] = Usertype::search($searchParams);
        if ($viewData['list']->total() > 0 && $viewData['page'] > $viewData['list']->lastPage()) {
            return redirect()->route('usertypes');
        }
        return view('admin.usertypes.list', $viewData);
    }

    public function add(Request $request)
    {
        // 画面に戻すための初期値
        $viewData = [
            'sort_order' => old('sort_order', ''),
            'usertype_subject1' => old('usertype_subject1', ''),
            'usertype_subject2' => old('usertype_subject2', ''),
            'usertype_subject3' => old('usertype_subject3', ''),
            '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'),
                'usertype_subject1' => $request->input('usertype_subject1'),
                'usertype_subject2' => $request->input('usertype_subject2'),
                'usertype_subject3' => $request->input('usertype_subject3'),
                'print_name' => $request->input('print_name'),
                'usertype_money' => $request->input('usertype_money'),
                'usertype_remarks' => $request->input('usertype_remarks'),
            ];

            // バリデーションルール（最小限）
            $rules = [
                'sort_order' => 'nullable|integer',
                'usertype_subject1' => 'nullable|string|max:255',
                'usertype_subject2' => 'nullable|string|max:255',
                'usertype_subject3' => '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',
                'usertype_subject1' => 'nullable|string|max:255',
                'usertype_subject2' => 'nullable|string|max:255',
                'usertype_subject3' => '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,
                    'usertype_subject1' => $data['usertype_subject1'] ?? null,
                    'usertype_subject2' => $data['usertype_subject2'] ?? null,
                    'usertype_subject3' => $data['usertype_subject3'] ?? 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)
    {
        $timestamp = now()->format('YmdHis');
        $filename = "利用者分類マスタ{$timestamp}.csv";
        $filePath = storage_path("app/{$filename}");
        $headers = [
            'Content-Type' => 'text/csv; charset=UTF-8',
            'Content-Encoding' => 'UTF-8',
            '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', ''),
            'filter_sort_order' => $request->input('filter_sort_order', ''),
            'filter_usertype_subject1' => $request->input('filter_usertype_subject1', ''),
            'filter_usertype_subject2' => $request->input('filter_usertype_subject2', ''),
            'filter_usertype_subject3' => $request->input('filter_usertype_subject3', ''),
        ];

        $dataExport = Usertype::search($inputs);
        $columns = array(
            __('利用者分類ID'),// 0
            __('分類名'),// 1
            __('適用料率'),// 2
            __('備考'),// 3
        );
        $file = fopen($filePath, '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($filePath, $filename, $headers)->deleteFileAfterSend(true);
    }

    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ファイルを選択していません。'));
        }
    }


}