<?php

namespace App\Livewire\Reports;

use App\Domain\Shared\Services\ReportService;
use App\Domain\Shared\Traits\UsesBranchScope;
use App\Domain\Training\Models\TrainingGroup;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('التقارير')]
class ReportsPage extends Component
{
    use UsesBranchScope;

    #[Url]
    public string $reportType = 'financial';

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

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

    public ?int $groupId = null;

    public function mount(): void
    {
        $this->authorize('reports.view');
        $this->dateFrom = now()->startOfMonth()->format('Y-m-d');
        $this->dateTo = now()->format('Y-m-d');
    }

    public function setReportType(string $type): void
    {
        $this->reportType = $type;
    }

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

        $reportData = match ($this->reportType) {
            'financial' => $reportService->financialSummary($this->dateFrom, $this->dateTo, $branchId),
            'attendance' => $reportService->attendanceReport($this->dateFrom, $this->dateTo, $this->groupId, $branchId),
            'enrollment' => $reportService->enrollmentReport($this->dateFrom, $this->dateTo, $branchId),
            default => [],
        };

        return view('livewire.reports.reports-page', [
            'reportData' => $reportData,
            'groups' => TrainingGroup::orderBy('name_ar')
                ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))->get(),
        ]);
    }
}
