<?php

namespace App\Livewire\Enrollments;

use App\Domain\Participant\Models\Participant;
use App\Domain\Training\Models\TrainingGroup;
use App\Domain\Training\Services\EnrollmentService;
use App\Domain\Shared\Exceptions\DomainException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('تسجيل في مجموعة')]
class EnrollmentForm extends Component
{
    public ?int $participant_id = null;
    public ?int $training_group_id = null;
    public ?string $start_date = null;
    public string $payment_status = 'pending';
    public string $notes = '';

    public function mount(): void
    {
        $this->authorize('enrollments.create');
    }

    public function rules(): array
    {
        return [
            'participant_id' => 'required|exists:participants,id',
            'training_group_id' => 'required|exists:training_groups,id',
            'start_date' => 'nullable|date',
            'payment_status' => 'required|in:paid,pending,partial,overdue,waived',
            'notes' => 'nullable|string|max:1000',
        ];
    }

    public function messages(): array
    {
        return [
            'participant_id.required' => 'اختيار المشترك مطلوب',
            'participant_id.exists' => 'المشترك المختار غير موجود',
            'training_group_id.required' => 'اختيار المجموعة مطلوب',
            'training_group_id.exists' => 'المجموعة المختارة غير موجودة',
            'start_date.date' => 'تاريخ البدء غير صحيح',
            'payment_status.required' => 'حالة الدفع مطلوبة',
            'payment_status.in' => 'حالة الدفع غير صحيحة',
            'notes.max' => 'الملاحظات يجب ألا تتجاوز 1000 حرف',
        ];
    }

    public function save(EnrollmentService $service): void
    {
        $this->validate();

        try {
            $participant = Participant::findOrFail($this->participant_id);
            $group = TrainingGroup::findOrFail($this->training_group_id);

            $service->enroll($participant, $group, auth()->user(), [
                'start_date' => $this->start_date ?: null,
                'payment_status' => $this->payment_status,
            ]);

            session()->flash('success', __('تم التسجيل بنجاح'));
            $this->redirect(route('enrollments.list'), navigate: true);
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.enrollments.enrollment-form', [
            'participants' => Participant::with('person')
                ->whereIn('status', ['registered', 'active'])
                ->orderBy('created_at', 'desc')
                ->limit(200)
                ->get(),
            'groups' => TrainingGroup::with('program')
                ->whereIn('status', ['forming', 'active'])
                ->orderBy('name_ar')
                ->get(),
            'paymentOptions' => [
                'paid' => 'مدفوع',
                'pending' => 'معلق',
                'partial' => 'جزئي',
                'overdue' => 'متأخر',
                'waived' => 'معفى',
            ],
        ]);
    }
}
