<?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\Locked;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('تفاصيل البرنامج')]
class ProgramShow extends Component
{
    // Which programme this page is showing is the route's decision, resolved
    // through TrainingProgram's branch scope. deleteProgram() acts on it, so it
    // must not be reachable from the browser.
    #[Locked]
    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. No branch clause: Enrollment
        // carries BranchScope, so this counts the same enrolments the tabs
        // below list — an academy-wide programme shows this branch's revenue,
        // not every branch's.
        $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,
        ]);
    }
}
