<?php
/**
 * Plugin Name: MailService Bridge for CF7
 * Description: Redirects Contact Form 7 emails through Flatlogic MailService.
 */

add_action('wpcf7_before_send_mail', function($contact_form, &$abort, $submission) {
    if ($abort) return;

    require_once ABSPATH . 'mail/MailService.php';

    $data = $submission->get_posted_data();
    
    $name = $data['your-name'] ?? '';
    $email = $data['your-email'] ?? '';
    $subject = $data['your-subject'] ?? 'Contact Form Submission';
    $message = $data['your-message'] ?? '';

    $to = getenv('MAIL_TO') ?: get_option('admin_email');

    $res = MailService::sendContactMessage($name, $email, $message, $to, $subject);

    if (!empty($res['success'])) {
        // Successfully sent via MailService. 
    }
}, 10);

// Override wp_mail to use MailService globally
if (!function_exists('wp_mail')) {
    function wp_mail($to, $subject, $message, $headers = '', $attachments = []) {
        require_once ABSPATH . 'mail/MailService.php';
        
        // Simple conversion of HTML/Text
        $is_html = false;
        if (strpos($headers, 'text/html') !== false) {
            $is_html = true;
        }

        $res = MailService::sendMail(
            $to,
            $subject,
            $is_html ? $message : nl2br($message),
            !$is_html ? $message : strip_tags($message)
        );

        return !empty($res['success']);
    }
}
