<?php
// Enable CORS and set response headers for JSON API
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Allow: POST, OPTIONS');
header('Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Origin');

// Include Mailer class
require_once 'Mailer.php';

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

// Validate required fields
if (!isset($data['to'], $data['subject'], $data['message']) || !filter_var($data['to'], FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid or missing parameters']);
    exit;
}

// Sanitize user input to prevent XSS
$to = filter_var($data['to'], FILTER_SANITIZE_EMAIL);
$subject = htmlspecialchars($data['subject'], ENT_QUOTES, 'UTF-8');
$message = htmlspecialchars($data['message'], ENT_QUOTES, 'UTF-8');

// Company configuration
$companyConfig = [
    'name' => 'Schoolmata App',
    'supportEmail' => 'support@schoolmata.com.ng',
    'website' => 'https://schoolmata.com.ng',
    'address' => 'Port Harcourt, Rivers State, Nigeria',
    'social' => [
        'facebook' => 'https://facebook.com/schoolmata',
        'twitter' => 'https://x.com/schoolmata',
        'instagram' => 'https://instagram.com/schoolmata',
    ],
    'logoUrl' => 'https://via.placeholder.com/150x50?text=YourCompany+Logo',
];

// Modern HTML email template
$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>
</head>
<body style="margin: 0; padding: 0; font-family: 'Segoe UI', 'Helvetica Neue', Arial, sans-serif; background-color: #f4f4f7; line-height: 1.6;">
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
        <!-- Header -->
        <tr>
            <td style="background-color: #007bff; padding: 20px; text-align: center; border-top-left-radius: 8px; border-top-right-radius: 8px;">
                <img src="{$companyConfig['logoUrl']}" alt="{$companyConfig['name']} Logo" style="max-width: 150px; height: auto; display: block; margin: 0 auto;">
                <h2 style="color: #ffffff; font-size: 24px; margin: 10px 0; font-weight: 600;">{$companyConfig['name']}</h2>
            </td>
        </tr>
        <!-- Content -->
        <tr>
            <td style="padding: 30px; font-size: 16px; color: #333333;">
                <p style="margin: 0 0 20px;">Hello,</p>
                <div style="margin-bottom: 20px;">{$message}</div>
                <p style="margin: 0;">Best regards,<br>The {$companyConfig['name']} Team</p>
            </td>
        </tr>
        <!-- Footer -->
        <tr>
            <td style="background-color: #f8f9fa; padding: 20px; text-align: center; font-size: 14px; color: #666666; border-bottom-left-radius: 8px; border-bottom-right-radius: 8px;">
                <p style="margin: 0 0 10px;">Need help? Contact us at <a href="mailto:{$companyConfig['supportEmail']}" style="color: #007bff; text-decoration: none;">{$companyConfig['supportEmail']}</a></p>
                <p style="margin: 0 0 10px;">Visit our website: <a href="{$companyConfig['website']}" style="color: #007bff; text-decoration: none;">{$companyConfig['website']}</a></p>
                <table role="presentation" cellpadding="0" cellspacing="0" style="margin: 10px auto;">
                    <tr>
                        <td style="padding: 0 8px;">
                            <a href="{$companyConfig['social']['facebook']}" style="color: #007bff; text-decoration: none;">Facebook</a>
                        </td>
                        <td style="padding: 0 8px;">
                            <a href="{$companyConfig['social']['twitter']}" style="color: #007bff; text-decoration: none;">Twitter/X</a>
                        </td>
                        <td style="padding: 0 8px;">
                            <a href="{$companyConfig['social']['instagram']}" style="color: #007bff; text-decoration: none;">Instagram</a>
                        </td>
                    </tr>
                </table>
                <p style="margin: 10px 0 0;">{$companyConfig['address']}</p>
            </td>
        </tr>
    </table>
    <!-- Responsive Design -->
    <style>
        @media only screen and (max-width: 600px) {
            table { width: 100% !important; margin: 10px auto !important; }
            td { padding: 15px !important; }
            h2 { font-size: 20px !important; }
            img[src*="logo"] { max-width: 120px !important; }
            .social-icons a { display: inline-block; margin: 5px !important; }
        }
    </style>
</body>
</html>
HTML;

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