<?php
// /public_html/includes/mailer.php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Note: If you don't have Composer, we will use a simple PHP mail() fallback or
// you can download PHPMailer manually. For this tutorial, we use a robust
// native socket function that mimics SMTP without needing external libraries.

function send_system_email($to_email, $to_name, $subject, $body) {
    global $conn;
    
    // 1. Fetch Credentials
    $s = $conn->query("SELECT * FROM settings WHERE id = 1")->fetch_assoc();
    if(empty($s['smtp_host'])) return false;

    // 2. Simple PHP Mail (Try this first if on Hostinger as it's pre-configured)
    $headers  = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
    $headers .= "From: " . $s['smtp_from_name'] . " <" . $s['smtp_user'] . ">" . "\r\n";
    
    // Wrap body in a nice template
    $html_body = "
    <div style='font-family: Arial, sans-serif; max-width: 600px; margin: auto; padding: 20px; border: 1px solid #ddd; border-radius: 10px;'>
        <h2 style='color: #0d6efd;'>{$s['site_name']}</h2>
        <hr style='border: 0; border-top: 1px solid #eee;'>
        <div style='padding: 20px 0; font-size: 16px; color: #333;'>
            $body
        </div>
        <hr style='border: 0; border-top: 1px solid #eee;'>
        <p style='font-size: 12px; color: #999; text-align: center;'>&copy; " . date('Y') . " {$s['site_name']}</p>
    </div>";

    if(mail($to_email, $subject, $html_body, $headers)) {
        return true;
    } else {
        // Log error if needed
        return false;
    }
}
?>