<?php

namespace App\Http\Controllers\School;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class UserActivityController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);

        $users = $schoolId
            ? DB::table('users as u')
                ->leftJoin('login_logs as ll', function ($join) use ($schoolId): void {
                    $join->on('ll.user_id', '=', 'u.id')
                        ->where('ll.status', 'success');
                })
                ->leftJoin('user_heartbeats as uh', 'uh.user_id', '=', 'u.id')
                ->where('u.school_id', $schoolId)
                ->groupBy(
                    'u.id', 'u.first_name', 'u.last_name', 'u.username',
                    'u.role_key', 'u.status', 'uh.last_seen_at'
                )
                ->select([
                    'u.id',
                    'u.first_name',
                    'u.last_name',
                    'u.username',
                    'u.role_key',
                    'u.status',
                    'uh.last_seen_at',
                    DB::raw('COUNT(ll.id) as total_logins'),
                    DB::raw("SUM(CASE WHEN ll.created_at >= '".now()->startOfMonth()->toDateTimeString()."' THEN 1 ELSE 0 END) as logins_this_month"),
                    DB::raw('MAX(ll.created_at) as last_login_at'),
                ])
                ->orderBy('u.last_name')
                ->limit(500)
                ->get()
            : collect();

        $now = now();

        return Inertia::render('School/UserActivity', [
            'users' => $users->map(function ($user) use ($now): array {
                $lastSeenAt = $user->last_seen_at ? \Carbon\Carbon::parse($user->last_seen_at) : null;
                $isOnline = $lastSeenAt && $lastSeenAt->diffInMinutes($now) <= 5;

                return [
                    'id' => (int) $user->id,
                    'name' => trim($user->first_name.' '.$user->last_name),
                    'username' => $user->username,
                    'roleKey' => $user->role_key,
                    'status' => $user->status,
                    'totalLogins' => (int) ($user->total_logins ?? 0),
                    'loginsThisMonth' => (int) ($user->logins_this_month ?? 0),
                    'lastLoginAt' => $user->last_login_at ? $this->jalaliDate($user->last_login_at, true) : '—',
                    'lastSeenAt' => $user->last_seen_at ? $this->jalaliDate($user->last_seen_at, true) : '—',
                    'isOnline' => $isOnline,
                ];
            })->values(),
        ]);
    }
}
