<?php

namespace App\Console\Commands;

use App\Domain\Financial\Models\Payment;
use App\Domain\Shared\Models\Academy;
use App\Domain\Notification\Services\NotificationService;
use App\Domain\Participant\Models\Participant;
use App\Domain\Training\Models\Enrollment;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SendDailySummary extends Command
{
    protected $signature = 'summary:daily';
    protected $description = 'Send daily summary to academy admins';

    public function handle(NotificationService $notificationService): int
    {
        $yesterday = now()->subDay()->toDateString();

        $academies = Academy::where('status', 'active')->get();

        foreach ($academies as $academy) {
            try {
                $payments = Payment::where('academy_id', $academy->id)
                    ->where('status', 'confirmed')
                    ->whereDate('payment_date', $yesterday)
                    ->get();

                $totalCollected = $payments->sum('amount');
                $paymentCount = $payments->count();

                $newEnrollments = Enrollment::where('academy_id', $academy->id)
                    ->whereDate('enrollment_date', $yesterday)
                    ->count();

                $newParticipants = Participant::where('academy_id', $academy->id)
                    ->whereDate('created_at', $yesterday)
                    ->count();

                $methodBreakdown = $payments->groupBy(fn ($p) => $p->method?->value ?? 'other')
                    ->map(fn ($group) => number_format($group->sum('amount') / 100, 2))
                    ->toArray();

                $variables = [
                    'date' => $yesterday,
                    'total_collected' => number_format($totalCollected / 100, 2),
                    'payment_count' => (string) $paymentCount,
                    'new_enrollments' => (string) $newEnrollments,
                    'new_participants' => (string) $newParticipants,
                    'cash_total' => $methodBreakdown['cash'] ?? '0.00',
                    'card_total' => $methodBreakdown['card'] ?? '0.00',
                ];

                $admins = DB::table('users')
                    ->where('academy_id', $academy->id)
                    ->where('status', 'active')
                    ->whereIn('id', function ($q) {
                        $q->select('user_id')->from('role_user')
                            ->whereIn('role_id', function ($rq) {
                                $rq->select('id')->from('roles')
                                    ->where('level', '>=', 80);
                            });
                    })
                    ->get();

                foreach ($admins as $admin) {
                    $notificationService->send(
                        eventType: 'daily_summary',
                        recipientType: 'user',
                        recipientId: $admin->id,
                        academyId: $academy->id,
                        variables: $variables,
                        recipientEmail: $admin->email,
                    );
                }

                $this->info("Sent daily summary for {$academy->name} ({$paymentCount} payments, " . number_format($totalCollected / 100, 2) . " EGP)");
            } catch (\Throwable $e) {
                Log::error("Daily summary failed for academy {$academy->id}: " . $e->getMessage());
                $this->error("Failed for {$academy->name}: " . $e->getMessage());
            }
        }

        return self::SUCCESS;
    }
}
