<?php

namespace App\Services\AttendanceTracking;

use App\Services\EmailService;
use Illuminate\Support\Facades\Log;

class DefaultAttendanceMailerService implements AttendanceMailerService
{
    public function __construct(
        protected EmailService $emailService,
        protected AttendanceEmailComposerService $emailComposerService
    ) {
    }

    public function send(string $to, string $subject, string $html): bool
    {
        return $this->emailService->send($to, $subject, $html, 'attendance');
    }

    public function queueAttendanceEvent(array $payload): void
    {
        $to = trim((string) data_get($payload, 'parent.email', ''));
        if ($to === '') {
            throw new \InvalidArgumentException('No parent email found for attendance notification.');
        }

        $student = (array) ($payload['student'] ?? []);
        $studentName = trim((string) ($student['firstname'] ?? '') . ' ' . (string) ($student['lastname'] ?? ''));
        $subjectType = (string) ($payload['subject'] ?? 'Attendance');
        $date = substr((string) ($payload['date'] ?? now()->toDateString()), 0, 10);

        $subject = "Attendance Notice: {$subjectType}";
        $body = '<p>Dear ' . e((string) data_get($payload, 'parent.name', 'Parent/Guardian')) . ',</p>'
            . '<p>This is an attendance notification for your student.</p>'
            . '<ul>'
            . '<li><strong>Student:</strong> ' . e($studentName !== '' ? $studentName : 'Student') . '</li>'
            . '<li><strong>Date:</strong> ' . e($date) . '</li>'
            . '<li><strong>Attendance:</strong> ' . e($subjectType) . '</li>'
            . '</ul>'
            . '<p>If you have any questions, please contact the school office.</p>';

        $html = $this->emailComposerService->renderWithEmailLayout($subject, $body);

        if (!$this->send($to, $subject, $html)) {
            Log::error('Attendance notification email failed for ' . $to);
            throw new \RuntimeException('Failed to send attendance notification email.');
        }
    }
}
