<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';
require_once '../utils/email-templates.php';
require_once '../utils/mailer.php';

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Extract authorization token
$token = getAuthToken();

// Validate token
$user = getUserFromToken($token);
if (!$user) {
    errorResponse('User not authenticated', 401);
}

// Validate required fields
if (!isset($input['to']) || !isset($input['subject'])) {
    errorResponse('To and subject are required', 400);
}

$to = $input['to'];
$subject = $input['subject'];
$message = isset($input['message']) ? $input['message'] : ''; 
$template = isset($input['template']) ? $input['template'] : 'custom';
$data = isset($input['data']) ? $input['data'] : [];

try {
    // 1. Prepare Content based on template
    $emailBody = $message;
    $emailSubject = $subject;
    
    if ($template !== 'custom') {
        $stmt = $pdo->prepare("SELECT * FROM email_templates WHERE template_type = ? AND is_active = TRUE LIMIT 1");
        $stmt->execute([$template]);
        $templateRecord = $stmt->fetch();
        
        if ($templateRecord) {
            // Basic placeholder replacement for existing fields
            $content = $templateRecord['content'];
            foreach ($data as $key => $value) {
                $content = str_replace('{' . $key . '}', $value, $content);
            }
            $emailBody = getBrandedTemplate($content, $subject);
            $emailSubject = $templateRecord['subject'];
            foreach ($data as $key => $value) {
                $emailSubject = str_replace('{' . $key . '}', $value, $emailSubject);
            }
        }
    } else {
        $emailBody = getBrandedTemplate($message, $subject);
    }

    // 2. Use robust mailer
    $result = sendRobustEmail($to, $emailSubject, $emailBody, [
        'from_name' => $input['from_name'] ?? null,
        'from_email' => $input['from_email'] ?? null
    ]);

    if ($result['success']) {
        // Update user progress if sent successfully
        $stmt = $pdo->prepare("UPDATE user_progress SET mails_sent = mails_sent + 1, updated_at = datetime('now') WHERE user_id = ?");
        $stmt->execute([$user['id']]);

        jsonResponse($result, 200);
    } else {
        errorResponse($result['message'], 500);
    }

} catch (Exception $e) {
    errorResponse('Error sending email: ' . $e->getMessage(), 500);
}
?>
