<?php

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

use App\Http\Controllers\Controller;
use App\Http\Controllers\Util;
use App\Voter;
use Illuminate\Support\Facades\DB;

/**
 * Lists every distinct member (by no_kp) found anywhere in voter,
 * for picking who is applicable to the current election.
 */
class AllMembersCatalogController extends Controller
{
    public function __invoke()
    {
        $electionId = Util::getCurrentElection();

        $maxIds = DB::table('voter')
            ->select(DB::raw('MAX(id) as id'))
            ->whereNotNull('no_kp')
            ->where('no_kp', '!=', '')
            ->groupBy('no_kp')
            ->pluck('id');

        $rows = Voter::whereIn('id', $maxIds)
            ->orderBy('name')
            ->get(['no_kp', 'no_anggota', 'name', 'unit']);

        $inCurrent = Voter::where('election_id', $electionId)
            ->pluck('no_kp')
            ->filter(function ($kp) {
                return $kp !== null && $kp !== '';
            })
            ->flip();

        $catalog = $rows->map(function ($row) use ($inCurrent) {
            return [
                'no_kp' => $row->no_kp,
                'no_anggota' => $row->no_anggota,
                'name' => $row->name,
                'unit' => $row->unit,
                'in_current_election' => $inCurrent->has($row->no_kp),
            ];
        });

        return response()->json([
            'election_id' => $electionId,
            'catalog' => $catalog->values()->all(),
        ]);
    }
}
