<?php
namespace App\Core;

class MailEngine
{
    public static function send($to, $subject, $message)
    {
        $headers = "From: no-reply@conference.com\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

        mail($to, $subject, $message, $headers);
    }

    public static function sendTemplate($template_key, $to, $variables = [])
{
    $db = \App\Core\Database::getInstance();
    $org_id = $_SESSION['org_id'] ?? null;
    $lang = $_SESSION['preferred_lang'] ?? 'en';

    $stmt = $db->prepare("
        SELECT *
        FROM email_templates
        WHERE template_key = ?
        AND (org_id = ? OR org_id IS NULL)
        AND is_active = 1
        LIMIT 1
    ");
    $stmt->execute([$template_key, $org_id]);
    $tpl = $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$tpl) return false;

    $subject = $lang == 'ar' ? $tpl['subject_ar'] : $tpl['subject_en'];
    $body = $lang == 'ar' ? $tpl['body_html_ar'] : $tpl['body_html_en'];

    foreach ($variables as $key => $value) {
        $subject = str_replace("{{".$key."}}", $value, $subject);
        $body = str_replace("{{".$key."}}", $value, $body);
    }

    mail($to, $subject, $body, "Content-Type: text/html; charset=UTF-8");

    return true;
}



public static function notifyReviewerAssigned($email, $title)
    {
        self::send(
            $email,
            "New Review Assignment",
            "<p>You have been assigned a paper:</p><strong>{$title}</strong>"
        );
    }

    public static function notifyAuthorDecision($email, $decision)
    {
        self::send(
            $email,
            "Submission Decision",
            "<p>Your submission decision: <strong>{$decision}</strong></p>"
        );
    }
}
