<?php

namespace App\Livewire\Activities;

use App\Domain\HR\Models\Trainer;
use App\Domain\Training\Models\Activity;
use App\Domain\Training\Services\ActivityService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('الأنشطة')]
class ActivityList extends Component
{
    #[Url]
    public string $search = '';

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

    public function updatedSearch(): void
    {
        // Reset not needed without pagination, but keeping for consistency
    }

    public function toggleActive(string $uuid, ActivityService $service): void
    {
        $activity = Activity::where('uuid', $uuid)->firstOrFail();
        $service->toggleActive($activity);
    }

    public function delete(string $uuid, ActivityService $service): void
    {
        try {
            $activity = Activity::where('uuid', $uuid)->firstOrFail();
            $service->delete($activity);
            session()->flash('success', __('تم حذف النشاط بنجاح'));
        } catch (\App\Domain\Shared\Exceptions\DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        $query = Activity::query()
            ->withCount('participants')
            ->when($this->search, fn ($q) => $q->where('name_ar', 'ilike', "%{$this->search}%")
                ->orWhere('name', 'ilike', "%{$this->search}%"))
            ->when($this->category, fn ($q) => $q->where('category', $this->category))
            ->orderBy('sort_order')
            ->orderBy('name_ar');

        $trainersByActivity = [];
        foreach (Trainer::with('employee.person')->where('status', 'active')->get() as $trainer) {
            if (!empty($trainer->sports)) {
                foreach ($trainer->sports as $actId) {
                    $trainersByActivity[$actId][] = $trainer->employee->person->name_ar ?? '';
                }
            }
        }

        return view('livewire.activities.activity-list', [
            'activities' => $query->get(),
            'trainersByActivity' => $trainersByActivity,
            'categoryLabels' => [
                'sport' => 'رياضة',
                'art' => 'فنون',
                'academic' => 'أكاديمي',
                'fitness' => 'لياقة',
                'other' => 'أخرى',
            ],
        ]);
    }
}
