<?php

namespace App\Services;

use App\Models\EmailTemplate;
use App\Models\EmailLog;
use App\Mail\DynamicMail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class EmailService
{
    public static function send($slug, $to, $data = [])
    {
        try {
            $template = EmailTemplate::where('slug', $slug)->first();

            if (!$template) {
                Log::warning("Email template not found: {$slug}");
                return false;
            }

            if (!$template->is_active) {
                Log::info("Email template disabled: {$slug}");
                return false;
            }

            // Replace variables
            $subject = $template->subject;
            $body = $template->body;

            foreach ($data as $key => $value) {
                $subject = str_replace('{{' . $key . '}}', $value, $subject);
                $body = str_replace('{{' . $key . '}}', $value, $body);
            }

            // Send Email
            Mail::to($to)->send(new DynamicMail($subject, $body));

            // Log Success
            EmailLog::create([
                'recipient' => $to,
                'subject' => $subject,
                'template_slug' => $slug,
                'status' => 'sent',
                'sent_at' => now(),
            ]);

            return true;

        } catch (\Exception $e) {
            Log::error("Failed to send email ({$slug}): " . $e->getMessage());
            
            // Log Failure
            EmailLog::create([
                'recipient' => $to,
                'subject' => $template->subject ?? 'Unknown',
                'template_slug' => $slug,
                'status' => 'failed',
                'error_message' => $e->getMessage(),
                'sent_at' => now(),
            ]);

            return false;
        }
    }
}
