<?php

namespace App\Livewire\Attendance;

use App\Domain\Shared\Traits\UsesBranchScope;
use App\Domain\Training\Models\TrainingSession;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('سجل الحضور')]
class AttendanceList extends Component
{
    use WithPagination, UsesBranchScope;

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

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

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

    public function mount(): void
    {
        $this->authorize('attendance.list');
        $this->dateFrom = now()->subDays(7)->format('Y-m-d');
        $this->dateTo = now()->format('Y-m-d');
    }

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

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

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

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

        $query = TrainingSession::query()
            ->with(['group'])
            ->when($branchId, fn ($q) => $q->whereHas('group', fn ($gq) => $gq->where('branch_id', $branchId)))
            ->withCount([
                'attendanceRecords',
                'attendanceRecords as present_count' => fn ($q) => $q->whereIn('status', ['present', 'late', 'partial']),
                'attendanceRecords as absent_count' => fn ($q) => $q->whereIn('status', ['absent', 'no_show']),
            ])
            ->when($this->dateFrom, fn ($q) => $q->where('session_date', '>=', $this->dateFrom))
            ->when($this->dateTo, fn ($q) => $q->where('session_date', '<=', $this->dateTo))
            ->when($this->search, fn ($q) => $q->whereHas('group', fn ($gq) => $gq->where('name_ar', 'ilike', "%{$this->search}%")))
            ->orderByDesc('session_date')
            ->orderByDesc('start_time');

        return view('livewire.attendance.attendance-list', [
            'sessions' => $query->paginate(20),
        ]);
    }
}
