Files
score_and_win/app/Http/Controllers/HomeController.php
T
2026-06-10 10:46:22 +05:45

123 lines
3.9 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Registration;
use Carbon\Carbon;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
$user = auth()->user();
return match ($user->role) {
'admin' => $this->adminDashboard(),
'counselor' => $this->counselorDashboard(),
default => abort(403, 'Unauthorized action.'),
};
}
public function adminDashboard()
{
$today = Carbon::today();
$query = Registration::with([
'sessions' => function ($q) use ($today) {
$q->whereDate('play_date', $today)->with('shots');
}
])
->whereHas('sessions', function ($q) use ($today) {
$q->whereDate('play_date', $today);
})
->orderBy('created_at', 'desc')
->paginate(10);
$registrations = $query->getCollection()->map(function ($student) {
$todaySession = $student->sessions->first();
$todayGoals = null;
if ($todaySession) {
$todayGoals = $todaySession->shots
->sortBy('shot_number')
->map(fn($shot) => (bool) $shot->result)
->values()
->toArray();
}
return [
'id' => $student->id,
'name' => $student->name,
'phone' => $student->phone,
'email' => $student->email,
'today_goals' => $todayGoals,
'total_score' => $student->total_score,
'session_id' => $todaySession?->id,
];
});
$query->setCollection($registrations);
$data['registrations'] = $query;
$data['total'] = Registration::count();
$data['played'] = $registrations->filter(fn($r) => !empty($r['today_goals']) && count($r['today_goals']) >= 3)->count();
$data['topScore'] = $registrations->max('total_score') ?? 0;
return view('dashboard.admin', $data);
}
public function counselorDashboard()
{
$today = Carbon::today();
$query = Registration::with([
'sessions' => function ($q) use ($today) {
$q->whereDate('play_date', $today)->with('shots');
},
'comments'
])
->whereHas('sessions', function ($q) use ($today) {
$q->whereDate('play_date', $today);
})
->orderBy('created_at', 'desc')
->paginate(10);
$registrations = $query->getCollection()->map(function ($student) {
$todaySession = $student->sessions->first();
$todayGoals = null;
if ($todaySession) {
$todayGoals = $todaySession->shots
->sortBy('shot_number')
->map(fn($shot) => (bool) $shot->result)
->values()
->toArray();
}
return [
'id' => $student->id,
'name' => $student->name,
'phone' => $student->phone,
'email' => $student->email,
'today_goals' => $todayGoals,
'total_score' => $student->total_score,
'session_id' => $todaySession?->id,
'comment_count' => $student->comments->count(),
];
});
$query->setCollection($registrations);
$data['registrations'] = $query;
$data['total'] = Registration::count();
$data['played'] = $registrations->filter(fn($r) => !empty($r['today_goals']) && count($r['today_goals']) >= 3)->count();
$data['topScore'] = $registrations->max('total_score') ?? 0;
return view('dashboard.counselor', $data);
}
}