<?php
// includes/email_helper.php - Email Sending Helper

function sendEmail($to, $subject, $message) {
    global $pdo;
    $admin_email = 'admin@onesbd.com';
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM site_settings WHERE setting_key = 'admin_email'");
        $stmt->execute();
        $result = $stmt->fetch();
        if($result) $admin_email = $result['setting_value'];
    } catch(PDOException $e) {}
    
    $headers = "From: ONESBD LMS <{$admin_email}>\r\n";
    $headers .= "Reply-To: {$admin_email}\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    
    $html = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;padding:20px">';
    $html .= '<div style="background:#6C5CE7;color:white;padding:20px;border-radius:10px 10px 0 0;text-align:center"><h2>ONESBD LMS</h2></div>';
    $html .= '<div style="background:#f8f9fa;padding:20px;border-radius:0 0 10px 10px">';
    $html .= $message;
    $html .= '</div></body></html>';
    
    $sent = @mail($to, $subject, $html, $headers);
    
    // Log email
    if(isset($pdo)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO email_logs (email, subject, message, type, status) VALUES (?, ?, ?, 'notification', ?)");
            $stmt->execute([$to, $subject, $message, $sent ? 'sent' : 'failed']);
        } catch(PDOException $e) {}
    }
    
    return $sent;
}

function sendApprovalEmail($user_email, $user_name, $course_name, $enrollment_id) {
    $subject = "✅ এনরোলমেন্ট অনুমোদিত - ONESBD LMS";
    $message = "<h3>অভিনন্দন {$user_name}!</h3>";
    $message .= "<p>আপনার এনরোলমেন্ট অনুমোদিত হয়েছে।</p>";
    $message .= "<p><strong>কোর্স:</strong> {$course_name}</p>";
    $message .= "<p><strong>এনরোলমেন্ট আইডি:</strong> #{$enrollment_id}</p>";
    $message .= "<p>এখনই আপনার কোর্স শুরু করুন!</p>";
    $message .= "<p style='text-align:center'><a href='https://onesbd.com/LMS/dashboard.php' style='background:#6C5CE7;color:white;padding:12px 30px;border-radius:50px;text-decoration:none;font-weight:bold'>কোর্স শুরু করুন</a></p>";
    $message .= "<p>ধন্যবাদ,<br>ONESBD LMS টিম</p>";
    return sendEmail($user_email, $subject, $message);
}

function sendRejectionEmail($user_email, $user_name, $course_name, $reason = '') {
    $subject = "❌ এনরোলমেন্ট গৃহীত হয়নি - ONESBD LMS";
    $message = "<h3>দুঃখিত {$user_name},</h3>";
    $message .= "<p>আপনার এনরোলমেন্ট গৃহীত হয়নি।</p>";
    $message .= "<p><strong>কোর্স:</strong> {$course_name}</p>";
    if($reason) $message .= "<p><strong>কারণ:</strong> {$reason}</p>";
    $message .= "<p>অনুগ্রহ করে সাপোর্টে যোগাযোগ করুন।</p>";
    $message .= "<p>ধন্যবাদ,<br>ONESBD LMS টিম</p>";
    return sendEmail($user_email, $subject, $message);
}
?>