<?php
require_once './includes/logging_helper.php'; // Include logging helper functions

function sendEmail($to, $subject, $body) {
    // Load SMTP settings from JSON file
    $jsonFilePath = __DIR__ . '/smtp_settings_data.json';
    if (!file_exists($jsonFilePath)) {
        $errorMessage = "SMTP settings file not found.";
        logCommunication('email', $to, $subject, $body, 'failed', $errorMessage);
        return $errorMessage;
    }

    $json = file_get_contents($jsonFilePath);
    $settings = json_decode($json, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        $errorMessage = "Invalid SMTP settings JSON: " . json_last_error_msg();
        logCommunication('email', $to, $subject, $body, 'failed', $errorMessage);
        return $errorMessage;
    }

    // Include PHPMailer
    require './vendor/autoload.php';

    $mail = new PHPMailer\PHPMailer\PHPMailer(true);
    try {
        // SMTP configuration
        $mail->isSMTP();
        $mail->Host = $settings['smtp_host'];
        $mail->SMTPAuth = true;
        $mail->Username = $settings['smtp_username'];
        $mail->Password = $settings['smtp_password'];
        $mail->SMTPSecure = $settings['smtp_encryption'];
        $mail->Port = $settings['smtp_port'];

        // Sender and recipient
        $mail->setFrom($settings['smtp_username'], $settings['sender_name'] ?? 'Creative Web Solutions');
        $mail->addAddress($to);

        // Email content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $body;

        // Send email
        $mail->send();
        logCommunication('email', $to, $subject, $body, 'success');
        return true; // Email sent successfully
    } catch (Exception $e) {
        $errorMessage = $e->getMessage();
        logCommunication('email', $to, $subject, $body, 'failed', $errorMessage);
        return $errorMessage; // Return error message if sending fails
    }
}
?>