<?php

namespace App\Http\Controllers\Admin\Members;

use App\Http\Controllers\Controller;
use App\Services\Admin\Member\AdminMemberJoinFilterService;
use Illuminate\Http\Request;

final class AdminMemberJoinFilterController extends Controller
{
    public function __construct(
        private readonly AdminMemberJoinFilterService $service,
    ) {}

    public function index(Request $request)
    {
        // ✅ query 전달(전역 request 의존 줄이기)
        $data = $this->service->indexData($request->query());

        return view('admin.members.join_filters.index', $data);
    }

    /**
     * AJAX row
     */
    public function get(int $seq, Request $request)
    {
        $row = $this->service->getRow($seq);

        if (!$row) {
            return response()->json([
                'ok' => false,
                'message' => 'NOT_FOUND',
                'row' => null,
            ], 404);
        }

        return response()->json([
            'ok' => true,
            'row' => $row,
        ]);
    }

    private function safeReturnTo(?string $rt): ?string
    {
        $rt = trim((string)$rt);
        if ($rt === '') return null;

        // 상대경로만 허용 (오픈리다이렉트 방지)
        if (!str_starts_with($rt, '/')) return null;

        // join-filters 화면으로만 복귀 허용
        if (!str_contains($rt, 'join-filters')) return null;

        return $rt;
    }

    public function store(Request $request)
    {
        $payload = $this->validated($request);

        $res = $this->service->store(
            input: $payload,
            actorName: $this->actorName(),
        );

        $to = $this->safeReturnTo($request->input('_return_to'))
            ?? route('admin.join-filters.index', [], false);

        return redirect()->to($to)
            ->with('toast', [
                'type' => ($res['ok'] ?? false) ? 'success' : 'danger',
                'title' => ($res['ok'] ?? false) ? '등록 완료' : '등록 실패',
                'message' => $res['message'] ?? '',
            ]);
    }

    public function update(int $seq, Request $request)
    {
        $payload = $this->validated($request);

        $res = $this->service->update(
            seq: $seq,
            input: $payload,
            actorName: $this->actorName(),
        );

        $to = $this->safeReturnTo($request->input('_return_to'))
            ?? route('admin.join-filters.index', [], false);

        return redirect()->to($to)
            ->with('toast', [
                'type' => ($res['ok'] ?? false) ? 'success' : 'danger',
                'title' => ($res['ok'] ?? false) ? '수정 완료' : '수정 실패',
                'message' => $res['message'] ?? '',
            ]);
    }

    public function destroy(int $seq, Request $request)
    {
        $res = $this->service->destroy($seq);
        $to = $this->safeReturnTo($request->input('_return_to'))
            ?? route('admin.join-filters.index', [], false);

        return redirect()->to($to)
            ->with('toast', [
                'type' => ($res['ok'] ?? false) ? 'success' : 'danger',
                'title' => ($res['ok'] ?? false) ? '삭제 완료' : '삭제 실패',
                'message' => $res['message'] ?? '',
            ]);
    }

    private function actorName(): string
    {
        $name = trim((string) session('admin_ctx.name'));
        if ($name !== '') return $name;

        $u = auth('admin')->user();
        return trim((string)($u->name ?? $u->nickname ?? $u->email ?? ''));
    }

    private function validated(Request $request): array
    {
        $data = $request->validate([
            'gubun_code' => ['required', 'string', 'in:01,02'],
            'filter'     => ['required', 'string', 'max:50'],
            'join_block' => ['required', 'string', 'in:S,A,N'],

            'admin_phone'   => ['nullable', 'array'],
            'admin_phone.*' => ['string', 'max:30'],

            // ✅ 모달에서 유지용(검증대상 아님) - withInput을 위해 받아둠
            'filter_seq' => ['nullable', 'string', 'max:20'],
        ]);

        if (($data['join_block'] ?? '') === 'S' && empty($data['admin_phone'])) {
            return redirect()->back()->withInput()->withErrors([
                'admin_phone' => '관리자SMS알림(S)을 선택한 경우 알림받을 관리자를 선택해야 합니다.',
            ])->throwResponse();
        }

        return $data;
    }
}
