<?php

namespace App\Livewire\Receptionist;

use App\Domain\Attendance\Enums\AttendanceStatus;
use App\Domain\Attendance\Models\AttendanceRecord;
use App\Domain\Financial\Models\Payment;
use App\Domain\Participant\Models\Participant;
use App\Domain\Training\Models\TrainingSession;
use App\Domain\Shared\Traits\UsesBranchScope;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('مكتب الاستقبال')]
class ReceptionistDashboard extends Component
{
    use UsesBranchScope;

    public ?int $branchId = null;
    public string $branchName = '';

    public function mount(): void
    {
        $this->authorize('participants.list');
        $this->branchId = $this->getActiveBranchIdOrFail();
        $this->branchName = \App\Domain\Identity\Models\Branch::find($this->branchId)?->name_ar ?? '';
    }

    public function render()
    {
        $today = now()->toDateString();

        // All queries scoped to this branch
        $stats = [
            'registrations_today' => Participant::where('branch_id', $this->branchId)
                ->whereDate('created_at', $today)->count(),
            'payments_today' => Payment::where('branch_id', $this->branchId)
                ->where('status', 'confirmed')
                ->whereDate('created_at', $today)->sum('amount'),
            'payments_count' => Payment::where('branch_id', $this->branchId)
                ->where('status', 'confirmed')
                ->whereDate('created_at', $today)->count(),
            'sessions_in_progress' => TrainingSession::whereHas('group', fn ($q) => $q->where('branch_id', $this->branchId))
                ->where('session_date', $today)
                ->where('status', 'in_progress')->count(),
            'sessions_today' => TrainingSession::whereHas('group', fn ($q) => $q->where('branch_id', $this->branchId))
                ->where('session_date', $today)->count(),
        ];

        // Attendance summary for today (branch-scoped)
        $todaySessions = TrainingSession::whereHas('group', fn ($q) => $q->where('branch_id', $this->branchId))
            ->where('session_date', $today)->pluck('id');

        $stats['checked_in'] = AttendanceRecord::whereIn('training_session_id', $todaySessions)
            ->whereIn('status', [AttendanceStatus::Present, AttendanceStatus::Late])
            ->count();
        $stats['expected_today'] = AttendanceRecord::whereIn('training_session_id', $todaySessions)
            ->where('status', AttendanceStatus::Expected)
            ->count();

        return view('livewire.receptionist.dashboard', [
            'stats' => $stats,
        ]);
    }
}
