<?php
class EndorsementApiController extends Controller
{
    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) {
            $this->json(['success' => false, 'message' => 'Invalid CSRF token'], 403);
            return;
        }

        $memberId = (int) $request->routeParam('id');

        $validator = new Validator($request->all(), [
            'endorsement_type_id'       => 'required|integer|exists:endorsement_types,id',
            'endorsed_person_name'      => 'required|string|max:300',
            'endorsed_person_phone'     => 'nullable|string|max:20',
            'endorsed_person_national_id' => 'nullable|string|max:20',
            'endorsement_text'          => 'nullable|string',
        ]);

        if ($validator->fails()) {
            $this->json(['success' => false, 'errors' => $validator->errors()], 422);
            return;
        }

        $number = SequenceGenerator::next('endorsement_number');
        $db = Database::getInstance();

        $id = $db->insert('member_endorsements', [
            'endorsement_number'          => $number,
            'endorsement_type_id'         => $request->post('endorsement_type_id'),
            'endorser_member_id'          => $memberId,
            'endorsed_person_name'        => $request->post('endorsed_person_name'),
            'endorsed_person_phone'       => $request->post('endorsed_person_phone'),
            'endorsed_person_national_id' => $request->post('endorsed_person_national_id'),
            'endorsement_date'            => date('Y-m-d'),
            'endorsement_text'            => $request->post('endorsement_text'),
            'status'                      => 'active',
        ]);

        AuditLog::log('create', 'members', 'member_endorsements', $id, "Created endorsement {$number}");

        $this->json(['success' => true, 'message' => 'Endorsement created: ' . $number]);
    }
}