<?php

namespace App\Http\Controllers\API\v1\Voter;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Util;
use App\Voter;
use Illuminate\Http\Request;

class VerifyFizikalRegistrationController extends Controller
{
    /**
     * Admin confirms physical registration so the voter may vote (fizikal_registration_verified_at).
     */
    public function __invoke(Request $request, $id)
    {
        $electionId = Util::getCurrentElection();

        $voter = Voter::where('election_id', $electionId)
            ->where('id', $id)
            ->firstOrFail();

        if ((int) $voter->kehadiran !== 1) {
            return response()->json([
                'status' => 'failed',
                'message' => 'Pengesahan pendaftaran fizikal hanya untuk pengundi Fizikal.',
            ], 422);
        }

        if ($voter->fizikal_registration_verified_at !== null) {
            activity()
                ->performedOn($voter)
                ->withProperties([
                    'election_id' => $electionId,
                    'voter_id' => $voter->id,
                    'voter_name' => $voter->name,
                    'already_verified' => true,
                    'verified_at' => (string) $voter->fizikal_registration_verified_at,
                    'verified_by_admin_id' => $request->user() ? (int) $request->user()->id : null,
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ])
                ->log("verify fizikal registration: {$voter->name}");

            return response()->json([
                'status' => 'success',
                'message' => 'Pendaftaran telah disahkan sebelum ini.',
                'voter' => $voter,
            ]);
        }

        $voter->fizikal_registration_verified_at = now();
        $voter->save();

        activity()
            ->performedOn($voter)
            ->withProperties([
                'election_id' => $electionId,
                'voter_id' => $voter->id,
                'voter_name' => $voter->name,
                'already_verified' => false,
                'verified_at' => (string) $voter->fizikal_registration_verified_at,
                'verified_by_admin_id' => $request->user() ? (int) $request->user()->id : null,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("verify fizikal registration: {$voter->name}");

        return response()->json([
            'status' => 'success',
            'message' => 'Pendaftaran fizikal telah disahkan.',
            'voter' => $voter->fresh(),
        ]);
    }
}
