<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\MailTemplate;

class MailTemplateController extends Controller
{
    /**
     * 一覧表示
     */
    public function list(Request $request)
    {
        if ($request->input('action') === 'reset') {
            return redirect()->route('mail_templates');
        }

        $allowedSorts = [
            'mail_template_id', 'pg_id', 'internal_id', 'mgr_cc_flag',
            'bcc_adrs', 'use_flag', 'memo', 'subject', 'text',
            'created_at', 'updated_at', 'operator_id'
        ];

        $sort = $request->input('sort', 'mail_template_id');
        $sort_type = $request->input('sort_type', 'asc');

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

        $query = MailTemplate::query();

        // === 絞り込み ===
        $mail_template_id = $request->input('mail_template_id');
        $pg_id = $request->input('pg_id');
        $mgr_cc_flag = $request->input('mgr_cc_flag');
        $use_flag = $request->input('use_flag');
        $subject = $request->input('subject');

        if ($mail_template_id) {
            $query->where('mail_template_id', $mail_template_id);
        }
        if ($pg_id) {
            $query->where('pg_id', $pg_id);
        }
        if ($mgr_cc_flag !== null && $mgr_cc_flag !== '') {
            $query->where('mgr_cc_flag', $mgr_cc_flag);
        }
        if ($use_flag !== null && $use_flag !== '') {
            $query->where('use_flag', $use_flag);
        }
        if ($subject) {
            $query->where('subject', 'LIKE', "%{$subject}%");
        }

        $templates = $query->orderBy($sort, $sort_type)->paginate(20);

        return view('admin.mail_templates.list', compact(
            'templates', 'sort', 'sort_type',
            'mail_template_id', 'pg_id', 'mgr_cc_flag', 'use_flag', 'subject'
        ));
    }


    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $this->validateTemplate($request);
            $data['operator_id'] = optional(\Auth::user())->ope_id ?? null;

            MailTemplate::create($data);

            return redirect()->route('mail_templates')
                ->with('success', '登録しました。');
        }

        return view('admin.mail_templates.add', [
            'mailTemplate' => new MailTemplate(),
            'isEdit'       => false,
        ]);
    }

    /**
     * 編集
     */
    public function edit(int $id, Request $request)
    {
        $mailTemplate = MailTemplate::findOrFail($id);

        if ($request->isMethod('post')) {
            $data = $this->validateTemplate($request);
            $data['operator_id'] = optional(\Auth::user())->ope_id ?? null;

            $mailTemplate->update($data);

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

        return view('admin.mail_templates.edit', [
            'mailTemplate' => $mailTemplate,
            'isEdit'       => true,
        ]);
    }

    /**
     * 削除
     */
    public function delete(Request $request)
    {
        $pk = $request->input('pk', []);

        // 配列に統一
        $ids = is_array($pk) ? $pk : [$pk];
        $ids = array_values(array_filter($ids, fn($v) => preg_match('/^\d+$/', (string) $v)));

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

        MailTemplate::whereIn('mail_template_id', $ids)->delete();

        return redirect()->route('mail_templates')->with('success', '削除しました。');
    }
    /**
     * バリデーション共通化
     */
    private function validateTemplate(Request $request)
    {
        return $request->validate([
            'pg_id' => 'required|integer',
            'internal_id' => 'required|integer',
            'mgr_cc_flag' => 'required|boolean',
            'bcc_adrs' => 'nullable|string|max:255',
            'use_flag' => 'required|boolean',
            'memo' => 'nullable|string|max:255',
            'subject' => 'required|string|max:255',
            'text' => 'required|string',
        ]);
    }
}
