<?php

namespace App\Livewire\Dashboard;

use App\Domain\HR\Models\Employee;
use App\Domain\HR\Models\Trainer;
use App\Domain\HR\Models\TrainerCompensation;
use App\Domain\Shared\Traits\UsesBranchScope;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class TrainerDuesWidget extends Component
{
    use UsesBranchScope;

    public function render()
    {
        $totalDues = 0;
        $trainerTotals = [];
        $topTrainers = collect();

        try {
            $startOfMonth = now()->startOfMonth()->toDateString();
            $endOfMonth = now()->endOfMonth()->toDateString();

            // No branch clause on either query. TrainerCompensation carries its
            // own branch_id and is strict-scoped, so BranchScope files each
            // record where it was earned. Reaching through trainer.employee
            // with forBranch() — as this did — lifted the scope and then
            // demanded an exact branch match on a SHARED table, so every
            // academy-wide (null-branch) coach's dues were counted in no branch
            // at all and the widget under-reported the month.
            $compensations = TrainerCompensation::whereIn('status', ['pending', 'approved'])
                ->forPeriod($startOfMonth, $endOfMonth)
                ->select('trainer_id', DB::raw('SUM(amount) as total_amount'), DB::raw('COUNT(*) as records_count'))
                ->groupBy('trainer_id')
                ->get()
                ->keyBy('trainer_id');

            // Trainer is shared-scoped: this branch's coaches plus the
            // academy-wide ones, which is what the scope already returns.
            $salaryTrainers = Trainer::whereIn('compensation_model', ['salary', 'hybrid'])
                ->where('status', 'active')
                ->with('employee:id,salary_amount')
                ->get();

            foreach ($compensations as $trainerId => $comp) {
                $trainerTotals[$trainerId] = ($trainerTotals[$trainerId] ?? 0) + $comp->total_amount;
            }

            foreach ($salaryTrainers as $trainer) {
                $salary = $trainer->employee?->salary_amount ?? 0;
                $trainerTotals[$trainer->id] = ($trainerTotals[$trainer->id] ?? 0) + $salary;
            }

            $totalDues = array_sum($trainerTotals);

            if ($trainerTotals) {
                $topTrainers = Trainer::whereIn('id', array_keys($trainerTotals))
                    ->with(['employee.person:id,name_ar,name', 'person:id,name_ar,name'])
                    ->get()
                    ->map(fn ($t) => [
                        'name' => $t->employee?->person?->name_ar ?? $t->person?->name_ar ?? $t->trainer_number,
                        'amount' => $trainerTotals[$t->id],
                    ])
                    ->sortByDesc('amount')
                    ->take(5)
                    ->values();
            }
        } catch (\Illuminate\Database\QueryException $e) {
            // Table may not exist yet if migrations haven't run
        }

        return view('livewire.dashboard.trainer-dues-widget', [
            'totalDues' => $totalDues,
            'trainerCount' => count($trainerTotals),
            'topTrainers' => $topTrainers,
            'monthName' => now()->translatedFormat('F Y'),
        ]);
    }
}
