<?php

namespace App\Services\Frontend;

use App\Models\ContactUs;
use App\Models\Configuration;
use App\Services\Email\EmailDispatchService;
use App\Services\System\GlobalConfigService;
use Illuminate\Support\Facades\Log;

class ContactSubmissionService
{
    public function __construct(
        private EmailDispatchService $emailService,
        private GlobalConfigService $configService
    ) {
    }

    public function submit(array $payload): array
    {
        $email = strtolower((string) $payload['email']);
        $message = (string) $payload['message'];
        $subject = (string) ($payload['subject'] ?? 'Contact Us Form Submission');

        $schoolYear = $payload['school_year'] ?? $this->configService->getSchoolYear() ?? '';
        $semester = $payload['semester'] ?? $this->configService->getSemester() ?? '';

        $record = null;
        try {
            $record = ContactUs::query()->create([
                'sender_id' => (int) ($payload['sender_id'] ?? 0),
                'reciever_id' => (int) ($payload['receiver_id'] ?? 0),
                'subject' => $subject,
                'message' => $message,
                'semester' => $semester ?: 'Fall',
                'school_year' => $schoolYear ?: '2025-2026',
            ]);
        } catch (\Throwable $e) {
            Log::error('Contact submission save failed: ' . $e->getMessage());
        }

        $recipient = Configuration::getConfig('administrator_email')
            ?: (string) config('mail.from.address', '')
            ?: 'alrahma.isgl@gmail.com';

        $htmlMessage = nl2br('You have received a new message from ' . $email . ":\n\n" . $message);

        $emailSent = false;
        if (!app()->runningUnitTests()) {
            $emailSent = $this->emailService->send($recipient, $subject, $htmlMessage, null, $email, $email);
            if (!$emailSent) {
                Log::error('Contact submission email failed for ' . $email);
            }
        }

        return [
            'record' => $record,
            'email_sent' => $emailSent,
            'recipient' => $recipient,
        ];
    }
}
