<?php

namespace App\Livewire\Attendance;

use App\Domain\Shared\Traits\UsesBranchScope;
use App\Domain\Training\Models\TrainingSession;
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 AttendanceList extends Component
{
    use WithPagination, UsesBranchScope, AppliesRoleScope, WithSorting;

    protected string $scopePermission = 'attendance.list';

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

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

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

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

    public function mount(): void
    {
        $this->authorize('attendance.list');
        if (!request()->has('sortBy')) {
            $this->sortBy = 'session_date';
        }
        if (!request()->has('sortDir')) {
            $this->sortDir = 'desc';
        }
        if (!$this->dateFrom) {
            $this->dateFrom = now()->subDays(7)->format('Y-m-d');
        }
        if (!$this->dateTo) {
            $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 updatedFilter(): 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}%")))
            ->when($this->filter === 'not_taken', function ($q) {
                $q->whereIn('status', ['scheduled', 'in_progress', 'completed'])
                  ->where('end_time', '<', now()->format('H:i:s'))
                  ->whereDoesntHave('attendanceRecords', fn ($ar) => $ar->whereNotIn('status', ['expected']));
            })
            ->orderBy($this->sortBy, $this->sortDir);

        $this->applyRoleScope($query);

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