<?php

namespace App\Livewire\Programs;

use App\Domain\Shared\Exceptions\DomainException;
use App\Domain\Training\Models\Enrollment;
use App\Domain\Training\Models\TrainingGroup;
use App\Domain\Training\Models\TrainingProgram;
use App\Domain\Training\Services\TrainingProgramService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('تفاصيل البرنامج')]
class ProgramShow extends Component
{
    public TrainingProgram $program;
    public string $activeTab = 'overview';

    public function mount(TrainingProgram $program): void
    {
        $this->authorize('programs.list');

        $this->program = $program->load([
            'activity',
            'branch',
            'defaultTrainer',
            'creator',
            'groups.headTrainer',
            'groups.schedules',
            'enrollments.participant.person',
            'enrollments.group',
        ]);
    }

    public function deleteProgram(TrainingProgramService $service): void
    {
        $this->authorize('programs.delete');

        try {
            $service->delete($this->program);
            session()->flash('success', __('تم حذف البرنامج وجميع مجموعاته بنجاح'));
            $this->redirect(route('programs.list'), navigate: true);
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        $groups = $this->program->groups;
        $enrollments = $this->program->enrollments;

        // KPI calculations
        $totalGroups = $groups->count();
        $activeEnrollments = $enrollments->where('status.value', 'active')->count();
        $totalCapacity = $groups->sum('max_capacity');
        $fillRate = $totalCapacity > 0 ? round(($activeEnrollments / $totalCapacity) * 100, 1) : 0;
        $waitlistTotal = $groups->sum('waitlist_count');

        // Total revenue from enrollment invoices
        $totalRevenue = Enrollment::where('training_program_id', $this->program->id)
            ->whereNotNull('invoice_id')
            ->with('invoice')
            ->get()
            ->sum(fn ($e) => $e->invoice?->total_amount ?? 0);

        // Recent enrollments (last 20)
        $recentEnrollments = $enrollments->sortByDesc('enrollment_date')->take(20);

        return view('livewire.programs.program-show', [
            'groups' => $groups,
            'totalGroups' => $totalGroups,
            'activeEnrollments' => $activeEnrollments,
            'totalCapacity' => $totalCapacity,
            'fillRate' => $fillRate,
            'waitlistTotal' => $waitlistTotal,
            'totalRevenue' => $totalRevenue,
            'recentEnrollments' => $recentEnrollments,
        ]);
    }
}
