<?php

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

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Models\Candidate;
use App\Modules\Pilkades\Models\Desa;
use App\Modules\Pilkades\Models\Kabupaten;
use App\Modules\Pilkades\Models\Kecamatan;
use App\Modules\Pilkades\Models\VisitorLog;
use App\Modules\Pilkades\Models\Voter;
use Illuminate\View\View;

class DashboardController extends Controller
{
    public function index(): View
    {
        $stats = [
            'kabupaten' => Kabupaten::count(),
            'kecamatan' => Kecamatan::count(),
            'desa' => Desa::count(),
            'candidates' => Candidate::count(),
            'voters' => Voter::count(),
            'visitors' => VisitorLog::count(),
        ];

        $dailyVisitors = VisitorLog::query()
            ->selectRaw('DATE(visited_at) as date, COUNT(*) as total')
            ->where('visited_at', '>=', now()->subDays(14))
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        $desaPerKabupaten = Kabupaten::query()
            ->withCount(['kecamatan as desa_count' => function ($query) {
                $query->join('desa', 'desa.kecamatan_id', '=', 'kecamatan.id');
            }])
            ->orderByDesc('desa_count')
            ->limit(10)
            ->get(['id', 'nama']);

        $topKota = VisitorLog::query()
            ->selectRaw('kota, COUNT(*) as total')
            ->whereNotNull('kota')
            ->groupBy('kota')
            ->orderByDesc('total')
            ->limit(10)
            ->get();

        return view('pilkades::super-admin.dashboard', compact('stats', 'dailyVisitors', 'desaPerKabupaten', 'topKota'));
    }
}
