<?php

namespace App\Livewire\HR;

use App\Domain\Attendance\Enums\AttendanceStatus;
use App\Domain\Attendance\Models\AttendanceRecord;
use App\Domain\HR\Models\Trainer;
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 TrainerShow extends Component
{
    public Trainer $trainer;
    public string $activeTab = 'overview';

    public function mount(Trainer $trainer): void
    {
        $this->authorize('trainers.list');
        $this->trainer = $trainer->load([
            'employee.person',
            'employee.branch',
            'person',
            'qualifications',
            'availabilities',
            'compensations',
        ]);
    }

    public function render()
    {
        $person = $this->trainer->employee?->person ?? $this->trainer->person;
        $trainerUserId = $this->trainer->employee?->user_id;

        // Groups where this trainer is head trainer
        $groups = TrainingGroup::where('head_trainer_id', $trainerUserId)
            ->with(['program', 'schedules', 'branch'])
            ->withCount(['enrollments as active_enrollments_count' => function ($q) {
                $q->where('status', 'active');
            }])
            ->get();

        // Upcoming sessions (next 7 days)
        $upcomingSessions = TrainingSession::whereHas('group', function ($q) use ($trainerUserId) {
                $q->where('head_trainer_id', $trainerUserId);
            })
            ->where('session_date', '>=', now()->toDateString())
            ->where('session_date', '<=', now()->addDays(7)->toDateString())
            ->with(['group'])
            ->orderBy('session_date')
            ->orderBy('start_time')
            ->limit(20)
            ->get();

        // Attendance stats for this trainer (as subject)
        $trainerClass = Trainer::class;
        $attendanceQuery = AttendanceRecord::where('subject_type', $trainerClass)
            ->where('subject_id', $this->trainer->id);

        $totalSessionsAttended = (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();
        $cancelledExempt = (clone $attendanceQuery)->whereIn('status', [AttendanceStatus::Cancelled, AttendanceStatus::Exempt])->count();

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

        // Total participants across all groups
        $totalParticipants = $groups->sum('active_enrollments_count');

        // Capacity utilization
        $totalCapacity = $groups->sum('max_capacity');
        $capacityRate = $totalCapacity > 0
            ? round($totalParticipants / $totalCapacity * 100, 1)
            : 0;

        // Recent compensations
        $recentCompensations = $this->trainer->compensations()
            ->orderByDesc('period_start')
            ->limit(6)
            ->get();

        // Monthly earnings (current month)
        $monthlyEarnings = $this->trainer->compensations()
            ->where('period_start', '>=', now()->startOfMonth())
            ->where('period_start', '<=', now()->endOfMonth())
            ->sum('total_amount');

        // Advances balance
        $pendingAdvances = $this->trainer->advances()
            ->where('status', 'pending')
            ->sum('amount');

        return view('livewire.hr.trainer-show', [
            'person' => $person,
            'groups' => $groups,
            'upcomingSessions' => $upcomingSessions,
            'totalSessionsAttended' => $totalSessionsAttended,
            'presentCount' => $presentCount,
            'lateCount' => $lateCount,
            'absentCount' => $absentCount,
            'attendanceRate' => $attendanceRate,
            'totalParticipants' => $totalParticipants,
            'capacityRate' => $capacityRate,
            'recentCompensations' => $recentCompensations,
            'monthlyEarnings' => $monthlyEarnings,
            'pendingAdvances' => $pendingAdvances,
        ]);
    }
}
