<?php

namespace App\Http\Controllers\Admin;

use App\Models\City;
use App\Http\Requests\RegularTypeRequest;
use App\Models\RegularType;  
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 RegularTypeController extends Controller
{
    
    public function add(Request $request)
    {
        // 画面用データ
        $dataList = $this->getDataDropList();

        // フォーム入力（画面初期表示用）
        $inputs = [
            'city_id'          => $request->input('city_id'),
            'regular_class_1'  => $request->input('regular_class_1'),
            'regular_class_2'  => $request->input('regular_class_2'),
            'regular_class_3'  => $request->input('regular_class_3'),
            'regular_class_6'  => $request->input('regular_class_6'),
            'regular_class_12' => $request->input('regular_class_12'),
            'memo'             => $request->input('memo'),
        ];
        $viewData = array_merge($inputs, $dataList);

        $record = new RegularType();

        if ($request->isMethod('POST')) {
            $validation = new RegularTypeRequest();
            $rules      = $validation->rules();
            $validator  = Validator::make($request->all(), $rules, $validation->messages());

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

            // バリデーション成功
            $payload = array_intersect_key($request->all(), array_flip([
                'city_id',
                'regular_class_1',
                'regular_class_2',
                'regular_class_3',
                'regular_class_6',
                'regular_class_12',
                'memo',
            ]));

            DB::transaction(function () use ($payload) {
                $new = new RegularType();
                $new->fill($payload);
                $new->operator_id = \Auth::user()->ope_id;
                $new->save();
            });

            $request->session()->flash('success', __('登録しました。'));
            return redirect()->route('regular_types');
        }

        return view('admin.regular_types.add', array_merge($viewData, [
            'record' => $record,
        ]));
    }

    public function edit(Request $request, $id, $view = '')
    {
        // --- データ取得 ---
        $record = RegularType::getById($id);
        if (empty($id) || empty($record)) {
            abort(404);
        }

        // --- 初期表示用データ ---
        $data = array_merge(
            $record->getAttributes(),
            $this->getDataDropList(),
            [
                'record' => $record,
                'isEdit' => true,
            ]
        );

        // --- 更新処理 ---
        if ($request->isMethod('POST')) {

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

            // city_name → city_id の補正
            $requestAll = $request->all();
            if (isset($requestAll['city_name']) && !isset($requestAll['city_id'])) {
                $requestAll['city_id'] = $requestAll['city_name'];
            }

            // 書き込み対象のカラムのみ許可
            $payload = array_intersect_key($requestAll, array_flip([
                'city_id',
                'regular_class_1',
                'regular_class_2',
                'regular_class_3',
                'regular_class_6',
                'regular_class_12',
                'memo',
            ]));

            // バリデーションエラー
            if ($validator->fails()) {
                $data['errorMsg'] = $this->buildErrorMessages($validator);
                $data = array_merge($data, $payload);

                if ($view !== '') return view($view, $data);
                return view('admin.regular_types.edit', $data);
            }

            // 更新
            DB::transaction(function () use (&$record, $payload) {
                $record->fill($payload);
                $record->save();
            });

            $request->session()->flash('success', __('更新しました。'));
            return redirect()->route('regular_types');
        }

        // --- 画面表示 ---
        if ($view !== '') {
            return view($view, $data);
        }
        return view('admin.regular_types.edit', $data);
    }

    /** バリデーションエラーをまとめる */
    protected function buildErrorMessages(\Illuminate\Contracts\Validation\Validator $validator): string
    {
        return implode("\n", $validator->errors()->all());
    }

    public function delete(Request $request, $id = null)
    {
        // 一覧画面（checkbox で複数削除）
        $ids = $request->input('pk');

        // 編集画面（単体削除）
        if ($id) {
            $ids = [$id];
        }

        // 削除対象が空の場合
        if (empty($ids)) {
            return redirect()
                ->route('regular_types')
                ->with('error', '削除対象が選択されていません。');
        }

        // 削除処理
        RegularType::destroy($ids);

        return redirect()
            ->route('regular_types')
            ->with('success', '削除しました。');
    }



    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 = RegularType::search($inputs);
        $columns = array('user_seq', 'user_id');
        $filename = "UserMaster.csv";
        $file = fopen($filename, 'w+');
        fputcsv($file, $columns);
        foreach ($dataExport as $item) {
            fputcsv($file, array($item->user_seq, $item->user_id));
        }
        fclose($file);
        return Response::download($filename, $filename, $headers);
    }

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

    public function getDataDropList()
    {
        $data['cities'] = City::getList();
        return $data;
    }
    public function list(Request $request)
    {
        $sort = $request->input('sort', 'regular_type_id');
        $sort_type = $request->input('sort_type', 'asc');

        $list = \App\Models\RegularType::orderBy($sort, $sort_type)->paginate(20);

        return view('admin.regular_types.list', [
            'list' => $list,
            'sort' => $sort,
            'sort_type' => $sort_type,
        ]);
    }



}