<?php

namespace App\Console\Commands;

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;

class SendParentWeeklyReport extends Command
{
    protected $signature = 'reports:parent-weekly';
    protected $description = 'Send weekly attendance/progress reports to guardians via SMS';

    public function handle(NotificationService $notificationService): int
    {
        $participants = Participant::where('status', 'active')
            ->whereHas('guardians')
            ->with(['guardians', 'enrollments' => fn ($q) => $q->where('status', 'active')])
            ->get();

        $sent = 0;
        $weekStart = now()->startOfWeek()->toDateString();
        $weekEnd = now()->endOfWeek()->toDateString();

        foreach ($participants as $participant) {
            $attendance = DB::table('attendance_records')
                ->where('subject_type', 'participant')
                ->where('subject_id', $participant->id)
                ->whereBetween('date', [$weekStart, $weekEnd])
                ->selectRaw("
                    COUNT(*) as total,
                    SUM(CASE WHEN status IN ('present','late','partial') THEN 1 ELSE 0 END) as attended,
                    SUM(CASE WHEN status = 'absent' THEN 1 ELSE 0 END) as absent
                ")
                ->first();

            if (!$attendance || $attendance->total == 0) {
                continue;
            }

            $rate = round(($attendance->attended / $attendance->total) * 100);

            foreach ($participant->guardians as $guardian) {
                $phone = $guardian->phone ?? $guardian->person?->phone ?? null;
                if (!$phone) continue;

                $message = "تقرير أسبوعي - {$participant->full_name}: "
                    . "حضر {$attendance->attended}/{$attendance->total} حصة "
                    . "({$rate}%) - غياب: {$attendance->absent}";

                try {
                    $notificationService->send(
                        channel: 'sms',
                        recipient: $phone,
                        subject: 'تقرير أسبوعي',
                        body: $message,
                        eventType: 'parent.weekly_report',
                    );
                    $sent++;
                } catch (\Throwable $e) {
                    $this->warn("Failed for {$participant->full_name}: {$e->getMessage()}");
                }
            }
        }

        $this->info("Sent {$sent} weekly reports to guardians.");
        return self::SUCCESS;
    }
}
