<?php
require_once 'mailer.php';

$templates = @json_decode(file_get_contents('email-templates.json'), true);

$fromEmail = isset($templates['from_email']) ? $templates['from_email'] : 'no-reply@yourdomain.com';
$fromName = isset($templates['from_name']) ? $templates['from_name'] : 'Your Company Name';

function sendEmail($to, $subject, $message, $tags = []) {
    return sendMail($to, $subject, $message, $tags);
}

// ✅ Welcome Email
function sendWelcomeEmail($userEmail, $userName) {
    global $templates;

    $subject = $templates['welcome']['subject'] ?? "Welcome to Our System!";
    $body    = $templates['welcome']['body'] ?? "Hi {{first_name}}, welcome aboard!";

    return sendEmail($userEmail, $subject, $body, [
        'first_name' => $userName
    ]);
}

// ✅ Referral Notification Email
function sendReferralEmail($referrerEmail, $referrerName, $newUser) {
    global $templates;

    $subject = $templates['referral']['subject'] ?? "You Have a New Signup!";
    $body    = $templates['referral']['body'] ?? "Hi {{sponsor_name}}, {{new_user}} just signed up under your link.";

    return sendEmail($referrerEmail, $subject, $body, [
        'sponsor_name' => $referrerName,
        'new_user'     => $newUser
    ]);
}

// ✅ Lead Notification Email
function sendLeadNotificationEmail($referrerEmail, $referrerName, $leadName) {
    global $templates;

    $subject = $templates['lead']['subject'] ?? "You Have a New Lead!";
    $body    = $templates['lead']['body'] ?? "Hi {{sponsor_name}}, {{lead_name}} just opted in.";

    return sendEmail($referrerEmail, $subject, $body, [
        'sponsor_name' => $referrerName,
        'lead_name'    => $leadName
    ]);
}

// ✅ Password Reset Email
function sendPasswordResetEmail($to, $firstName, $resetLink) {
    global $templates;

    $subject = $templates['reset']['subject'] ?? "Reset Your Password";
    $body    = $templates['reset']['body'] ?? "Hi {{first_name}}, click here to reset: {{reset_link}}";

    return sendEmail($to, $subject, $body, [
        'first_name' => $firstName,
        'reset_link' => $resetLink
    ]);
}
?>
