<?php

namespace App\Livewire\Enrollments;

use App\Domain\Shared\Traits\UsesBranchScope;
use App\Domain\Training\Models\Enrollment;
use App\Domain\Training\Models\TrainingGroup;
use App\Domain\Training\Models\TrainingProgram;
use App\Domain\Training\Services\EnrollmentService;
use App\Domain\Shared\Exceptions\DomainException;
use App\Livewire\Concerns\AppliesRoleScope;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('التسجيلات')]
class EnrollmentList extends Component
{
    use WithPagination, UsesBranchScope, AppliesRoleScope;

    protected string $scopePermission = 'enrollments.list';

    #[Url]
    public string $search = '';

    #[Url]
    public string $status = '';

    #[Url]
    public string $programFilter = '';

    public string $groupFilter = '';
    public string $paymentFilter = '';

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedStatus(): void
    {
        $this->resetPage();
    }

    public function updatedProgramFilter(): void
    {
        $this->groupFilter = '';
        $this->resetPage();
    }

    public function updatedGroupFilter(): void
    {
        $this->resetPage();
    }

    public function updatedPaymentFilter(): void
    {
        $this->resetPage();
    }

    public function cancelEnrollment(int $enrollmentId, string $reason): void
    {
        $this->authorize('enrollments.cancel');

        try {
            $enrollment = Enrollment::findOrFail($enrollmentId);
            $service = app(EnrollmentService::class);
            $service->cancel($enrollment, $reason, auth()->user());
            session()->flash('success', __('تم إلغاء التسجيل بنجاح'));
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        $branchId = $this->getActiveBranchId();

        $query = Enrollment::query()
            ->with(['participant.person', 'group', 'program'])
            ->when($branchId, fn ($q) => $q->whereHas('group', fn ($gq) => $gq->where('branch_id', $branchId)))
            ->when($this->search, function ($q) {
                $search = $this->search;
                $q->where(function ($q2) use ($search) {
                    $q2->whereHas('participant.person', function ($pq) use ($search) {
                        $pq->where('name_ar', 'ilike', "%{$search}%")
                           ->orWhere('name', 'ilike', "%{$search}%");
                    })->orWhereHas('participant', function ($pq) use ($search) {
                        $pq->where('participant_number', 'ilike', "%{$search}%");
                    });
                });
            })
            ->when($this->status, fn ($q) => $q->where('status', $this->status))
            ->when($this->programFilter, fn ($q) => $q->where('training_program_id', $this->programFilter))
            ->when($this->groupFilter, fn ($q) => $q->where('training_group_id', $this->groupFilter))
            ->when($this->paymentFilter, fn ($q) => $q->where('payment_status', $this->paymentFilter))
            ->orderByDesc('enrollment_date');

        $this->applyRoleScope($query);

        $groups = TrainingGroup::whereIn('status', ['forming', 'active', 'full'])
            ->when($this->programFilter, fn ($q) => $q->where('training_program_id', $this->programFilter))
            ->orderBy('name_ar')
            ->get(['id', 'name_ar']);

        return view('livewire.enrollments.enrollment-list', [
            'enrollments' => $query->paginate(20),
            'programs' => TrainingProgram::where('status', 'active')->orderBy('name_ar')->get(['id', 'name_ar']),
            'groups' => $groups,
            'statusOptions' => [
                'pending' => 'معلق',
                'active' => 'نشط',
                'completed' => 'مكتمل',
                'cancelled' => 'ملغي',
                'expired' => 'منتهي',
                'waitlisted' => 'قائمة انتظار',
            ],
            'paymentOptions' => [
                'paid' => 'مدفوع',
                'pending' => 'معلق',
                'partial' => 'جزئي',
                'overdue' => 'متأخر',
                'waived' => 'معفى',
            ],
        ]);
    }
}
