<?php

namespace Modules\MembershipApplication\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Modules\MembershipApplication\Http\Requests\LookupMemberRequest;
use Modules\MembershipApplication\Http\Requests\StoreMembershipApplicationRequest;
use Modules\MembershipApplication\Services\MembershipApplicationService;
use Modules\MembershipApplication\Transformers\MembershipApplicationResource;

class PublicMembershipApplicationController extends Controller
{
    public function __construct(
        protected MembershipApplicationService $membershipApplicationService
    ) {}

    public function store(StoreMembershipApplicationRequest $request): JsonResponse
    {
        $documents = collect($request->file('documents', []))
            ->filter()
            ->all();

        $application = $this->membershipApplicationService->submit(
            $request->safe()->except(['documents']),
            $documents
        );

        return response()->json([
            'success' => true,
            'message' => 'Permohonan keahlian berjaya dihantar.',
            'data' => new MembershipApplicationResource($application),
        ], 201);
    }

    public function lookupMember(LookupMemberRequest $request): JsonResponse
    {
        $member = $this->membershipApplicationService->lookupMemberByIcNumber(
            $request->validated('ic_number')
        );

        if (! $member) {
            return response()->json([
                'success' => false,
                'message' => 'Ahli dengan nombor kad pengenalan ini tidak dijumpai.',
                'data' => null,
            ]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Ahli dijumpai.',
            'data' => [
                'id' => $member->id,
                'name' => $member->name,
                'ic_number' => $member->ic_number,
            ],
        ]);
    }
}
