<?php

namespace App\Livewire\Dashboard;

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

class EnrollmentTrends extends Component
{
    public string $period = '30';

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

        $dailyEnrollments = Enrollment::where('created_at', '>=', $startDate)
            ->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)
            ->count();

        $active = Enrollment::where('status', 'active')->count();

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