<?php
// send_mail.php - Fully Fixed & Production Ready (2025)

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, User-Agent, X-Requested-With');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once 'Mailer.php';

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

if (!$data || empty($data['to']) || !filter_var($data['to'], FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Valid email address is required']);
    exit;
}

// Safely extract and sanitize data
$to             = filter_var($data['to'], FILTER_SANITIZE_EMAIL);
$subject        = $data['subject'] ?? 'You received a special card!';
$recipientName  = htmlspecialchars($data['recipient_name'] ?? 'there', ENT_QUOTES, 'UTF-8');
$cardMessage    = htmlspecialchars($data['card_message'] ?? 'Wishing you the very best!', ENT_QUOTES, 'UTF-8');
$cardCategory   = htmlspecialchars($data['card_category'] ?? 'Gift', ENT_QUOTES, 'UTF-8');
$bgColor        = $data['background_color'] ?? '#ff6b6b';
$textColor      = $data['text_color'] ?? '#ffffff';
$fontFamily     = $data['font_family'] ?? 'Default';

// Font mapping with Google Fonts
$fonts = [
    'Default'         => ['family' => 'Arial, sans-serif', 'import' => ''],
    'Roboto'          => ['family' => "'Roboto', sans-serif", 'import' => '@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@700&display=swap");'],
    'Pacifico'        => ['family' => "'Pacifico', cursive", 'import' => '@import url("https://fonts.googleapis.com/css2?family=Pacifico&display=swap");'],
    'DancingScript'   => ['family' => "'Dancing Script', cursive", 'import' => '@import url("https://fonts.googleapis.com/css2?family=Dancing+Script:wght@700&display=swap");'],
    'Caveat'          => ['family' => "'Caveat', cursive", 'import' => '@import url("https://fonts.googleapis.com/css2?family=Caveat:wght@700&display=swap");'],
    'IndieFlower'     => ['family' => "'Indie Flower', cursive", 'import' => '@import url("https://fonts.googleapis.com/css2?family=Indie+Flower&display=swap");'],
    'PermanentMarker' => ['family' => "'Permanent Marker', cursive", 'import' => '@import url("https://fonts.googleapis.com/css2?family=Permanent+Marker&display=swap");'],
    'Satisfy'         => ['family' => "'Satisfy', cursive", 'import' => '@import url("https://fonts.googleapis.com/css2?family=Satisfy&display=swap");'],
    'GreatVibes'      => ['family' => "'Great Vibes', cursive", 'import' => '@import url("https://fonts.googleapis.com/css2?family=Great+Vibes&display=swap");'],
];

$font = $fonts[$fontFamily] ?? $fonts['Default'];

// Pre-process message with nl2br BEFORE heredoc
$formattedMessage = nl2br($cardMessage);
$fontImport = $font['import'];
$fontFamily = $font['family'];

// FULL BEAUTIFUL EMAIL TEMPLATE (Server-side rendered - Cloudflare safe!)
$styledMessage = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{$subject}</title>
    {$fontImport}
    <style>
        body { 
            margin: 0; 
            padding: 0; 
            background: #f0f2f5; 
            font-family: 'Segoe UI', Arial, sans-serif; 
        }
        .container { 
            max-width: 600px; 
            margin: 20px auto; 
            background: white; 
            border-radius: 16px; 
            overflow: hidden; 
            box-shadow: 0 10px 40px rgba(0,0,0,0.1); 
        }
        .header { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            padding: 40px 20px; 
            text-align: center; 
            color: white; 
        }
        .header h1 { 
            margin: 0; 
            font-size: 32px; 
            font-weight: 600; 
        }
        .header p { 
            margin: 10px 0 0; 
            font-size: 18px; 
            opacity: 0.9; 
        }
        .card-wrapper { 
            padding: 40px 20px; 
            text-align: center; 
        }
        .card {
            background: {$bgColor};
            color: {$textColor};
            padding: 80px 40px;
            border-radius: 32px;
            margin: 0 auto;
            max-width: 90%;
            min-height: 420px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 25px 50px rgba(0,0,0,0.2);
        }
        .card-message {
            font-family: {$fontFamily};
            font-size: 38px;
            line-height: 1.4;
            font-weight: bold;
            text-align: center;
            text-shadow: 0 4px 8px rgba(0,0,0,0.3);
        }
        .footer { 
            padding: 30px; 
            text-align: center; 
            background: #f8f9fa; 
            color: #666; 
            font-size: 15px; 
        }
        @media (max-width: 480px) {
            .card { 
                padding: 60px 20px !important; 
            }
            .card-message { 
                font-size: 28px !important; 
            }
            .header h1 { 
                font-size: 26px !important; 
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>{$cardCategory} Card</h1>
            <p>Hello {$recipientName}!</p>
        </div>
        
        <div class="card-wrapper">
            <div class="card">
                <div class="card-message">
                    {$formattedMessage}
                </div>
            </div>
        </div>
        
        <div class="footer">
            <p><strong>You've received a {$cardCategory} card!</strong></p>
            <p>Sent with love using <strong>Landr</strong></p>
        </div>
    </div>
</body>
</html>
HTML;

try {
    $mailer = new Mailer();
    $result = $mailer->send($to, $subject, $styledMessage);
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Card sent successfully!'
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => 'Failed to send email: ' . $e->getMessage()
    ]);
}