<?php

namespace App\Livewire\Groups;

use App\Domain\Attendance\Enums\AttendanceStatus;
use App\Domain\Attendance\Models\AttendanceRecord;
use App\Domain\Training\Enums\SessionStatus;
use App\Domain\Training\Models\Enrollment;
use App\Domain\Training\Models\TrainingGroup;
use App\Domain\Training\Models\TrainingSession;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('تفاصيل المجموعة')]
class GroupShow extends Component
{
    public TrainingGroup $group;
    public string $activeTab = 'overview';

    public function mount(TrainingGroup $group): void
    {
        $this->authorize('groups.list');

        $this->group = $group->load([
            'program',
            'branch',
            'headTrainer',
            'creator',
            'schedules',
            'schedules.facility',
            'schedules.trainer',
        ]);
    }

    public function render()
    {
        // Active enrollments with participant details
        $activeEnrollments = Enrollment::where('training_group_id', $this->group->id)
            ->where('status', 'active')
            ->with(['participant.person'])
            ->orderBy('enrollment_date')
            ->get();

        // All enrollments count (any status)
        $totalEnrollments = Enrollment::where('training_group_id', $this->group->id)
            ->whereNotIn('status', ['cancelled'])
            ->count();

        // Sessions: recent completed + upcoming scheduled
        $recentSessions = TrainingSession::where('training_group_id', $this->group->id)
            ->where('session_date', '<', now()->toDateString())
            ->orderByDesc('session_date')
            ->limit(20)
            ->get();

        $upcomingSessions = TrainingSession::where('training_group_id', $this->group->id)
            ->where('session_date', '>=', now()->toDateString())
            ->orderBy('session_date')
            ->limit(10)
            ->get();

        // Session stats
        $totalSessions = TrainingSession::where('training_group_id', $this->group->id)->count();
        $completedSessions = TrainingSession::where('training_group_id', $this->group->id)
            ->where('status', SessionStatus::Completed)
            ->count();

        // Attendance stats for the group (across all sessions)
        $sessionIds = TrainingSession::where('training_group_id', $this->group->id)
            ->pluck('id');

        $attendanceQuery = AttendanceRecord::whereIn('training_session_id', $sessionIds);

        $totalAttendanceRecords = (clone $attendanceQuery)->count();
        $presentCount = (clone $attendanceQuery)->where('status', AttendanceStatus::Present)->count();
        $lateCount = (clone $attendanceQuery)->where('status', AttendanceStatus::Late)->count();
        $absentCount = (clone $attendanceQuery)->whereIn('status', [AttendanceStatus::Absent, AttendanceStatus::NoShow])->count();
        $partialCount = (clone $attendanceQuery)->where('status', AttendanceStatus::Partial)->count();
        $excusedCount = (clone $attendanceQuery)->where('status', AttendanceStatus::Excused)->count();
        $cancelledExempt = (clone $attendanceQuery)->whereIn('status', [AttendanceStatus::Cancelled, AttendanceStatus::Exempt])->count();

        $attendanceDenominator = $totalAttendanceRecords - $cancelledExempt;
        $attendanceRate = $attendanceDenominator > 0
            ? round(($presentCount + $lateCount + $partialCount) / $attendanceDenominator * 100, 1)
            : 0;

        // Capacity percentage
        $capacityPercent = $this->group->max_capacity > 0
            ? round(($this->group->current_count / $this->group->max_capacity) * 100, 1)
            : 0;

        // Per-participant attendance rates for enrollments tab
        $participantAttendanceRates = [];
        if ($activeEnrollments->isNotEmpty() && $sessionIds->isNotEmpty()) {
            $participantClass = \App\Domain\Participant\Models\Participant::class;
            foreach ($activeEnrollments as $enrollment) {
                $pQuery = AttendanceRecord::whereIn('training_session_id', $sessionIds)
                    ->where('subject_type', $participantClass)
                    ->where('subject_id', $enrollment->participant_id);

                $pTotal = (clone $pQuery)->count();
                $pExcluded = (clone $pQuery)->whereIn('status', [AttendanceStatus::Cancelled, AttendanceStatus::Exempt])->count();
                $pPositive = (clone $pQuery)->whereIn('status', [AttendanceStatus::Present, AttendanceStatus::Late, AttendanceStatus::Partial])->count();

                $pDenom = $pTotal - $pExcluded;
                $participantAttendanceRates[$enrollment->participant_id] = $pDenom > 0
                    ? round(($pPositive / $pDenom) * 100, 1)
                    : null;
            }
        }

        // Waitlist count
        $waitlistCount = $this->group->waitlist_count ?? 0;

        return view('livewire.groups.group-show', [
            'activeEnrollments' => $activeEnrollments,
            'totalEnrollments' => $totalEnrollments,
            'recentSessions' => $recentSessions,
            'upcomingSessions' => $upcomingSessions,
            'totalSessions' => $totalSessions,
            'completedSessions' => $completedSessions,
            'totalAttendanceRecords' => $totalAttendanceRecords,
            'presentCount' => $presentCount,
            'lateCount' => $lateCount,
            'absentCount' => $absentCount,
            'partialCount' => $partialCount,
            'excusedCount' => $excusedCount,
            'attendanceRate' => $attendanceRate,
            'capacityPercent' => $capacityPercent,
            'participantAttendanceRates' => $participantAttendanceRates,
            'waitlistCount' => $waitlistCount,
        ]);
    }
}
