<?php

namespace App\Livewire\Dashboard;

use App\Domain\Shared\Traits\UsesBranchScope;
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
{
    use UsesBranchScope;

    public function render()
    {
        $branchId = $this->getActiveBranchId();
        $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,
            ]))
            ->when($branchId, fn ($q) => $q->whereHas('group', fn ($g) => $g->where('branch_id', $branchId)))
            ->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,
            ]))
            ->when($branchId, fn ($q) => $q->whereHas('group', fn ($g) => $g->where('branch_id', $branchId)))
            ->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,
            ]))
            ->when($branchId, fn ($q) => $q->whereHas('group', fn ($g) => $g->where('branch_id', $branchId)))
            ->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,
            ]))
            ->when($branchId, fn ($q) => $q->where('training_groups.branch_id', $branchId))
            ->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,
        ]);
    }
}
