<?php

namespace App\Livewire\Dashboard;

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

class RenewalsDueWidget extends Component
{
    public function render()
    {
        $today = now()->toDateString();
        $upcoming3Days = now()->addDays(3)->toDateString();

        $dueToday = Enrollment::where('status', EnrollmentStatus::Active)
            ->where('next_billing_date', $today)
            ->whereHas('program', fn ($q) => $q->whereIn('renewal_policy', [
                RenewalPolicy::AutoRenew->value,
                RenewalPolicy::ManualRenew->value,
            ]))
            ->count();

        $dueThisWeek = Enrollment::where('status', EnrollmentStatus::Active)
            ->whereBetween('next_billing_date', [$today, $upcoming3Days])
            ->whereHas('program', fn ($q) => $q->whereIn('renewal_policy', [
                RenewalPolicy::AutoRenew->value,
                RenewalPolicy::ManualRenew->value,
            ]))
            ->count();

        $overdue = Enrollment::where('status', EnrollmentStatus::Active)
            ->where('next_billing_date', '<', $today)
            ->whereHas('program', fn ($q) => $q->whereIn('renewal_policy', [
                RenewalPolicy::AutoRenew->value,
                RenewalPolicy::ManualRenew->value,
            ]))
            ->count();

        $byBranch = Enrollment::where('enrollments.status', EnrollmentStatus::Active)
            ->where('next_billing_date', '<=', $upcoming3Days)
            ->whereHas('program', fn ($q) => $q->whereIn('renewal_policy', [
                RenewalPolicy::AutoRenew->value,
                RenewalPolicy::ManualRenew->value,
            ]))
            ->join('training_groups', 'enrollments.training_group_id', '=', 'training_groups.id')
            ->join('branches', 'training_groups.branch_id', '=', 'branches.id')
            ->select('branches.name_ar as branch_name', DB::raw('COUNT(*) as count'))
            ->groupBy('branches.name_ar')
            ->orderByDesc('count')
            ->limit(5)
            ->get();

        return view('livewire.dashboard.renewals-due-widget', [
            'dueToday' => $dueToday,
            'dueThisWeek' => $dueThisWeek,
            'overdue' => $overdue,
            'byBranch' => $byBranch,
        ]);
    }
}
