<?php

namespace App\Services\Attendance;

use App\Models\AttendanceTracking;
use App\Services\EmailService;
use App\Services\Notifications\UserNotificationDispatchService;
use Illuminate\Support\Facades\Log;

class AttendanceConsequenceService
{
    public function __construct(
        private EmailService $emailService,
        private UserNotificationDispatchService $notifier
    ) {
    }

    public function sendFollowUp(array $payload): array
    {
        return $this->send(
            'follow_up',
            $payload,
            'Attendance Follow Up',
            'emails/follow_up',
            'info'
        );
    }

    public function sendFinalWarning(array $payload): array
    {
        return $this->send(
            'final_warning',
            $payload,
            'Final Warning: Attendance Issue',
            'emails/final_warning',
            'warning'
        );
    }

    public function sendDismissal(array $payload): array
    {
        return $this->send(
            'dismissal',
            $payload,
            'Notice of Dismissal',
            'emails/dismissal',
            'error'
        );
    }

    private function send(
        string $type,
        array $payload,
        string $defaultSubject,
        string $viewName,
        string $logLevel
    ): array {
        $studentName = trim((string) ($payload['student']['firstname'] ?? '') . ' ' . (string) ($payload['student']['lastname'] ?? ''));
        $parentEmail = (string) ($payload['parent']['email'] ?? '');
        $parentName = (string) ($payload['parent']['name'] ?? '');
        $teacherName = trim((string) ($payload['teacher']['firstname'] ?? '') . ' ' . (string) ($payload['teacher']['lastname'] ?? ''));
        $className = (string) ($payload['class']['class_section_name'] ?? '');
        $semester = (string) ($payload['semester'] ?? '');
        $schoolYear = (string) ($payload['school_year'] ?? '');
        $dateYmd = (string) ($payload['date'] ?? '');
        $dateFmt = $dateYmd !== '' ? date('m-d-Y', strtotime($dateYmd)) : '';
        $sentAt = $payload['now'] ?? utc_now();

        if ($parentEmail === '') {
            Log::warning("Attendance {$type}: missing parent email", [
                'student_id' => $payload['student_id'] ?? null,
            ]);
            return ['ok' => false, 'message' => 'Missing parent email.'];
        }

        $subject = (string) ($payload['subject'] ?? $this->buildSubject($defaultSubject, $studentName, $dateFmt));

        $emailData = [
            'title' => $subject,
            'student_name' => $studentName,
            'parent_name' => $parentName,
            'teacher_name' => $teacherName,
            'class_section_name' => $className,
            'semester' => $semester,
            'school_year' => $schoolYear,
            'date_fmt' => $dateFmt,
            'sent_at' => $sentAt,
        ];

        $html = trim((string) ($payload['html'] ?? ''));
        if ($html === '') {
            try {
                $html = view($viewName, $emailData, ['saveData' => true]);
            } catch (\Throwable $e) {
                $html = '<p>' . e($subject) . '</p>';
            }
        }

        $ok = false;
        try {
            $ok = $this->emailService->send($parentEmail, $subject, $html, 'attendance');
        } catch (\Throwable $e) {
            Log::error('Attendance email send failed: ' . $e->getMessage());
        }

        $summary = $this->buildInAppSummary($type, $studentName, $dateFmt);
        $parentUserId = (int) ($payload['parent']['user_id'] ?? 0);
        if ($parentUserId > 0) {
            $this->notifier->notifyUser(
                $parentUserId,
                $subject,
                $summary,
                ['in_app'],
                'attendance',
                'parent'
            );
        }

        if (!empty($payload['tracking_id'])) {
            AttendanceTracking::markAsNotified((int) $payload['tracking_id']);
        }

        Log::log($logLevel, "Attendance {$type} email " . ($ok ? 'sent' : 'failed'), [
            'student_id' => $payload['student_id'] ?? null,
            'recipient' => $parentEmail,
        ]);

        return ['ok' => $ok];
    }

    private function buildSubject(string $base, string $studentName, string $dateFmt): string
    {
        $name = $studentName !== '' ? " — {$studentName}" : '';
        $date = $dateFmt !== '' ? " ({$dateFmt})" : '';
        return $base . $name . $date;
    }

    private function buildInAppSummary(string $type, string $studentName, string $dateFmt): string
    {
        $who = $studentName !== '' ? $studentName : 'a student';
        $when = $dateFmt !== '' ? " on {$dateFmt}" : '';

        return match ($type) {
            'dismissal' => "Dismissal notice sent for {$who}{$when}.",
            'final_warning' => "Final warning sent for {$who}{$when}.",
            default => "Follow-up notice sent for {$who}{$when}.",
        };
    }
}
