<?php

namespace App\Modules\Pilkades\Http\Controllers\AdminDesa;

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Models\Candidate;
use App\Modules\Pilkades\Models\Desa;
use App\Modules\Pilkades\Models\VisitorLog;
use App\Modules\Pilkades\Models\Voter;
use App\Modules\Pilkades\Services\ShareService;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class DashboardController extends Controller
{
    public function __construct(protected ShareService $shareService) {}

    public function index(): View
    {
        $desa = Desa::with('kecamatan.kabupaten')->find(Auth::user()->desa_id);

        $stats = [
            'candidates' => Candidate::count(),
            'voters' => Voter::count(),
            'visitors_total' => VisitorLog::count(),
            'visitors_today' => VisitorLog::whereDate('visited_at', today())->count(),
            'visitors_this_month' => VisitorLog::whereYear('visited_at', now()->year)
                ->whereMonth('visited_at', now()->month)
                ->count(),
        ];

        $landingUrl = null;
        $qrCodeUrl = null;

        if ($desa) {
            $landingUrl = $this->shareService->landingUrl($desa);
            $qrCodeUrl = route('public.share.qr-code', [
                $desa->kecamatan->kabupaten->slug,
                $desa->kecamatan->slug,
                $desa->slug,
            ]);
        }

        return view('pilkades::admin-desa.dashboard', compact('desa', 'stats', 'landingUrl', 'qrCodeUrl'));
    }
}
