<?php

namespace App\Livewire\Enrollments;

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

#[Layout('layouts.app')]
#[Title('نقل إلى مجموعة')]
class TransferGroup extends Component
{
    use UsesBranchScope;

    public string $search = '';
    public ?int $participant_id = null;
    public ?int $enrollment_id = null;
    public ?int $destination_group_id = null;

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

    public function rules(): array
    {
        return [
            'participant_id' => 'required|exists:participants,id',
            'enrollment_id' => 'required|exists:enrollments,id',
            'destination_group_id' => 'required|exists:training_groups,id',
        ];
    }

    public function messages(): array
    {
        return [
            'participant_id.required' => 'اختيار المشترك مطلوب',
            'participant_id.exists' => 'المشترك المختار غير موجود',
            'enrollment_id.required' => 'اختيار التسجيل الحالي مطلوب',
            'enrollment_id.exists' => 'التسجيل المختار غير موجود',
            'destination_group_id.required' => 'اختيار المجموعة الجديدة مطلوب',
            'destination_group_id.exists' => 'المجموعة المختارة غير موجودة',
        ];
    }

    public function updatedSearch(): void
    {
        $this->participant_id = null;
        $this->enrollment_id = null;
        $this->destination_group_id = null;
    }

    public function selectParticipant(int $id): void
    {
        $this->participant_id = $id;
        $this->enrollment_id = null;
        $this->destination_group_id = null;
    }

    public function selectEnrollment(int $id): void
    {
        $this->enrollment_id = $id;
        $this->destination_group_id = null;
    }

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

        try {
            $enrollment = Enrollment::findOrFail($this->enrollment_id);
            $toGroup = TrainingGroup::findOrFail($this->destination_group_id);

            $service->transfer($enrollment, $toGroup, auth()->user());

            session()->flash('success', __('تم نقل المشترك بنجاح إلى المجموعة الجديدة'));
            $this->redirect(route('enrollments.list'), navigate: true);
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

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

        // Search participants
        $participants = collect();
        if (strlen($this->search) >= 2) {
            $participants = Participant::with('person')
                ->whereIn('status', ['registered', 'active'])
                ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
                ->where(function ($q) {
                    $q->whereHas('person', function ($pq) {
                        $pq->where('name_ar', 'ilike', "%{$this->search}%")
                           ->orWhere('name', 'ilike', "%{$this->search}%");
                    })->orWhere('participant_number', 'ilike', "%{$this->search}%");
                })
                ->limit(20)
                ->get();
        }

        // Active enrollments for selected participant
        $activeEnrollments = collect();
        if ($this->participant_id) {
            $activeEnrollments = Enrollment::with(['group', 'program'])
                ->where('participant_id', $this->participant_id)
                ->where('status', 'active')
                ->get();
        }

        // Available destination groups (excluding current group)
        $destinationGroups = collect();
        if ($this->enrollment_id) {
            $enrollment = Enrollment::find($this->enrollment_id);
            if ($enrollment) {
                $destinationGroups = TrainingGroup::with('program')
                    ->whereIn('status', ['forming', 'active'])
                    ->where('id', '!=', $enrollment->training_group_id)
                    ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
                    ->whereColumn('current_count', '<', 'max_capacity')
                    ->orderBy('name_ar')
                    ->get();
            }
        }

        return view('livewire.enrollments.transfer-group', [
            'participants' => $participants,
            'activeEnrollments' => $activeEnrollments,
            'destinationGroups' => $destinationGroups,
        ]);
    }
}
