<?php

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

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

class AttendanceSummaryController extends Controller
{
    /**
     * Aggregate attendance for a specific election (by primary key), for admin reporting.
     * Kehadiran: null/0 = belum ditetapkan, 1 = fizikal, 2 = maya.
     */
    public function __invoke($id)
    {
        $electionId = (int) $id;

        $row = Voter::query()
            ->where('election_id', $electionId)
            ->selectRaw('COUNT(*) as total_registered')
            ->selectRaw('COALESCE(SUM(CASE WHEN kehadiran IS NULL OR kehadiran = 0 THEN 1 ELSE 0 END), 0) as unset')
            ->selectRaw('COALESCE(SUM(CASE WHEN kehadiran = 1 THEN 1 ELSE 0 END), 0) as fizikal')
            ->selectRaw('COALESCE(SUM(CASE WHEN kehadiran = 2 THEN 1 ELSE 0 END), 0) as maya')
            ->selectRaw('COALESCE(SUM(CASE WHEN kehadiran IN (1, 2) THEN 1 ELSE 0 END), 0) as marked_present')
            ->selectRaw('COALESCE(SUM(CASE WHEN kehadiran = 1 AND fizikal_registration_verified_at IS NULL THEN 1 ELSE 0 END), 0) as fizikal_reg_pending')
            ->selectRaw('COALESCE(SUM(CASE WHEN kehadiran = 1 AND fizikal_registration_verified_at IS NOT NULL THEN 1 ELSE 0 END), 0) as fizikal_reg_verified')
            ->first();

        $total = (int) ($row ? $row->total_registered : 0);
        $marked = (int) ($row ? $row->marked_present : 0);

        $votersWhoVoted = (int) DB::table('result')
            ->where('election_id', $electionId)
            ->select(DB::raw('COUNT(DISTINCT voter_id) as c'))
            ->value('c');

        return response()->json([
            'election_id' => $electionId,
            'total_registered' => $total,
            'unset' => (int) ($row ? $row->unset : 0),
            'fizikal' => (int) ($row ? $row->fizikal : 0),
            'maya' => (int) ($row ? $row->maya : 0),
            'marked_present' => $marked,
            'attendance_rate' => $total > 0 ? round(($marked / $total) * 100, 2) : 0.0,
            'fizikal_registration_pending' => (int) ($row ? $row->fizikal_reg_pending : 0),
            'fizikal_registration_verified' => (int) ($row ? $row->fizikal_reg_verified : 0),
            'voters_who_voted' => $votersWhoVoted,
        ]);
    }
}
