<?php

function get_email_template($templateKey)
{
    global $pdo;

    $stmt = $pdo->prepare("
        SELECT *
        FROM email_templates
        WHERE template_key = ?
          AND status = 'active'
        LIMIT 1
    ");
    $stmt->execute([$templateKey]);

    return $stmt->fetch();
}

function replace_email_variables($content, $variables = [])
{
    foreach ($variables as $key => $value) {
        $content = str_replace('{{' . $key . '}}', (string) $value, $content);
    }

    return $content;
}

function log_email($emailTo, $subject, $customerId = null, $orderId = null, $status = 'pending', $errorMessage = null)
{
    global $pdo;

    $stmt = $pdo->prepare("
        INSERT INTO email_logs (
            customer_id,
            order_id,
            email_to,
            subject,
            status,
            error_message,
            sent_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->execute([
        $customerId,
        $orderId,
        $emailTo,
        $subject,
        $status,
        $errorMessage,
        $status === 'sent' ? date('Y-m-d H:i:s') : null
    ]);

    return (int) $pdo->lastInsertId();
}

function queue_template_email($templateKey, $emailTo, $variables = [], $customerId = null, $orderId = null)
{
    $template = get_email_template($templateKey);

    if (!$template) {
        return log_email(
            $emailTo,
            'Missing email template: ' . $templateKey,
            $customerId,
            $orderId,
            'failed',
            'Email template not found or inactive.'
        );
    }

    $subject = replace_email_variables($template['subject'], $variables);

    return log_email(
        $emailTo,
        $subject,
        $customerId,
        $orderId,
        'pending',
        'Email queued only. SMTP not connected yet.'
    );
}