<?php
// Securely load the PHPMailer core files
require_once __DIR__ . '/../includes/PHPMailer/src/Exception.php';
require_once __DIR__ . '/../includes/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/../includes/PHPMailer/src/SMTP.php';

// Declare namespaces
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class EmailGateway {
    private $conn;

    // Connect to the database when the class starts
    public function __construct($db_connection) {
        $this->conn = $db_connection;
    }

    // THE MAIN FUNCTION
    public function send($to_email, $subject, $body, $is_html = true) {
        try {
            // 1. Fetch the active SMTP credentials from the database
            $query = "SELECT config_data FROM system_integrations WHERE module_type = 'email' AND is_enabled = 1 AND provider_name = 'SMTP' LIMIT 1";
            $result = $this->conn->query($query);

            if (!$result || $result->num_rows === 0) {
                throw new Exception("Email module is disabled or no SMTP provider is active.");
            }

            $row = $result->fetch_assoc();
            $config = json_decode($row['config_data'], true);

            // 2. Initialize PHPMailer
            $mail = new PHPMailer(true);

            // 3. Server Settings
            $mail->isSMTP();
            $mail->Host       = $config['smtp_host'];                     
            $mail->SMTPAuth   = true;                                   
            $mail->Username   = $config['smtp_user'];                     
            $mail->Password   = $config['smtp_pass'];                     
            
            // Auto-detect encryption based on the port you saved in the UI
            $mail->Port = (int)$config['smtp_port'];
            if ($mail->Port === 465) {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // SSL
            } else {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // TLS (587 usually)
            }

            // 4. Recipients
            $from_name = !empty($config['from_name']) ? $config['from_name'] : 'System Admin';
            $mail->setFrom($config['smtp_user'], $from_name);
            $mail->addAddress($to_email);

            // 5. Content
            $mail->isHTML($is_html);
            $mail->Subject = $subject;
            $mail->Body    = $body;

            // Strip HTML tags for email clients that don't support HTML
            if ($is_html) {
                $mail->AltBody = strip_tags($body);
            }

            // 6. Send the Email
            $mail->send();
            return true;

        } catch (Exception $e) {
            // If it fails, log the exact reason so you can debug it in your server logs
            error_log("Email Gateway Failed: " . $e->getMessage());
            // Also check PHPMailer's internal error
            if (isset($mail)) {
                error_log("PHPMailer Details: " . $mail->ErrorInfo);
            }
            return false;
        }
    }
}
?>