<?php

namespace App\Http\Livewire\Admin;

use App\Models\Ballot;
use App\Models\Candidate;
use App\Models\Period;
use App\Models\Voter;
use Livewire\Component;

class DashboardDisplay extends Component
{
    public function render()
    {
        $period = Period::where('is_active', 1)->latest()->first();
        $totalVoters = Voter::where('is_active', 1)->count();
        $votedCount  = Ballot::when($period, fn($q) => $q->where('period_id', $period->id))
                             ->distinct('voter_id')->count('voter_id');
        $totalVotes  = Ballot::when($period, fn($q) => $q->where('period_id', $period->id))
                             ->count();
        $candidateBase = Candidate::query();
        if ($period) {
            $candidateBase->where(function ($w) use ($period) {
                $w->where('period_id', $period->id)
                  ->orWhereNull('period_id');
            });
        }
        $candidateCount = (clone $candidateBase)->count();
        $rawCandidates = (clone $candidateBase)->orderBy('sort_order')->orderBy('name')->get();
        $candidates = $rawCandidates->map(function ($c) use ($period, $totalVotes) {
            $votes = Ballot::where('candidate_id', c->id)
                           ->when($period, fn($q) => $q->where('period_id', $period->id))
                           ->count();
            $percentage = $totalVotes > 0 ? round(($votes / $totalVotes) * 100, 1) : 0.0;

            return (object)[
                'id'         => $c->id,
                'name'       => $c->name,
                'class'      => $c->class,
                'votes'      => $votes,
                'percentage' => $percentage,
            ];
        });

        return view('livewire.admin.dashboarddisplay', [
            'period'         => $period,
            'totalVoters'    => $totalVoters,
            'votedCount'     => $votedCount,
            'candidateCount' => $candidateCount,
            'totalVotes'     => $totalVotes,
            'candidates'     => $candidates,
        ])->layout('layouts.app');
    }
}