<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Usertype;
use App\Models\Ope;

class PersonalController extends Controller
{
    /**
     * 本人確認手動処理 一覧画面
     */
    public function list(Request $request)
    {
        $query = User::query();

        if ($request->filled('user_id')) {
            $query->where('user_id', $request->input('user_id'));
        }

        $users = $query->paginate(20);

        return view('admin.personal.list', [
            'users' => $users,
            'request' => $request,
        ]);
    }

    /**
     * 本人確認手動処理 編集画面
     */
    public function edit(Request $request, $id)
    {
        // 利用者情報取得
        $user = User::where('user_id', $id)->firstOrFail();

        // 利用者分類マスタ取得（ラジオボタン用）
        $usertypes = Usertype::orderBy('sort_order')->get();

        // POST時の処理
        if ($request->isMethod('post')) {
            // 利用者分類IDの更新
            $user->user_categoryid = $request->input('user_categoryid', $user->user_categoryid);

            // 本人確認チェックOK/NG
            if ($request->input('check') === 'ok') {
                $user->user_idcard_chk_flag = 1;
            } elseif ($request->input('check') === 'ng') {
                $user->user_idcard_chk_flag = 0;
                // 備考欄も更新（NG理由）
                $user->user_remarks = $request->input('user_remarks', $user->user_remarks);
            }

            $user->save();

            return redirect()->route('personal')->with('success', '更新しました');
        }

        return view('admin.personal.edit', [
            'user' => $user,
            'usertypes' => $usertypes,
        ]);
    }
}

class OpesController extends Controller
{
    /**
     * オペレータ一覧画面
     */
    public function list(Request $request)
    {
        $sort = $request->input('sort', 'ope_id'); // デフォルト値を設定
        $sort_type = $request->input('sort_type', 'asc'); // デフォルト値を設定

        $query = Ope::query();

        // 並び替え
        $query->orderBy($sort, $sort_type);

        $list = $query->paginate(20);

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

    /**
     * オペレータ編集画面
     */
    public function edit(Request $request, $id)
    {
        $ope = \App\Models\Ope::findOrFail($id);

        if ($request->isMethod('post')) {
            // バリデーション＆更新処理
            // ...
        }

        // 各項目を配列で渡す
        return view('admin.opes.edit', [
            'ope_id' => $ope->ope_id,
            'ope_name' => $ope->ope_name,
            'login_id' => $ope->login_id,
            'ope_pass' => '', // パスワードは空で
            'ope_belong' => $ope->ope_belong,
            'ope_type' => $ope->ope_type,
            'ope_mail' => $ope->ope_mail,
            'ope_phone' => $ope->ope_phone,
            'ope_sendalart_que1' => $ope->ope_sendalart_que1,
            'ope_sendalart_que2' => $ope->ope_sendalart_que2,
            'ope_sendalart_que3' => $ope->ope_sendalart_que3,
            'ope_sendalart_que4' => $ope->ope_sendalart_que4,
            'ope_sendalart_que5' => $ope->ope_sendalart_que5,
            'ope_sendalart_que6' => $ope->ope_sendalart_que6,
            'ope_sendalart_que7' => $ope->ope_sendalart_que7,
            'ope_sendalart_que8' => $ope->ope_sendalart_que8,
            'ope_sendalart_que9' => $ope->ope_sendalart_que9,
            'ope_sendalart_que10' => $ope->ope_sendalart_que10,
            'ope_sendalart_que11' => $ope->ope_sendalart_que11,
            'ope_sendalart_que12' => $ope->ope_sendalart_que12,
            'ope_sendalart_que13' => $ope->ope_sendalart_que13,
            'ope_auth1' => $ope->ope_auth1,
            'ope_auth2' => $ope->ope_auth2,
            'ope_auth3' => $ope->ope_auth3,
            'ope_auth4' => $ope->ope_auth4,
            'ope_quit_flag' => $ope->ope_quit_flag,
            'ope_quitday' => $ope->ope_quitday,
        ]);
    }

    /**
     * オペレータ一覧のエクスポート
     */
    public function export(Request $request)
    {
        $filename = 'ope_export_' . date('Ymd_His') . '.csv';
        $columns = [
            'ope_id', 'ope_belong', 'login_id', 'ope_name', 'ope_pass', 'ope_type', 'ope_mail', 'ope_phone',
            'ope_sendalart_que1', 'ope_sendalart_que2', 'ope_sendalart_que3', 'ope_sendalart_que4', 'ope_sendalart_que5',
            'ope_sendalart_que6', 'ope_sendalart_que7', 'ope_sendalart_que8', 'ope_sendalart_que9', 'ope_sendalart_que10',
            'ope_sendalart_que11', 'ope_sendalart_que12', 'ope_sendalart_que13',
            'ope_auth1', 'ope_auth2', 'ope_auth3', 'ope_auth4',
            'ope_quit_flag', 'ope_quitday', 'created_at', 'updated_at'
        ];

        $ids = $request->input('pk', []);
        if (!empty($ids)) {
            $list = \App\Models\Ope::whereIn('ope_id', $ids)->select($columns)->get();
        } else {
            $list = \App\Models\Ope::select($columns)->get();
        }

        $callback = function() use ($list, $columns) {
            $file = fopen('php://output', 'w');
            // ヘッダー
            fputcsv($file, $columns);

            foreach ($list as $row) {
                $data = [];
                foreach ($columns as $col) {
                    $data[] = $row->$col;
                }
                fputcsv($file, $data);
            }
            fclose($file);
        };

        return response()->stream($callback, 200, [
            "Content-Type" => "text/csv",
            "Content-Disposition" => "attachment; filename={$filename}",
        ]);
    }

    /**
     * オペレータの削除
     */
    public function delete(Request $request)
    {
        // チェックされたIDの配列を受け取る想定
        $ids = $request->input('pk', []);
        if (!empty($ids)) {
            \App\Models\Ope::whereIn('ope_id', $ids)->delete();
            return redirect()->route('opes')->with('success', '削除しました');
        }
        return redirect()->route('opes')->with('error', '削除対象が選択されていません');
    }

    /**
     * オペレータの追加
     */
    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $validated = $request->validate([
                'ope_name' => 'required|string|max:255',
                'login_id' => 'required|string|max:255|unique:ope,login_id',
                'password' => 'required|string|min:6|confirmed',
                'ope_type' => 'required',
                'ope_mail' => 'required|email',
            ]);
            $ope = new \App\Models\Ope();
            $ope->ope_name = $request->ope_name;
            $ope->login_id = $request->login_id;
            $ope->ope_pass = bcrypt($request->password);
            $ope->ope_type = $request->ope_type;
            $ope->ope_mail = $request->ope_mail;
            $ope->ope_phone = $request->ope_phone;
            for ($i = 1; $i <= 13; $i++) {
                $field = "ope_sendalart_que{$i}";
                $ope->$field = $request->$field ?? 0;
            }
            for ($i = 1; $i <= 4; $i++) {
                $field = "ope_auth{$i}";
                $ope->$field = $request->$field ?? '';
            }
            $ope->ope_quit_flag = $request->ope_quit_flag ?? 0;
            $ope->ope_quitday = $request->ope_quitday ?? null;
            $ope->save();
            return redirect()->route('opes')->with('success', '登録しました');
        }
        return view('admin.opes.add');
    }
}