<?php

namespace App\Livewire\Dashboard;

use App\Domain\Shared\Traits\UsesBranchScope;
use App\Domain\Training\Models\Enrollment;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class EnrollmentTrends extends Component
{
    use UsesBranchScope;

    public string $period = '30';

    public function render()
    {
        $branchId = $this->getActiveBranchId();
        $days = (int) $this->period;
        $startDate = now()->subDays($days)->toDateString();

        $dailyEnrollments = Enrollment::where('created_at', '>=', $startDate)
            ->when($branchId, fn ($q) => $q->whereHas('group', fn ($g) => $g->where('branch_id', $branchId)))
            ->select(DB::raw('DATE(created_at) as date'), DB::raw('COUNT(*) as count'))
            ->groupBy('date')
            ->orderBy('date')
            ->pluck('count', 'date')
            ->toArray();

        $totalNew = array_sum($dailyEnrollments);
        $cancelled = Enrollment::where('status', 'cancelled')
            ->where('updated_at', '>=', $startDate)
            ->when($branchId, fn ($q) => $q->whereHas('group', fn ($g) => $g->where('branch_id', $branchId)))
            ->count();

        $active = Enrollment::where('status', 'active')
            ->when($branchId, fn ($q) => $q->whereHas('group', fn ($g) => $g->where('branch_id', $branchId)))
            ->count();

        return view('livewire.dashboard.enrollment-trends', [
            'dailyEnrollments' => $dailyEnrollments,
            'totalNew' => $totalNew,
            'cancelled' => $cancelled,
            'active' => $active,
        ]);
    }
}
