<?php
declare(strict_types=1);

namespace App\Services;

use App\Models\ConferenceEmailTemplateModel;
use App\Models\EmailTemplate;
use App\Models\NotificationModel;

final class ConferenceNotificationService
{
    public static function notifyAndEmail(
        array $user,
        int $conferenceId,
        string $eventKey,
        array $placeholders,
        string $type,
        ?string $relatedTable = null,
        ?int $relatedId = null
    ): void {
        $templateModel = new ConferenceEmailTemplateModel();
        $template = $templateModel->findByConferenceAndEvent($conferenceId, $eventKey);

        if (!$template) {
            $fallback = new EmailTemplate();
            $template = $fallback->findByKey($eventKey);
        }

        $lang = (string) ($user['preferred_lang'] ?? 'en');

        if ($template) {
            $subject = $lang === 'ar' ? (string) $template['subject_ar'] : (string) $template['subject_en'];
            $body = $lang === 'ar' ? (string) $template['body_ar'] : (string) $template['body_en'];
        } else {
            $subject = $eventKey;
            $body = $eventKey;
        }

        $subject = self::render($subject, $placeholders);
        $body = self::render($body, $placeholders);

        $model = new NotificationModel();
        $model->create([
            'user_id' => (int) $user['id'],
            'type' => $type,
            'title' => $subject,
            'message' => $body,
            'related_table' => $relatedTable,
            'related_id' => $relatedId,
            'is_read' => 0,
        ]);

        if (!empty($user['email'])) {
            Mailer::send((string) $user['email'], $subject, strip_tags($body));
        }
    }

    private static function render(string $text, array $vars): string
    {
        foreach ($vars as $key => $value) {
            $text = str_replace('{{' . $key . '}}', (string) $value, $text);
        }
        return $text;
    }
}
