<?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 = '';

    /**
     * Not #[Locked]: the view binds it to a <select>, so it has to be settable.
     * It is re-checked against the branch-scoped group list in
     * resolveGroupId() instead — at the point the report query is built, which
     * is the only place the check counts.
     */
    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 updatedGroupId(): void
    {
        // Drop a value that does not name a group in this branch, so the
        // <select> shows what the report is actually reporting on.
        $this->groupId = $this->resolveGroupId();
    }

    /**
     * The selected group id, or null if it does not resolve inside this branch.
     *
     * TrainingGroup carries BranchScope, so this exists() check answers "is
     * this one of my groups?" — an id belonging to another branch fails it, and
     * the report falls back to every group in this branch rather than reporting
     * on a group the user may not see.
     */
    private function resolveGroupId(): ?int
    {
        if (! $this->groupId) {
            return null;
        }

        return TrainingGroup::whereKey($this->groupId)->exists() ? $this->groupId : null;
    }

    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->resolveGroupId(), $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(),
        ]);
    }
}
