<?php
if (!defined('ABSPATH')) {
    exit;
}

class BMTQB_Email_Service {
    public static function send(BMTQB_Industry_Interface $industry, array $data, $pdf_path, array $photos = [], array $results = [], $quote_reference = '') {
        $settings = BMTQB_Settings_Repository::email_settings($industry);

        $to_customer = sanitize_email($data['email'] ?? '');
        $to_company = $settings['company_email'] ?: get_option('admin_email');

        if (!is_email($to_customer)) {
            return new WP_Error('bmtqb_email_invalid_customer', 'Customer email address is missing or invalid.');
        }

        if (!is_email($to_company)) {
            return new WP_Error('bmtqb_email_invalid_company', 'Company email address is missing or invalid.');
        }

        if ($pdf_path === '' || !file_exists($pdf_path)) {
            return new WP_Error('bmtqb_email_missing_pdf', 'PDF attachment was not found.');
        }

        $headers = ['Content-Type: text/html; charset=UTF-8'];
        if ($settings['from_email'] !== '' && is_email($settings['from_email'])) {
            $from_name = $settings['from_name'] !== '' ? $settings['from_name'] : $industry->label();
            $headers[] = 'From: ' . $from_name . ' <' . $settings['from_email'] . '>';
        }

        $attachments = array_merge([$pdf_path], BMTQB_Photo_Uploader::attachment_paths($photos));
        $subject = $industry->email_subject($data, $results, $quote_reference);
        $customer_message = $industry->customer_email_body($data, $results, $quote_reference);
        $company_message = $industry->company_email_body($data, $results, $quote_reference);

        $customer_sent = wp_mail($to_customer, $subject, $customer_message, $headers, $attachments);
        $company_sent = wp_mail($to_company, 'New ' . $industry->label(), $company_message, $headers, $attachments);

        if (!$customer_sent || !$company_sent) {
            return new WP_Error('bmtqb_email_send_failed', 'One or more quote emails failed to send.');
        }

        return [
            'customer_sent' => $customer_sent,
            'company_sent' => $company_sent,
        ];
    }
}
