<?php

namespace App\Livewire\Participants;

use App\Domain\Participant\Models\Participant;
use App\Domain\Shared\Traits\UsesBranchScope;
use App\Domain\Training\Models\Activity;
use App\Livewire\Concerns\AppliesRoleScope;
use App\Livewire\Concerns\WithSorting;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('المشتركين')]
class ParticipantList extends Component
{
    use WithPagination, WithSorting, UsesBranchScope, AppliesRoleScope;

    protected string $scopePermission = 'participants.list';

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

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

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

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

    public string $activity = '';
    public string $skillLevel = '';

    public function mount(): void
    {
        if (!request()->has('sortBy')) {
            $this->sortBy = 'name_ar';
        }
        if (!request()->has('sortDir')) {
            $this->sortDir = 'asc';
        }
    }

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

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

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

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

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

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

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

        $query = Participant::query()
            ->with(['person', 'primaryActivity'])
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->when($this->search, function ($q) {
                $search = $this->search;
                $q->where(function ($q2) use ($search) {
                    $q2->where('participant_number', 'ilike', "%{$search}%")
                       ->orWhere('membership_id', 'ilike', "%{$search}%")
                       ->orWhereHas('person', function ($pq) use ($search) {
                           $pq->where('name_ar', 'ilike', "%{$search}%")
                              ->orWhere('name', 'ilike', "%{$search}%")
                              ->orWhere('phone', 'like', "%{$search}%")
                              ->orWhere('national_id', 'like', "%{$search}%");
                       });
                });
            })
            ->when($this->status, fn ($q) => $q->where('status', $this->status))
            ->when($this->activity, fn ($q) => $q->where('primary_activity_id', $this->activity))
            ->when($this->skillLevel, fn ($q) => $q->where('skill_level', $this->skillLevel))
            ->when($this->membershipType, fn ($q) => $q->where('membership_type', $this->membershipType))
            ->when($this->isFree !== '', fn ($q) => $q->where('is_free', $this->isFree === '1'));

        if ($this->sortBy === 'name_ar') {
            $query->join('people', 'participants.person_id', '=', 'people.id')
                  ->orderBy('people.name_ar', $this->sortDir)
                  ->select('participants.*');
        } else {
            $query->orderBy($this->sortBy, $this->sortDir);
        }

        $this->applyRoleScope($query);

        return view('livewire.participants.participant-list', [
            'participants' => $query->paginate(20),
            'activities' => Activity::where('is_active', true)->orderBy('name_ar')->get(['id', 'name_ar']),
            'statusOptions' => [
                'registered' => 'مسجل',
                'active' => 'نشط',
                'frozen' => 'مجمد',
                'suspended' => 'موقوف',
                'inactive' => 'غير نشط',
                'graduated' => 'متخرج',
                'transferred' => 'محول',
                'withdrawn' => 'منسحب',
                'blacklisted' => 'محظور',
            ],
            'skillLevelOptions' => [
                'beginner' => 'مبتدئ',
                'intermediate' => 'متوسط',
                'advanced' => 'متقدم',
                'professional' => 'محترف',
            ],
            'membershipTypeOptions' => [
                'member' => 'عضو',
                'non_member' => 'غير عضو',
            ],
            'isFreeOptions' => [
                '1' => 'مجاني',
                '0' => 'غير مجاني',
            ],
        ]);
    }
}
