<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class SettingController extends Controller
{
    /**
     * 一覧（絞り込みなし・ページングのみ）: /settings
     */
    public function list(Request $request)
    {
        $perPage = \App\Utils::item_per_page ?? 20;

        // リクエストから取得
        $sort = $request->input('sort', 'setting_id');
        $sort_type = $request->input('sort_type', 'desc');

        // 許可されたカラムのみソート（安全対策）
        $allowedSorts = ['setting_id', 'setting_key', 'setting_value']; // ← 必要に応じて増やす

        if (!in_array($sort, $allowedSorts)) {
            $sort = 'setting_id';
        }
        if (!in_array($sort_type, ['asc', 'desc'])) {
            $sort_type = 'desc';
        }

        $list = Setting::orderBy($sort, $sort_type)->paginate($perPage);

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


    /**
     * 追加（GET: 画面 / POST: 登録）: /settings/add
     */
    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $v = Validator::make($request->all(), $this->rules());
            if ($v->fails()) return back()->withErrors($v)->withInput();

            // チェックボックス（未送信時は 0）
            $data = $this->onlyFillable($request);
            $data['printable_alert_flag'] = $request->boolean('printable_alert_flag');

            DB::transaction(function () use ($data) {
                Setting::create($data);
            });

            return redirect()->route('settings')->with('success', '設定を登録しました。');
        }

        return view('admin.settings.add', [
            'setting' => new Setting(), // フォーム初期化用
            'isInfo'  => false,
            'isEdit'  => false,
        ]);
    }

    /**
     * 編集（GET: 画面 / POST: 更新）: /settings/edit/{id}
     */
    public function edit(Request $request, int $id)
    {
        $setting = Setting::findOrFail($id);

        if ($request->isMethod('post')) {
            $v = Validator::make($request->all(), $this->rules($id));
            if ($v->fails()) return back()->withErrors($v)->withInput();

            $data = $this->onlyFillable($request);
            $data['printable_alert_flag'] = $request->boolean('printable_alert_flag');

            DB::transaction(function () use ($setting, $data) {
                $setting->update($data);
            });

            return redirect()->route('settings')->with('success', '設定を更新しました。');
        }

        return view('admin.settings.edit', [
            'setting' => $setting,
            'isInfo'  => false,
            'isEdit'  => true,
        ]);
    }

    /**
     * 詳細表示: /settings/info/{id}
     */
    public function info(int $id)
    {
        $setting = Setting::findOrFail($id);

        return view('admin.settings.info', [
            'setting' => $setting,
            'isInfo'  => true,
            'isEdit'  => false,
        ]);
    }

    /**
     * 削除（単体/複数対応）: /settings/delete
     */
    public function delete(Request $request)
    {
        $ids = $request->input('ids');
        $id  = $request->input('id');
        if ($id) $ids = [$id];

        if (!is_array($ids) || empty($ids)) {
            return back()->with('error', '削除対象が指定されていません。');
        }

        DB::transaction(function () use ($ids) {
            Setting::whereIn('setting_id', $ids)->delete();
        });

        return redirect()->route('settings')->with('success', '設定を削除しました。');
    }

    // ===== バリデーション・ユーティリティ =====

    /**
     * バリデーションルール
     */
    private function rules(?int $id = null): array
    {
        return [
            'edit_master'             => ['nullable','string','max:255'],
            'web_master'              => ['nullable','string','max:255'],
            'auto_change_date'        => ['nullable','date'],
            'auto_chage_master'       => ['nullable','string','max:255'], // ※カラム名は仕様通り
            're_issue_alert_number'   => ['nullable','integer','min:0'],
            'image_base_url1'         => ['nullable','string','max:255'],
            'image_base_url2'         => ['nullable','string','max:255'],
            'printable_alert_flag'    => ['nullable','boolean'],
            'printable_number'        => ['nullable','integer','min:0'],
            'printable_alert_number'  => ['nullable','integer','min:0'],
            'printer_keep_alive'      => ['nullable','integer','min:0'],
            'operator_id'             => ['nullable','integer','min:0'],
        ];
    }

    /**
     * フォームから fillable のみ抽出
     */
    private function onlyFillable(Request $request): array
    {
        return $request->only([
            'edit_master',
            'web_master',
            'auto_change_date',
            'auto_chage_master',
            're_issue_alert_number',
            'image_base_url1',
            'image_base_url2',
            'printable_number',
            'printable_alert_number',
            'printer_keep_alive',
            'operator_id',
            'printable_alert_flag',

        ]);
    }
}
