<?php

namespace App\Livewire\Parent;

use App\Domain\Pricing\Models\BasePrice;
use App\Domain\Training\Models\Activity;
use App\Domain\Training\Models\TrainingProgram;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.parent')]
#[Title('البرامج المتاحة - بوابة ولي الأمر')]
class ParentPrograms extends Component
{
    use WithPagination;

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

    #[Url]
    public ?int $activityFilter = null;

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

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

    public function render()
    {
        $programsQuery = TrainingProgram::where('status', 'active')
            ->where('registration_open', true)
            ->with(['activity', 'branch']);

        if ($this->search !== '') {
            $programsQuery->where(function ($q) {
                $q->where('name_ar', 'ilike', '%' . $this->search . '%')
                    ->orWhere('name', 'ilike', '%' . $this->search . '%')
                    ->orWhere('description_ar', 'ilike', '%' . $this->search . '%');
            });
        }

        if ($this->activityFilter) {
            $programsQuery->where('activity_id', $this->activityFilter);
        }

        $programs = $programsQuery->orderBy('sort_order')->orderBy('name_ar')->paginate(12);

        // Load base prices for these programs
        $programIds = $programs->pluck('id')->toArray();
        $basePrices = BasePrice::where('priceable_type', TrainingProgram::class)
            ->whereIn('priceable_id', $programIds)
            ->where('is_active', true)
            ->get()
            ->keyBy('priceable_id');

        // Available activities for filter
        $activities = Activity::where('is_active', true)
            ->orderBy('name_ar')
            ->get();

        return view('livewire.parent.parent-programs', [
            'programs' => $programs,
            'basePrices' => $basePrices,
            'activities' => $activities,
        ]);
    }
}
