const express = require('express');
const nodemailer = require('nodemailer');
const app = express();

// cPanel Port
const PORT = process.env.PORT || 3000;

// Middleware - JSON කියවීම
app.use(express.json());

// --- MANUAL CORS SETUP ---
const allowedOrigins = [
    'https://tavyo.lk',
    'https://www.tavyo.lk',
    'http://127.0.0.1:5500',
    'https://kcch.lk', // Added for local testing (e.g. Live Server), you can remove this later
    // Add your other verified URLs here
];

app.use((req, res, next) => {
    const origin = req.headers.origin;
    
    // Block the request if it's from a browser and the origin is not allowed
    if (origin && !allowedOrigins.includes(origin)) {
        return res.status(403).json({ status: "error", message: "Forbidden: Origin not allowed" });
    }

    if (origin) {
        res.header("Access-Control-Allow-Origin", origin);
    }
    
    // GET, POST සහ OPTIONS ඉල්ලීම් වලට ඉඩ දෙයි
    res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    
    // බ්‍රව්සරයට යැවිය හැකි Headers වර්ග (Content-Type සහ api_key)
    res.header("Access-Control-Allow-Headers", "Content-Type, api_key");

    // Preflight (OPTIONS) ඉල්ලීමක් ආ විට වහාම 200 OK යවන්න
    if (req.method === 'OPTIONS') {
        return res.sendStatus(200);
    }
    
    next();
});
// ----------------------------------------------

const SECRET_API_KEY = "TAVYO_SECURE_KEY_2024";

const transporter = nodemailer.createTransport({
    host: 'mail.tavyo.lk',
    port: 465,
    secure: true, 
    auth: {
        user: 'noreply@tavyo.lk',
        pass: 'CoCgD$aqy3}{s9Z$'
    }
});

app.post('/send-email', async (req, res) => {
    // API Key එක Body එකේ හෝ Header එකේ තිබේදැයි බලයි (වඩාත් පහසුයි)
    const apiKey = req.body.api_key || req.headers['api_key'];
    const { to, subject, html_body } = req.body;

    // 1. ආරක්ෂක පරීක්ෂාව
    if (!apiKey || apiKey !== SECRET_API_KEY) {
        return res.status(403).json({ status: "error", message: "Invalid API Key" });
    }

    // 2. දත්ත පරීක්ෂාව
    if (!to || !subject || !html_body) {
        return res.status(400).json({ status: "error", message: "Missing required fields" });
    }

    // 3. ඊමේල් යැවීම
    try {
        const info = await transporter.sendMail({
            from: '"Tavyo Notifications" <noreply@tavyo.lk>',
            to: to,
            subject: subject,
            html: html_body
        });

        console.log("Email sent: %s", info.messageId);
        res.status(200).json({ status: "success", message: "Email sent successfully" });

    } catch (error) {
        console.error("Error sending email:", error);
        res.status(500).json({ status: "error", message: "Failed to send email", error: error.message });
    }
});

app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});