<?php
/**
 * Email Service
 *
 * @package Freelance_Studio
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


class FS_Email_Service {

    /**
     * Send proposal to client
     *
     * @param int $proposal_id Proposal ID
     * @param array $contact_ids Optional array of contact IDs to send to
     * @param string $custom_message Optional custom message to include in email
     * @return bool
     */
    public static function send_proposal($proposal_id, $contact_ids = array(), $custom_message = '', $custom_subject = '', $include_primary = true, $primary_recipient = 'primary', $cc_contact_ids = array()) {
        $proposal = FS_Proposal::get($proposal_id);
        
        if (!$proposal) {
            error_log('Freelance Studio: send_proposal failed - proposal not found');
            return false;
        }
        
        $client = FS_Client::get($proposal->client_id);
        
        if (!$client) {
            error_log('Freelance Studio: send_proposal failed - client not found');
            return false;
        }
        
        // Get project if exists
        $project = null;
        if ($proposal->project_id) {
            $project = FS_Project::get($proposal->project_id);
        }
        
        // Resolve primary "To" recipient
        $to_info = self::resolve_contact_info($client, $primary_recipient);
        if (!$to_info) {
            $to_info = self::resolve_contact_info($client, 'primary');
        }
        if (!$to_info) {
            error_log('Freelance Studio: send_proposal failed - no valid primary recipient');
            return false;
        }
        
        $settings = self::get_business_settings();
        $proposal_url = home_url('?fs_proposal=' . $proposal->view_token);
        
        // Get the email template
        $template = FS_Email_Template::get('proposal_sent');
        
        // Build variable data - personalize for primary "To" recipient
        $client_name = $to_info['name'];
        $project_name = $project ? $project->name : __('N/A', 'freelance-studio');
        $current_month = date_i18n('F');
        
        $template_vars = array(
            '{client_name}' => $client_name,
            '{proposal_title}' => $proposal->title,
            '{amount}' => FS_View_Context::format_currency($proposal->total_amount),
            '{project_name}' => $project_name,
            '{current_month}' => $current_month,
            '{view_link}' => $proposal_url,
            '{business_name}' => $settings['business_name'],
        );
        
        // Process subject
        if (!empty($custom_subject)) {
            $subject = FS_Email_Template::process_variables($custom_subject, $template_vars);
        } else {
            $subject = FS_Email_Template::process_variables($template['subject'], $template_vars);
        }
        
        // Process body content - just replace variables, no formatting changes
        $body_content = FS_Email_Template::process_variables($template['body'], $template_vars);
        
        // Prepend custom message if provided (styled in italics, before main content)
        if (!empty($custom_message)) {
            $processed_message = FS_Email_Template::process_variables($custom_message, $template_vars);
            $processed_message = nl2br(esc_html($processed_message));
            $custom_message_html = '<div style="margin-bottom: 24px; padding-bottom: 24px; border-bottom: 1px solid #e5e7eb; font-style: italic; color: #4b5563;">' . $processed_message . '</div>';
            $body_content = $custom_message_html . $body_content;
        }
        
        // Add client dashboard link if portal is enabled
        if (!empty($client->portal_enabled) && !empty($client->portal_token)) {
            $portal_url = home_url('?fs_portal=' . $client->portal_token);
            $primary_color = get_option('fs_invoice_primary_color', '#4173B0');
            $body_content .= '<div style="margin-top: 32px; padding-top: 24px; border-top: 1px solid #e5e7eb; text-align: center;">';
            $body_content .= '<a href="' . esc_url($portal_url) . '" style="color: ' . esc_attr($primary_color) . '; text-decoration: none; font-size: 14px;">';
            $body_content .= __('View Your Client Dashboard', 'freelance-studio');
            $body_content .= '</a>';
            $body_content .= '</div>';
        }
        
        // Wrap in email template
        $message = FS_Email_Template::wrap_in_template($body_content, $subject);
        
        // Set headers with business email as the From address
        $headers = array(
            'Content-Type: text/html; charset=UTF-8',
        );
        
        if (!empty($settings['business_email'])) {
            $from_name = !empty($settings['business_name']) ? $settings['business_name'] : get_bloginfo('name');
            $headers[] = 'From: ' . $from_name . ' <' . $settings['business_email'] . '>';
            $headers[] = 'Reply-To: ' . $from_name . ' <' . $settings['business_email'] . '>';
        }
        
        // Resolve CC recipients
        $cc_emails = array();
        foreach ($cc_contact_ids as $cc_id) {
            $cc_info = self::resolve_contact_info($client, $cc_id);
            if ($cc_info && $cc_info['email'] !== $to_info['email']) {
                $cc_emails[] = $cc_info['email'];
            }
        }
        
        // Add CC headers
        foreach ($cc_emails as $cc_email) {
            $headers[] = 'Cc: ' . $cc_email;
        }
        
        // Send single email to primary recipient with CC
        add_action('wp_mail_failed', array(__CLASS__, 'log_mail_error'));
        
        $sent = wp_mail($to_info['email'], $subject, $message, $headers);
        
        if ($sent) {
            self::log_email($to_info['email'], $subject, 'proposal', $proposal_id);
            error_log('Freelance Studio: Proposal email sent to ' . $to_info['email'] . (!empty($cc_emails) ? ' (CC: ' . implode(', ', $cc_emails) . ')' : ''));
        } else {
            error_log('Freelance Studio: Failed to send proposal email to ' . $to_info['email']);
        }
        
        remove_action('wp_mail_failed', array(__CLASS__, 'log_mail_error'));
        
        if ($sent) {
            // Update proposal status to sent
            FS_Proposal::update_status($proposal_id, 'sent');
            
            // Clear viewed_at so the "viewed" notification fires again on next client view
            global $wpdb;
            $wpdb->update(
                $wpdb->prefix . 'fs_proposals',
                array('viewed_at' => null),
                array('id' => $proposal_id),
                array('%s'),
                array('%d')
            );
        }
        
        return $sent;
    }

    /**
     * Log mail errors
     */
    public static function log_mail_error($wp_error) {
        error_log('Freelance Studio Mail Error: ' . $wp_error->get_error_message());
    }

    /**
     * Send proposal approved notification to freelancer
     *
     * @param int $proposal_id Proposal ID
     * @return bool
     */
    public static function send_proposal_approved_notification($proposal_id) {
        $proposal = FS_Proposal::get($proposal_id);
        
        if (!$proposal) {
            return false;
        }
        
        $client = FS_Client::get($proposal->client_id);
        $settings = self::get_business_settings();
        
        if (empty($settings['business_email'])) {
            return false;
        }
        
        $subject = sprintf(
            /* translators: 1. proposal approved value */
            __('Proposal Approved: %s', 'freelance-studio'),
            $proposal->title
        );
        
        $message = self::get_proposal_approved_email_html($proposal, $client, $settings);
        
        $headers = array(
            'Content-Type: text/html; charset=UTF-8',
        );
        
        return wp_mail($settings['business_email'], $subject, $message, $headers);
    }

    /**
     * Send revision request notification to freelancer
     *
     * @param int    $proposal_id    Proposal ID
     * @param string $revision_notes Client's requested changes
     * @return bool
     */
    public static function send_revision_request_notification($proposal_id, $revision_notes) {
        $proposal = FS_Proposal::get($proposal_id);
        
        if (!$proposal) {
            return false;
        }
        
        $client = FS_Client::get($proposal->client_id);
        $settings = self::get_business_settings();
        
        if (empty($settings['business_email'])) {
            return false;
        }
        
        $subject = sprintf(
            /* translators: 1. date/time */
            __('Revision Requested: %s', 'freelance-studio'),
            $proposal->title
        );
        
        $message = self::get_revision_request_email_html($proposal, $client, $settings, $revision_notes);
        
        $headers = array(
            'Content-Type: text/html; charset=UTF-8',
        );
        
        return wp_mail($settings['business_email'], $subject, $message, $headers);
    }

    /**
     * Get revision request notification email HTML
     */
    private static function get_revision_request_email_html($proposal, $client, $settings, $revision_notes) {
        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
        </head>
        <body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background-color: #f3f4f6;">
            <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f3f4f6; padding: 40px 20px;">
                <tr>
                    <td align="center">
                        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden;">
                            <tr>
                                <td style="padding: 32px; text-align: center; background-color: #f59e0b;">
                                    <h1 style="margin: 0; color: #ffffff; font-size: 24px;">📝 <?php esc_html_e('Revision Requested', 'freelance-studio'); ?></h1>
                                </td>
                            </tr>
                            <tr>
                                <td style="padding: 40px 32px;">
                                    <p style="margin: 0 0 16px 0; color: #4b5563; font-size: 16px;">
                                        <?php printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                            /* translators: 1. has requested value */
                                            __('%s has requested changes to your proposal.', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                            esc_html($client->company_name ?: $client->name)
                                        ); ?>
                                    </p>
                                    
                                    <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f9fafb; border-radius: 8px; margin: 24px 0;">
                                        <tr>
                                            <td style="padding: 24px;">
                                                <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;"><?php esc_html_e('Proposal', 'freelance-studio'); ?></p>
                                                <p style="margin: 0 0 16px 0; color: #111827; font-size: 18px; font-weight: 600;"><?php echo esc_html($proposal->title); ?></p>
                                                
                                                <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;"><?php esc_html_e('Client', 'freelance-studio'); ?></p>
                                                <p style="margin: 0 0 16px 0; color: #111827; font-size: 16px;"><?php echo esc_html($client->company_name ?: $client->name); ?></p>
                                                
                                                <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;"><?php esc_html_e('Requested Changes', 'freelance-studio'); ?></p>
                                                <div style="margin: 0; padding: 16px; background-color: #fff; border-left: 4px solid #f59e0b; color: #111827; font-size: 14px; white-space: pre-wrap;"><?php echo esc_html($revision_notes); ?></div>
                                            </td>
                                        </tr>
                                    </table>
                                    
                                    <table width="100%" cellpadding="0" cellspacing="0">
                                        <tr>
                                            <td align="center">
                                                <a href="<?php echo esc_url(admin_url('admin.php?page=fs-proposals&action=edit&id=' . $proposal->id)); ?>" style="display: inline-block; padding: 16px 32px; background-color: #2271b1; color: #ffffff; text-decoration: none; border-radius: 8px; font-size: 16px; font-weight: 600;">
                                                    <?php esc_html_e('Edit Proposal', 'freelance-studio'); ?>
                                                </a>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Send contract to client
     *
     * @param int $contract_id Contract ID
     * @param array $contact_ids Optional specific contact IDs
     * @param string $custom_message Optional custom message
     * @param string $custom_subject Optional custom subject line
     * @return bool Success
     */
    public static function send_contract($contract_id, $contact_ids = array(), $custom_message = '', $custom_subject = '', $include_primary = true, $primary_recipient = 'primary', $cc_contact_ids = array()) {
        $contract = FS_Contract::get($contract_id);
        
        if (!$contract) {
            error_log('Freelance Studio: send_contract failed - contract not found');
            return false;
        }
        
        $client = FS_Client::get($contract->client_id);
        
        if (!$client) {
            error_log('Freelance Studio: send_contract failed - client not found');
            return false;
        }
        
        // Get project if exists
        $project = null;
        if ($contract->project_id) {
            $project = FS_Project::get($contract->project_id);
        }
        
        // Resolve primary "To" recipient
        $to_info = self::resolve_contact_info($client, $primary_recipient);
        if (!$to_info) {
            $to_info = self::resolve_contact_info($client, 'primary');
        }
        if (!$to_info) {
            error_log('Freelance Studio: send_contract failed - no valid primary recipient');
            return false;
        }
        
        $settings = self::get_business_settings();
        $contract_url = home_url('?fs_contract=' . $contract->view_token);
        
        // Get the email template
        $template = FS_Email_Template::get('contract_sent');
        
        // Build variable data - personalize for primary "To" recipient (the signer)
        $project_name = $project ? $project->name : __('N/A', 'freelance-studio');
        $current_month = date_i18n('F');
        $expires_date = !empty($contract->valid_until) ? date_i18n(get_option('date_format'), strtotime($contract->valid_until)) : __('N/A', 'freelance-studio');
        
        $template_vars = array(
            '{client_name}' => $to_info['name'],
            '{contact_name}' => $to_info['name'],
            '{contract_title}' => $contract->title,
            '{expires_date}' => $expires_date,
            '{project_name}' => $project_name,
            '{current_month}' => $current_month,
            '{view_link}' => $contract_url,
            '{business_name}' => $settings['business_name'],
        );
        
        // Process subject
        if (!empty($custom_subject)) {
            $subject = FS_Email_Template::process_variables($custom_subject, $template_vars);
        } else {
            $subject = FS_Email_Template::process_variables($template['subject'] ?? '', $template_vars);
        }
        
        // Process body content
        $body_content = FS_Email_Template::process_variables($template['body'] ?? '', $template_vars);
        
        // Clean up TinyMCE artifacts
        if (!empty($body_content)) {
            $body_content = preg_replace('/<p>\s*(&nbsp;|\xC2\xA0)?\s*<\/p>/i', '', $body_content);
            $body_content = preg_replace('/<p>\s*<br\s*\/?>\s*<\/p>/i', '', $body_content);
            $body_content = preg_replace('/(<br\s*\/?>\s*){3,}/i', '<br><br>', $body_content);
        }
        
        // Only apply nl2br if content doesn't already have paragraph tags
        if (!empty($body_content) && strpos($body_content, '<p>') === false && strpos($body_content, '<p ') === false) {
            $body_content = nl2br($body_content);
        }
        
        // Prepend custom message if provided
        if (!empty($custom_message)) {
            $processed_message = FS_Email_Template::process_variables($custom_message, $template_vars);
            $processed_message = nl2br(esc_html($processed_message));
            $custom_message_html = '<div style="margin-bottom: 24px; padding-bottom: 24px; border-bottom: 1px solid #e5e7eb; font-style: italic; color: #4b5563;">' . $processed_message . '</div>';
            $body_content = $custom_message_html . $body_content;
        }
        
        // Add client dashboard link if portal is enabled
        if (!empty($client->portal_enabled) && !empty($client->portal_token)) {
            $portal_url = home_url('?fs_portal=' . $client->portal_token);
            $primary_color = get_option('fs_invoice_primary_color', '#4173B0');
            $body_content .= '<div style="margin-top: 32px; padding-top: 24px; border-top: 1px solid #e5e7eb; text-align: center;">';
            $body_content .= '<a href="' . esc_url($portal_url) . '" style="color: ' . esc_attr($primary_color) . '; text-decoration: none; font-size: 14px;">';
            $body_content .= __('View Your Client Dashboard', 'freelance-studio');
            $body_content .= '</a>';
            $body_content .= '</div>';
        }
        
        // Wrap in email template
        $message = FS_Email_Template::wrap_in_template($body_content, $subject);
        
        // Set headers
        $headers = array(
            'Content-Type: text/html; charset=UTF-8',
        );
        
        if (!empty($settings['business_email'])) {
            $from_name = !empty($settings['business_name']) ? $settings['business_name'] : get_bloginfo('name');
            $headers[] = 'From: ' . $from_name . ' <' . $settings['business_email'] . '>';
            $headers[] = 'Reply-To: ' . $from_name . ' <' . $settings['business_email'] . '>';
        }
        
        // Resolve CC recipients
        $cc_emails = array();
        foreach ($cc_contact_ids as $cc_id) {
            $cc_info = self::resolve_contact_info($client, $cc_id);
            if ($cc_info && $cc_info['email'] !== $to_info['email']) {
                $cc_emails[] = $cc_info['email'];
            }
        }
        
        // Add CC headers
        foreach ($cc_emails as $cc_email) {
            $headers[] = 'Cc: ' . $cc_email;
        }
        
        // Send single email to primary recipient with CC
        add_action('wp_mail_failed', array(__CLASS__, 'log_mail_error'));
        
        $sent = wp_mail($to_info['email'], $subject, $message, $headers);
        
        if ($sent) {
            self::log_email($to_info['email'], $subject, 'contract', $contract_id);
            error_log('Freelance Studio: Contract email sent to ' . $to_info['email'] . (!empty($cc_emails) ? ' (CC: ' . implode(', ', $cc_emails) . ')' : ''));
        } else {
            error_log('Freelance Studio: Failed to send contract email to ' . $to_info['email']);
        }
        
        remove_action('wp_mail_failed', array(__CLASS__, 'log_mail_error'));
        
        if ($sent) {
            FS_Contract::update_status($contract_id, 'sent');
            
            // Clear viewed_at so the "viewed" notification fires again on next client view
            global $wpdb;
            $wpdb->update(
                $wpdb->prefix . 'fs_contracts',
                array('viewed_at' => null),
                array('id' => $contract_id),
                array('%s'),
                array('%d')
            );
        }
        
        return $sent;
    }

    /**
     * Send contract signed notification to freelancer
     *
     * @param int $contract_id Contract ID
     * @return bool Success
     */
    /**
     * Send notification to freelancer when a proposal is viewed for the first time
     *
     * @param int $proposal_id Proposal ID
     * @return bool
     */
    public static function send_proposal_viewed_notification($proposal_id) {
        if (!get_option('fs_notify_proposal_viewed', '0')) {
            return false;
        }

        $proposal = FS_Proposal::get($proposal_id);
        if (!$proposal) {
            return false;
        }

        $client = FS_Client::get($proposal->client_id);
        $client_name = $client ? FS_Client::get_display_name($client) : __('Unknown', 'freelance-studio');

        $content = '<p style="margin: 0 0 16px 0;">'
            . sprintf(
                /* translators: 1. date/time, 2. date/time */
                __('Your proposal <strong>%1$s</strong> was just opened by <strong>%2$s</strong>.', 'freelance-studio'),
                esc_html($proposal->title),
                esc_html($client_name)
            )
            . '</p>';

        $content .= '<p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;">'
            /* translators: 1. date/time */
            . sprintf(__('Viewed on %s', 'freelance-studio'), date_i18n(get_option('date_format') . ' ' . get_option('time_format'), current_time('timestamp')))
            . '</p>';

        $total = !empty($proposal->total_amount) ? $proposal->total_amount : 0;
        if ($total > 0) {
            $content .= '<p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;">'
                /* translators: 1. proposal total value */
                . sprintf(__('Proposal total: %s', 'freelance-studio'), FS_View_Context::format_currency($total))
                . '</p>';
        }

        return self::send_styled_email(
            get_option('fs_business_email', get_option('admin_email')),
            /* translators: 1. proposal viewed value */
            sprintf(__('👀 Proposal Viewed: %s', 'freelance-studio'), $proposal->title),
            __('Proposal Viewed', 'freelance-studio'),
            $content,
            array(
                'cta_text' => __('View Proposal', 'freelance-studio'),
                'cta_url' => admin_url('admin.php?page=fs-proposals&action=view&id=' . $proposal->id),
                'internal' => true,
            )
        );
    }

    /**
     * Send notification to freelancer when a contract is viewed for the first time
     *
     * @param int $contract_id Contract ID
     * @return bool
     */
    public static function send_contract_viewed_notification($contract_id) {
        if (!get_option('fs_notify_contract_viewed', '0')) {
            return false;
        }

        $contract = FS_Contract::get($contract_id);
        if (!$contract) {
            return false;
        }

        $client = FS_Client::get($contract->client_id);
        $client_name = $client ? FS_Client::get_display_name($client) : __('Unknown', 'freelance-studio');

        $content = '<p style="margin: 0 0 16px 0;">'
            . sprintf(
                /* translators: 1. date/time, 2. date/time */
                __('Your contract <strong>%1$s</strong> was just opened by <strong>%2$s</strong>.', 'freelance-studio'),
                esc_html($contract->title),
                esc_html($client_name)
            )
            . '</p>';

        $content .= '<p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;">'
            /* translators: 1. date/time */
            . sprintf(__('Viewed on %s', 'freelance-studio'), date_i18n(get_option('date_format') . ' ' . get_option('time_format'), current_time('timestamp')))
            . '</p>';

        return self::send_styled_email(
            get_option('fs_business_email', get_option('admin_email')),
            /* translators: 1. date/time */
            sprintf(__('👀 Contract Viewed: %s', 'freelance-studio'), $contract->title),
            __('Contract Viewed', 'freelance-studio'),
            $content,
            array(
                'cta_text' => __('View Contract', 'freelance-studio'),
                'cta_url' => admin_url('admin.php?page=fs-contracts&action=view&id=' . $contract->id),
                'internal' => true,
            )
        );
    }

    /**
     * Send notification to freelancer when an invoice is viewed for the first time
     *
     * @param int $invoice_id Invoice ID
     * @return bool
     */
    public static function send_invoice_viewed_notification($invoice_id) {
        if (!get_option('fs_notify_invoice_viewed', '0')) {
            return false;
        }

        $invoice = FS_Invoice::get($invoice_id);
        if (!$invoice) {
            return false;
        }

        $client = FS_Client::get($invoice->client_id);
        $client_name = $client ? FS_Client::get_display_name($client) : __('Unknown', 'freelance-studio');

        $content = '<p style="margin: 0 0 16px 0;">'
            . sprintf(
                /* translators: 1. number/ID, 2. date/time */
                __('Your invoice <strong>#%1$s</strong> was just opened by <strong>%2$s</strong>.', 'freelance-studio'),
                esc_html($invoice->invoice_number),
                esc_html($client_name)
            )
            . '</p>';

        $content .= '<p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;">'
            /* translators: 1. date/time */
            . sprintf(__('Viewed on %s', 'freelance-studio'), date_i18n(get_option('date_format') . ' ' . get_option('time_format'), current_time('timestamp')))
            . '</p>';

        $content .= '<p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;">'
            /* translators: 1. invoice total value */
            . sprintf(__('Invoice total: %s', 'freelance-studio'), FS_View_Context::format_currency($invoice->total))
            . '</p>';

        if ($invoice->due_date) {
            $content .= '<p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;">'
                /* translators: 1. date/time */
                . sprintf(__('Due date: %s', 'freelance-studio'), date_i18n(get_option('date_format'), strtotime($invoice->due_date)))
                . '</p>';
        }

        return self::send_styled_email(
            get_option('fs_business_email', get_option('admin_email')),
            /* translators: 1. number/ID */
            sprintf(__('👀 Invoice Viewed: #%s', 'freelance-studio'), $invoice->invoice_number),
            __('Invoice Viewed', 'freelance-studio'),
            $content,
            array(
                'cta_text' => __('View Invoice', 'freelance-studio'),
                'cta_url' => admin_url('admin.php?page=fs-finances&tab=invoices&action=view&id=' . $invoice->id),
                'internal' => true,
            )
        );
    }

    public static function send_contract_signed_notification($contract_id, $pdf_path = null) {
        $contract = FS_Contract::get($contract_id);
        
        if (!$contract) {
            return false;
        }
        
        $client = FS_Client::get($contract->client_id);
        $settings = self::get_business_settings();
        
        if (empty($settings['business_email'])) {
            return false;
        }
        
        $subject = sprintf(
            /* translators: 1. date/time */
            __('Contract Signed: %s', 'freelance-studio'),
            $contract->title
        );
        
        $message = self::get_contract_signed_notification_html($contract, $client, $settings, $pdf_path);
        
        $headers = array('Content-Type: text/html; charset=UTF-8');
        
        // Attach PDF if available
        $attachments = array();
        if ($pdf_path) {
            $upload_dir = wp_upload_dir();
            $full_path = $upload_dir['basedir'] . '/' . $pdf_path;
            if (file_exists($full_path)) {
                $attachments[] = $full_path;
            }
        }
        
        return wp_mail($settings['business_email'], $subject, $message, $headers, $attachments);
    }

    /**
     * Send signed contract copy to client
     *
     * @param int $contract_id Contract ID
     * @param string|null $pdf_path Path to signed PDF
     * @return bool Success
     */
    public static function send_signed_contract_to_client($contract_id, $pdf_path = null) {
        $contract = FS_Contract::get($contract_id);
        
        if (!$contract) {
            return false;
        }
        
        $client = FS_Client::get($contract->client_id);
        $settings = self::get_business_settings();
        
        // Get client email
        $client_email = $client->email;
        if (empty($client_email)) {
            return false;
        }
        
        $subject = sprintf(
            /* translators: 1. date/time */
            __('Your Signed Contract: %s', 'freelance-studio'),
            $contract->title
        );
        
        $message = self::get_signed_contract_client_email_html($contract, $client, $settings, $pdf_path);
        
        $headers = array('Content-Type: text/html; charset=UTF-8');
        if (!empty($settings['business_email'])) {
            $headers[] = 'From: ' . $settings['business_name'] . ' <' . $settings['business_email'] . '>';
        }
        
        // Attach PDF if available
        $attachments = array();
        if ($pdf_path) {
            $upload_dir = wp_upload_dir();
            $full_path = $upload_dir['basedir'] . '/' . $pdf_path;
            if (file_exists($full_path)) {
                $attachments[] = $full_path;
            }
        }
        
        return wp_mail($client_email, $subject, $message, $headers, $attachments);
    }

    /**
     * Get signed contract email HTML for client
     */
    private static function get_signed_contract_client_email_html($contract, $client, $settings, $pdf_path = null) {
        $primary_color = !empty($settings['primary_color']) ? $settings['primary_color'] : '#4173B0';
        
        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
        </head>
        <body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background-color: #f3f4f6;">
            <table width="100%" cellpadding="0" cellspacing="0" style="padding: 40px 20px;">
                <tr>
                    <td align="center">
                        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
                            <tr>
                                <td style="padding: 40px;">
                                    <!-- Logo/Header -->
                                    <?php if (!empty($settings['business_logo'])): ?>
                                        <div style="text-align: center; margin-bottom: 24px;">
                                            <img src="<?php echo esc_url($settings['business_logo']); ?>" alt="<?php echo esc_attr($settings['business_name']); ?>" style="max-width: 200px; max-height: 60px;">
                                        </div>
                                    <?php else: ?>
                                        <h2 style="text-align: center; margin: 0 0 24px 0; color: <?php echo  esc_attr( $primary_color ); ?>; font-size: 24px;"><?php echo esc_html($settings['business_name']); ?></h2>
                                    <?php endif; ?>
                                    
                                    <div style="background-color: #dcfce7; color: #166534; padding: 16px 24px; border-radius: 8px; margin-bottom: 24px; text-align: center;">
                                        <strong style="font-size: 18px;">✓ <?php esc_html_e('Contract Successfully Signed', 'freelance-studio'); ?></strong>
                                    </div>
                                    
                                    <p style="margin: 0 0 16px 0; color: #374151; font-size: 16px;">
                                        <?php /* translators: 1. recipient name */ ?>
                                        <?php echo esc_html( sprintf( __( 'Hello %s,', 'freelance-studio'), esc_html($client->name ?: $client->company_name)) ); ?>
                                    </p>
                                    
                                    <p style="margin: 0 0 16px 0; color: #374151; font-size: 16px;">
                                        <?php esc_html_e('Thank you for signing the contract. Please find attached a copy for your records.', 'freelance-studio'); ?>
                                    </p>
                                    
                                    <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f9fafb; border-radius: 8px; padding: 20px; margin-bottom: 24px;">
                                        <tr>
                                            <td>
                                                <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;"><?php esc_html_e('Contract', 'freelance-studio'); ?></p>
                                                <p style="margin: 0 0 16px 0; color: #111827; font-size: 18px; font-weight: 600;"><?php echo esc_html($contract->title); ?></p>
                                                
                                                <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;"><?php esc_html_e('Contract Number', 'freelance-studio'); ?></p>
                                                <p style="margin: 0 0 16px 0; color: #111827; font-size: 16px;"><?php echo esc_html($contract->contract_number); ?></p>
                                                
                                                <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;"><?php esc_html_e('Signed on', 'freelance-studio'); ?></p>
                                                <p style="margin: 0; color: #111827; font-size: 16px;"><?php echo  esc_html( date_i18n(get_option('date_format'), strtotime($contract->signed_at)) ); ?></p>
                                            </td>
                                        </tr>
                                    </table>
                                    
                                    <?php if ($pdf_path): ?>
                                    <p style="margin: 0 0 24px 0; color: #6b7280; font-size: 14px; text-align: center;">
                                        📎 <?php esc_html_e('A copy of the signed contract is attached to this email.', 'freelance-studio'); ?>
                                    </p>
                                    <?php endif; ?>
                                    
                                    <p style="margin: 0 0 8px 0; color: #374151; font-size: 16px;">
                                        <?php esc_html_e('If you have any questions, please don\'t hesitate to reach out.', 'freelance-studio'); ?>
                                    </p>
                                    
                                    <p style="margin: 24px 0 0 0; color: #374151; font-size: 16px;">
                                        <?php esc_html_e('Best regards,', 'freelance-studio'); ?><br>
                                        <strong><?php echo esc_html($settings['business_name']); ?></strong>
                                    </p>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Get contract signed notification email HTML
     */
    private static function get_contract_signed_notification_html($contract, $client, $settings, $pdf_path = null) {
        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
        </head>
        <body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background-color: #f3f4f6;">
            <table width="100%" cellpadding="0" cellspacing="0" style="padding: 40px 20px;">
                <tr>
                    <td align="center">
                        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
                            <tr>
                                <td style="padding: 40px;">
                                    <div style="background-color: #dcfce7; color: #166534; padding: 16px 24px; border-radius: 8px; margin-bottom: 24px; text-align: center;">
                                        <strong style="font-size: 18px;">🎉 <?php esc_html_e('Contract Signed!', 'freelance-studio'); ?></strong>
                                    </div>
                                    
                                    <p style="margin: 0 0 16px 0; color: #374151; font-size: 16px;">
                                        <?php /* translators: 1. date/time */ ?>
                                        <?php echo wp_kses_post( sprintf( __('Great news! %s has signed the contract.', 'freelance-studio'), '<strong>' . esc_html($client->company_name ?: $client->name) . '</strong>')); ?>
                                    </p>
                                    
                                    <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f9fafb; border-radius: 8px; padding: 20px; margin-bottom: 24px;">
                                        <tr>
                                            <td>
                                                <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;"><?php esc_html_e('Contract', 'freelance-studio'); ?></p>
                                                <p style="margin: 0 0 16px 0; color: #111827; font-size: 18px; font-weight: 600;"><?php echo esc_html($contract->title); ?></p>
                                                
                                                <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;"><?php esc_html_e('Signed by', 'freelance-studio'); ?></p>
                                                <p style="margin: 0 0 16px 0; color: #111827; font-size: 16px;"><?php echo esc_html($contract->signature_client_name); ?></p>
                                                
                                                <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;"><?php esc_html_e('Signed at', 'freelance-studio'); ?></p>
                                                <p style="margin: 0; color: #111827; font-size: 16px;"><?php echo  esc_html( date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($contract->signature_client_date)) ); ?></p>
                                            </td>
                                        </tr>
                                    </table>
                                    
                                    <?php if ($pdf_path): ?>
                                    <p style="margin: 0 0 24px 0; color: #6b7280; font-size: 14px; text-align: center;">
                                        📎 <?php esc_html_e('The signed contract is attached to this email.', 'freelance-studio'); ?>
                                    </p>
                                    <?php endif; ?>
                                    
                                    <table width="100%" cellpadding="0" cellspacing="0">
                                        <tr>
                                            <td align="center">
                                                <a href="<?php echo esc_url(admin_url('admin.php?page=fs-contracts&action=view&id=' . $contract->id)); ?>" style="display: inline-block; padding: 16px 32px; background-color: #2271b1; color: #ffffff; text-decoration: none; border-radius: 8px; font-size: 16px; font-weight: 600;">
                                                    <?php esc_html_e('View Contract', 'freelance-studio'); ?>
                                                </a>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Get contract email HTML
     */
    private static function get_contract_email_html($contract, $client, $settings, $contract_url, $custom_message = '') {
        $primary_color = !empty($settings['primary_color']) ? $settings['primary_color'] : '#4173B0';
        $deposit_amount = FS_Contract::calculate_deposit($contract);
        
        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
        <body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; background-color: #f3f4f6;">
            <table width="100%" cellpadding="0" cellspacing="0" style="padding: 40px 20px;">
                <tr>
                    <td align="center">
                        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 12px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);">
                            <tr>
                                <td style="padding: 40px;">
                                    <!-- Logo/Header -->
                                    <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom: 32px;">
                                        <tr>
                                            <td align="center">
                                                <?php if (!empty($settings['business_logo'])): ?>
                                                    <img src="<?php echo esc_url($settings['business_logo']); ?>" alt="<?php echo esc_attr($settings['business_name']); ?>" style="max-width: 200px; max-height: 60px; margin-bottom: 16px;">
                                                <?php else: ?>
                                                    <h2 style="margin: 0 0 16px 0; color: <?php echo  esc_attr( $primary_color ); ?>; font-size: 24px;"><?php echo esc_html($settings['business_name']); ?></h2>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    </table>
                                    
                                    <!-- Greeting -->
                                    <p style="margin: 0 0 16px 0; color: #374151; font-size: 16px; line-height: 1.5;">
                                        <?php /* translators: 1. recipient name */ ?>
                                        <?php echo esc_html( sprintf( __( 'Hello %s,', 'freelance-studio'), esc_html($client->name ?: $client->company_name)) ); ?>
                                    </p>
                                    
                                    <p style="margin: 0 0 24px 0; color: #374151; font-size: 16px; line-height: 1.5;">
                                        <?php esc_html_e('Please review and sign the following contract:', 'freelance-studio'); ?>
                                    </p>
                                    
                                    <?php if (!empty($custom_message)): ?>
                                    <!-- Custom Message -->
                                    <div style="margin: 0 0 24px 0; padding: 16px 20px; background-color: #f0f9ff; border-left: 4px solid <?php echo  esc_attr( $primary_color ); ?>; color: #1e40af; font-size: 15px; line-height: 1.6;">
                                        <?php echo nl2br(esc_html($custom_message)); ?>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <!-- Contract Summary Box -->
                                    <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f9fafb; border-radius: 8px; margin-bottom: 24px;">
                                        <tr>
                                            <td style="padding: 24px;">
                                                <h3 style="margin: 0 0 16px 0; color: #111827; font-size: 18px;">
                                                    <?php echo esc_html($contract->title); ?>
                                                </h3>
                                                
                                                <table width="100%" cellpadding="0" cellspacing="0">
                                                    <tr>
                                                        <td style="padding: 8px 0; border-bottom: 1px solid #e5e7eb;">
                                                            <span style="color: #6b7280; font-size: 14px;"><?php esc_html_e('Contract #:', 'freelance-studio'); ?></span>
                                                        </td>
                                                        <td align="right" style="padding: 8px 0; border-bottom: 1px solid #e5e7eb;">
                                                            <span style="color: #111827; font-size: 14px; font-weight: 500;"><?php echo esc_html($contract->contract_number); ?></span>
                                                        </td>
                                                    </tr>
                                                    <?php if ($contract->start_date): ?>
                                                    <tr>
                                                        <td style="padding: 8px 0; border-bottom: 1px solid #e5e7eb;">
                                                            <span style="color: #6b7280; font-size: 14px;"><?php esc_html_e('Start Date:', 'freelance-studio'); ?></span>
                                                        </td>
                                                        <td align="right" style="padding: 8px 0; border-bottom: 1px solid #e5e7eb;">
                                                            <span style="color: #111827; font-size: 14px; font-weight: 500;"><?php echo  esc_html( date_i18n(get_option('date_format'), strtotime($contract->start_date)) ); ?></span>
                                                        </td>
                                                    </tr>
                                                    <?php endif; ?>
                                                    <tr>
                                                        <td style="padding: 8px 0;">
                                                            <span style="color: #6b7280; font-size: 14px;"><?php esc_html_e('Total:', 'freelance-studio'); ?></span>
                                                        </td>
                                                        <td align="right" style="padding: 8px 0;">
                                                            <span style="color: #111827; font-size: 18px; font-weight: 600;">$<?php echo number_format($contract->total_amount, 2); ?></span>
                                                        </td>
                                                    </tr>
                                                    <?php if ($deposit_amount > 0): ?>
                                                    <tr>
                                                        <td style="padding: 8px 0;">
                                                            <span style="color: #6b7280; font-size: 14px;"><?php esc_html_e('Deposit Due:', 'freelance-studio'); ?></span>
                                                        </td>
                                                        <td align="right" style="padding: 8px 0;">
                                                            <span style="color: #111827; font-size: 16px; font-weight: 500;">$<?php echo number_format($deposit_amount, 2); ?></span>
                                                        </td>
                                                    </tr>
                                                    <?php endif; ?>
                                                </table>
                                            </td>
                                        </tr>
                                    </table>
                                    
                                    <!-- CTA Button -->
                                    <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom: 24px;">
                                        <tr>
                                            <td align="center">
                                                <a href="<?php echo esc_url($contract_url); ?>" style="display: inline-block; padding: 16px 40px; background-color: <?php echo esc_attr( $primary_color ); ?>; color: #ffffff; text-decoration: none; border-radius: 8px; font-size: 16px; font-weight: 600;">
                                                    <?php esc_html_e('Review & Sign Contract', 'freelance-studio'); ?>
                                                </a>
                                            </td>
                                        </tr>
                                    </table>
                                    
                                    <!-- Footer -->
                                    <p style="margin: 0; color: #9ca3af; font-size: 14px; text-align: center;">
                                        <?php esc_html_e('If you have any questions, please reply to this email.', 'freelance-studio'); ?>
                                    </p>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Get proposal email HTML
     *
     * @param object $proposal Proposal object
     * @param object $client Client object
     * @param array $settings Business settings
     * @param string $proposal_url URL to view proposal
     * @param string $custom_message Optional custom message
     */
    private static function get_proposal_email_html($proposal, $client, $settings, $proposal_url, $custom_message = '') {
        $primary_color = !empty($settings['primary_color']) ? $settings['primary_color'] : '#4173B0';
        
        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
        <body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background-color: #f3f4f6;">
            <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f3f4f6; padding: 40px 20px;">
                <tr>
                    <td align="center">
                        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                            <!-- Header -->
                            <tr>
                                <td style="padding: 32px; text-align: center; background-color: <?php echo esc_attr($primary_color); ?>;">
                                    <?php 
                                        // Use light logo on colored background, fall back to dark logo
                                        $email_header_logo = !empty($settings['business_logo_light']) ? $settings['business_logo_light'] : (!empty($settings['business_logo']) ? $settings['business_logo'] : '');
                                    ?>
                                    <?php if (!empty($email_header_logo)): ?>
                                        <img src="<?php echo esc_url($email_header_logo); ?>" alt="<?php echo esc_attr($settings['business_name']); ?>" style="max-width: 180px; max-height: 60px;">
                                    <?php else: ?>
                                        <h1 style="margin: 0; color: #ffffff; font-size: 24px;"><?php echo esc_html($settings['business_name']); ?></h1>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            
                            <!-- Content -->
                            <tr>
                                <td style="padding: 40px 32px;">
                                    <h2 style="margin: 0 0 16px 0; color: #111827; font-size: 24px;">
                                        <?php esc_html_e('You have a new proposal', 'freelance-studio'); ?>
                                    </h2>
                                    
                                    <p style="margin: 0 0 24px 0; color: #4b5563; font-size: 16px; line-height: 1.6;">
                                        <?php printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                            /* translators: 1. recipient name, 2. , value */
                                            __('Hi %1$s, %2$s has sent you a proposal for your review.', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                            esc_html($client->name),
                                            esc_html($settings['business_name'])
                                        ); ?>
                                    </p>
                                    
                                    <?php if (!empty($custom_message)): ?>
                                    <!-- Custom Message -->
                                    <div style="margin: 0 0 24px 0; padding: 16px 20px; background-color: #f9fafb; border-left: 4px solid <?php echo esc_attr($primary_color); ?>; border-radius: 0 8px 8px 0;">
                                        <div style="margin: 0; color: #374151; font-size: 15px; line-height: 1.8;"><?php echo nl2br(esc_html($custom_message)); ?></div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <!-- Proposal Summary Box -->
                                    <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f9fafb; border-radius: 8px; margin-bottom: 24px;">
                                        <tr>
                                            <td style="padding: 24px;">
                                                <h3 style="margin: 0 0 8px 0; color: #111827; font-size: 18px;">
                                                    <?php echo esc_html($proposal->title); ?>
                                                </h3>
                                                
                                                <?php if ($proposal->start_date): ?>
                                                    <p style="margin: 0 0 16px 0; color: #6b7280; font-size: 14px;">
                                                        <?php esc_html_e('Starts:', 'freelance-studio'); ?> <?php echo  esc_html( date_i18n(get_option('date_format'), strtotime($proposal->start_date)) ); ?>
                                                    </p>
                                                <?php endif; ?>
                                                
                                                <p style="margin: 0; color: #111827; font-size: 28px; font-weight: 700;">
                                                    <?php echo  esc_html( FS_View_Context::format_currency($proposal->total_amount) ); ?>
                                                </p>
                                            </td>
                                        </tr>
                                    </table>
                                    
                                    <!-- CTA Button -->
                                    <table width="100%" cellpadding="0" cellspacing="0">
                                        <tr>
                                            <td align="center">
                                                <a href="<?php echo esc_url($proposal_url); ?>" style="display: inline-block; padding: 16px 32px; background-color: <?php echo esc_attr($primary_color); ?>; color: #ffffff; text-decoration: none; border-radius: 8px; font-size: 16px; font-weight: 600;">
                                                    <?php esc_html_e('View Proposal', 'freelance-studio'); ?>
                                                </a>
                                            </td>
                                        </tr>
                                    </table>
                                    
                                    <?php if ($proposal->valid_until): ?>
                                        <p style="margin: 24px 0 0 0; color: #6b7280; font-size: 14px; text-align: center;">
                                            <?php printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                                /* translators: 1. recipient name */
                                                __('This proposal is valid until %s', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                                date_i18n(get_option('date_format'), strtotime($proposal->valid_until)) // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                            ); ?>
                                        </p>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            
                            <!-- Footer -->
                            <tr>
                                <td style="padding: 24px 32px; background-color: #f9fafb; border-top: 1px solid #e5e7eb;">
                                    <p style="margin: 0; color: #6b7280; font-size: 14px; text-align: center;">
                                        <?php echo esc_html($settings['business_name']); ?>
                                        <?php if (!empty($settings['business_phone'])): ?>
                                            • <?php echo esc_html($settings['business_phone']); ?>
                                        <?php endif; ?>
                                        <?php if (!empty($settings['business_email'])): ?>
                                            • <?php echo esc_html($settings['business_email']); ?>
                                        <?php endif; ?>
                                    </p>
                                </td>
                            </tr>
                        </table>
                        
                        <p style="margin: 24px 0 0 0; color: #9ca3af; font-size: 12px; text-align: center;">
                            <?php esc_html_e('This email was sent by', 'freelance-studio'); ?> <?php echo esc_html($settings['business_name']); ?>
                        </p>
                    </td>
                </tr>
            </table>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Get proposal approved notification email HTML
     */
    private static function get_proposal_approved_email_html($proposal, $client, $settings) {
        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
        </head>
        <body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background-color: #f3f4f6;">
            <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f3f4f6; padding: 40px 20px;">
                <tr>
                    <td align="center">
                        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden;">
                            <tr>
                                <td style="padding: 32px; text-align: center; background-color: #10b981;">
                                    <h1 style="margin: 0; color: #ffffff; font-size: 24px;">✓ <?php esc_html_e('Proposal Approved!', 'freelance-studio'); ?></h1>
                                </td>
                            </tr>
                            <tr>
                                <td style="padding: 40px 32px;">
                                    <p style="margin: 0 0 16px 0; color: #4b5563; font-size: 16px;">
                                        <?php printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                            /* translators: 1. date/time */
                                            __('Great news! %s has approved your proposal.', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                            esc_html($client->company_name ?: $client->name)
                                        ); ?>
                                    </p>
                                    
                                    <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f9fafb; border-radius: 8px; margin: 24px 0;">
                                        <tr>
                                            <td style="padding: 24px;">
                                                <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;"><?php esc_html_e('Proposal', 'freelance-studio'); ?></p>
                                                <p style="margin: 0 0 16px 0; color: #111827; font-size: 18px; font-weight: 600;"><?php echo esc_html($proposal->title); ?></p>
                                                
                                                <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;"><?php esc_html_e('Client', 'freelance-studio'); ?></p>
                                                <p style="margin: 0 0 16px 0; color: #111827; font-size: 16px;"><?php echo esc_html($client->company_name ?: $client->name); ?></p>
                                                
                                                <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;"><?php esc_html_e('Signed by', 'freelance-studio'); ?></p>
                                                <p style="margin: 0 0 16px 0; color: #111827; font-size: 16px;"><?php echo esc_html($proposal->signature_client_name); ?></p>
                                                
                                                <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px;"><?php esc_html_e('Amount', 'freelance-studio'); ?></p>
                                                <p style="margin: 0; color: #111827; font-size: 24px; font-weight: 700;"><?php echo  esc_html( FS_View_Context::format_currency($proposal->total_amount) ); ?></p>
                                            </td>
                                        </tr>
                                    </table>
                                    
                                    <table width="100%" cellpadding="0" cellspacing="0">
                                        <tr>
                                            <td align="center">
                                                <a href="<?php echo esc_url(admin_url('admin.php?page=fs-proposals&action=view&id=' . $proposal->id)); ?>" style="display: inline-block; padding: 16px 32px; background-color: #2271b1; color: #ffffff; text-decoration: none; border-radius: 8px; font-size: 16px; font-weight: 600;">
                                                    <?php esc_html_e('View Proposal', 'freelance-studio'); ?>
                                                </a>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Send invoice to client
     *
     * @param int   $invoice_id   Invoice ID
     * @param array $contact_ids  Optional array of contact IDs to send to
     * @param string $custom_message Optional custom message to include in email
     * @param string $custom_subject Optional custom subject line
     * @param bool $include_primary Whether to include primary client email
     * @return bool
     */
    public static function send_invoice($invoice_id, $contact_ids = array(), $custom_message = '', $custom_subject = '', $include_primary = true, $primary_recipient = 'primary', $cc_contact_ids = array()) {
        $invoice = FS_Invoice::get($invoice_id);
        
        if (!$invoice) {
            error_log('Freelance Studio: send_invoice failed - invoice not found');
            return false;
        }
        
        $client = FS_Client::get($invoice->client_id);
        
        if (!$client) {
            error_log('Freelance Studio: send_invoice failed - client not found');
            return false;
        }
        
        // Get project if exists
        $project = null;
        if ($invoice->project_id) {
            $project = FS_Project::get($invoice->project_id);
        }
        
        // Resolve primary "To" recipient
        $to_info = self::resolve_contact_info($client, $primary_recipient);
        if (!$to_info) {
            // Fall back: try 'primary' if a contact ID failed
            $to_info = self::resolve_contact_info($client, 'primary');
        }
        if (!$to_info) {
            error_log('Freelance Studio: send_invoice failed - no valid primary recipient');
            return false;
        }
        
        $settings = self::get_business_settings();
        
        // Generate view token if not exists
        if (empty($invoice->view_token)) {
            global $wpdb;
            $view_token = wp_generate_password(32, false);
            $wpdb->update(
                $wpdb->prefix . 'fs_invoices',
                array('view_token' => $view_token),
                array('id' => $invoice_id)
            );
            $invoice->view_token = $view_token;
        }
        
        $invoice_url = home_url('?fs_invoice=' . $invoice->view_token);
        
        // Get the email template
        $template = FS_Email_Template::get('invoice_sent');
        
        // Build variable data for template processing - personalize for primary "To" recipient
        $client_name = $to_info['name'];
        $project_name = $project ? $project->name : __('N/A', 'freelance-studio');
        $current_month = date_i18n('F'); // Current month name
        
        $template_vars = array(
            '{client_name}' => $client_name,
            '{invoice_number}' => $invoice->invoice_number,
            '{amount}' => FS_View_Context::format_currency($invoice->total),
            '{due_date}' => date_i18n(get_option('date_format'), strtotime($invoice->due_date)),
            '{project_name}' => $project_name,
            '{current_month}' => $current_month,
            '{view_link}' => $invoice_url,
            '{business_name}' => $settings['business_name'],
        );
        
        // Process subject - use custom subject if provided, otherwise template subject
        if (!empty($custom_subject)) {
            $subject = FS_Email_Template::process_variables($custom_subject, $template_vars);
        } else {
            $subject = FS_Email_Template::process_variables($template['subject'] ?? '', $template_vars);
        }
        
        // Process body content - ensure it's not null
        $body_content = FS_Email_Template::process_variables($template['body'] ?? '', $template_vars);
        
        // Clean up TinyMCE artifacts (empty paragraphs, excessive whitespace)
        if (!empty($body_content)) {
            $body_content = preg_replace('/<p>\s*(&nbsp;|\xC2\xA0)?\s*<\/p>/i', '', $body_content);
            $body_content = preg_replace('/<p>\s*<br\s*\/?>\s*<\/p>/i', '', $body_content);
            $body_content = preg_replace('/(<br\s*\/?>\s*){3,}/i', '<br><br>', $body_content);
        }
        
        // Only apply nl2br if content doesn't already have paragraph tags (plain text template)
        if (!empty($body_content) && strpos($body_content, '<p>') === false && strpos($body_content, '<p ') === false) {
            $body_content = nl2br($body_content);
        }
        
        // Prepend custom message if provided (styled in italics, before main content)
        if (!empty($custom_message)) {
            // Process variables in custom message and convert line breaks to HTML
            $processed_message = FS_Email_Template::process_variables($custom_message, $template_vars);
            $processed_message = nl2br(esc_html($processed_message));
            $custom_message_html = '<div style="margin-bottom: 24px; padding-bottom: 24px; border-bottom: 1px solid #e5e7eb; font-style: italic; color: #4b5563;">' . $processed_message . '</div>';
            $body_content = $custom_message_html . $body_content;
        }
        
        // Add client dashboard link if portal is enabled
        if (!empty($client->portal_enabled) && !empty($client->portal_token)) {
            $portal_url = home_url('?fs_portal=' . $client->portal_token);
            $primary_color = get_option('fs_invoice_primary_color', '#4173B0');
            $body_content .= '<div style="margin-top: 32px; padding-top: 24px; border-top: 1px solid #e5e7eb; text-align: center;">';
            $body_content .= '<a href="' . esc_url($portal_url) . '" style="color: ' . esc_attr($primary_color) . '; text-decoration: none; font-size: 14px;">';
            $body_content .= __('View Your Client Dashboard', 'freelance-studio');
            $body_content .= '</a>';
            $body_content .= '</div>';
        }
        
        // Wrap in email template
        $message = FS_Email_Template::wrap_in_template($body_content, $subject);
        
        // Set headers
        $headers = array(
            'Content-Type: text/html; charset=UTF-8',
        );
        
        if (!empty($settings['business_email'])) {
            $from_name = !empty($settings['business_name']) ? $settings['business_name'] : get_bloginfo('name');
            $headers[] = 'From: ' . $from_name . ' <' . $settings['business_email'] . '>';
            $headers[] = 'Reply-To: ' . $from_name . ' <' . $settings['business_email'] . '>';
        }
        
        // Resolve CC recipients
        $cc_emails = array();
        foreach ($cc_contact_ids as $cc_id) {
            $cc_info = self::resolve_contact_info($client, $cc_id);
            if ($cc_info && $cc_info['email'] !== $to_info['email']) {
                $cc_emails[] = $cc_info['email'];
            }
        }
        
        // Add CC headers
        foreach ($cc_emails as $cc_email) {
            $headers[] = 'Cc: ' . $cc_email;
        }
        
        // Send single email to primary recipient with CC
        add_action('wp_mail_failed', array(__CLASS__, 'log_mail_error'));
        
        $sent = wp_mail($to_info['email'], $subject, $message, $headers);
        
        if ($sent) {
            self::log_email($to_info['email'], $subject, 'invoice', $invoice_id);
            error_log('Freelance Studio: Invoice email sent to ' . $to_info['email'] . (!empty($cc_emails) ? ' (CC: ' . implode(', ', $cc_emails) . ')' : ''));
        } else {
            error_log('Freelance Studio: Failed to send invoice email to ' . $to_info['email']);
        }
        
        remove_action('wp_mail_failed', array(__CLASS__, 'log_mail_error'));
        
        if ($sent) {
            // Update invoice sent_at
            global $wpdb;
            $wpdb->update(
                $wpdb->prefix . 'fs_invoices',
                array(
                    'sent_at' => current_time('mysql'),
                    'status' => $invoice->status === 'draft' ? 'sent' : $invoice->status
                ),
                array('id' => $invoice_id)
            );
        }
        
        return $sent;
    }

    /**
     * Send payment receipt email to client
     *
     * @param int    $invoice_id        Invoice ID
     * @param float  $amount            Payment amount recorded
     * @param string $custom_message    Optional personal message
     * @param string $custom_subject    Optional custom subject line
     * @param string $primary_recipient Primary recipient identifier ('primary' or contact ID)
     * @param array  $cc_contact_ids    CC contact identifiers
     * @return bool Whether email was sent
     */
    public static function send_payment_receipt($invoice_id, $amount = 0, $custom_message = '', $custom_subject = '', $primary_recipient = 'primary', $cc_contact_ids = array()) {
        $invoice = FS_Invoice::get($invoice_id);
        
        if (!$invoice) {
            error_log('Freelance Studio: send_payment_receipt failed - invoice not found');
            return false;
        }
        
        $client = FS_Client::get($invoice->client_id);
        
        if (!$client) {
            error_log('Freelance Studio: send_payment_receipt failed - client not found');
            return false;
        }
        
        // Resolve primary "To" recipient
        $to_info = self::resolve_contact_info($client, $primary_recipient);
        if (!$to_info) {
            $to_info = self::resolve_contact_info($client, 'primary');
        }
        if (!$to_info) {
            error_log('Freelance Studio: send_payment_receipt failed - no valid primary recipient');
            return false;
        }
        
        $settings = self::get_business_settings();
        
        // Use the payment amount or the full invoice total
        if ($amount <= 0) {
            $amount = floatval($invoice->total);
        }
        
        // Get project if exists
        $project = null;
        if ($invoice->project_id) {
            $project = FS_Project::get($invoice->project_id);
        }
        
        // Generate invoice URL for view_link
        $invoice_url = '';
        if (!empty($invoice->view_token)) {
            $invoice_url = home_url('?fs_invoice=' . $invoice->view_token);
        }
        
        // Get the email template
        $template = FS_Email_Template::get('payment_received');
        
        // Build variable data for template processing
        $client_name = $to_info['name'];
        
        $template_vars = array(
            '{client_name}' => $client_name,
            '{invoice_number}' => $invoice->invoice_number,
            '{amount}' => FS_View_Context::format_currency($amount),
            '{payment_date}' => date_i18n(get_option('date_format')),
            '{project_name}' => $project ? $project->name : __('N/A', 'freelance-studio'),
            '{view_link}' => $invoice_url,
            '{business_name}' => $settings['business_name'],
        );
        
        // Process subject
        if (!empty($custom_subject)) {
            $subject = FS_Email_Template::process_variables($custom_subject, $template_vars);
        } else {
            $subject = FS_Email_Template::process_variables($template['subject'] ?? '', $template_vars);
        }
        
        // Process body content
        $body_content = FS_Email_Template::process_variables($template['body'] ?? '', $template_vars);
        
        // Clean up TinyMCE artifacts
        if (!empty($body_content)) {
            $body_content = preg_replace('/<p>\s*(&nbsp;|\xC2\xA0)?\s*<\/p>/i', '', $body_content);
            $body_content = preg_replace('/<p>\s*<br\s*\/?>\s*<\/p>/i', '', $body_content);
            $body_content = preg_replace('/(<br\s*\/?>\s*){3,}/i', '<br><br>', $body_content);
        }
        
        // Only apply nl2br if content doesn't already have paragraph tags
        if (!empty($body_content) && strpos($body_content, '<p>') === false && strpos($body_content, '<p ') === false) {
            $body_content = nl2br($body_content);
        }
        
        // Prepend custom message if provided
        if (!empty($custom_message)) {
            $processed_message = FS_Email_Template::process_variables($custom_message, $template_vars);
            $processed_message = nl2br(esc_html($processed_message));
            $custom_message_html = '<div style="margin-bottom: 24px; padding-bottom: 24px; border-bottom: 1px solid #e5e7eb; font-style: italic; color: #4b5563;">' . $processed_message . '</div>';
            $body_content = $custom_message_html . $body_content;
        }
        
        // Add client dashboard link if portal is enabled
        if (!empty($client->portal_enabled) && !empty($client->portal_token)) {
            $portal_url = home_url('?fs_portal=' . $client->portal_token);
            $primary_color = get_option('fs_invoice_primary_color', '#4173B0');
            $body_content .= '<div style="margin-top: 32px; padding-top: 24px; border-top: 1px solid #e5e7eb; text-align: center;">';
            $body_content .= '<a href="' . esc_url($portal_url) . '" style="color: ' . esc_attr($primary_color) . '; text-decoration: none; font-size: 14px;">';
            $body_content .= __('View Your Client Dashboard', 'freelance-studio');
            $body_content .= '</a>';
            $body_content .= '</div>';
        }
        
        // Wrap in email template
        $message = FS_Email_Template::wrap_in_template($body_content, $subject);
        
        // Set headers
        $headers = array(
            'Content-Type: text/html; charset=UTF-8',
        );
        
        if (!empty($settings['business_email'])) {
            $from_name = !empty($settings['business_name']) ? $settings['business_name'] : get_bloginfo('name');
            $headers[] = 'From: ' . $from_name . ' <' . $settings['business_email'] . '>';
            $headers[] = 'Reply-To: ' . $from_name . ' <' . $settings['business_email'] . '>';
        }
        
        // Resolve CC recipients
        $cc_emails = array();
        foreach ($cc_contact_ids as $cc_id) {
            $cc_info = self::resolve_contact_info($client, $cc_id);
            if ($cc_info && $cc_info['email'] !== $to_info['email']) {
                $cc_emails[] = $cc_info['email'];
            }
        }
        
        // Add CC headers
        foreach ($cc_emails as $cc_email) {
            $headers[] = 'Cc: ' . $cc_email;
        }
        
        // Send email
        add_action('wp_mail_failed', array(__CLASS__, 'log_mail_error'));
        
        $sent = wp_mail($to_info['email'], $subject, $message, $headers);
        
        if ($sent) {
            self::log_email($to_info['email'], $subject, 'payment_receipt', $invoice_id);
            error_log('Freelance Studio: Payment receipt sent to ' . $to_info['email'] . (!empty($cc_emails) ? ' (CC: ' . implode(', ', $cc_emails) . ')' : ''));
        } else {
            error_log('Freelance Studio: Failed to send payment receipt to ' . $to_info['email']);
        }
        
        remove_action('wp_mail_failed', array(__CLASS__, 'log_mail_error'));
        
        return $sent;
    }

    /**
     * Get recipients based on client and optional contact IDs
     *
     * @param object $client      Client object
     * @param array  $contact_ids Optional specific contact IDs
     * @param bool   $include_primary Whether to include primary client email
     * @return array Array of email addresses
     */
    public static function get_recipients($client, $contact_ids = array(), $include_primary = true) {
        $recipients = array();
        
        // Add primary client email if requested
        if ($include_primary) {
            // First check for legacy client email field
            if (!empty($client->email)) {
                $recipients[] = $client->email;
            } else {
                // Look for primary contact in contacts table
                $contacts = FS_Client_Contact::get_by_client($client->id);
                foreach ($contacts as $contact) {
                    if (!empty($contact->is_primary) && !empty($contact->email)) {
                        $recipients[] = $contact->email;
                        break;
                    }
                }
            }
        }
        
        // Add specific contact emails if specified
        if (!empty($contact_ids)) {
            $contacts = FS_Client_Contact::get_by_client($client->id);
            foreach ($contacts as $contact) {
                if (in_array($contact->id, $contact_ids) && !empty($contact->email)) {
                    $recipients[] = $contact->email;
                }
            }
        }
        
        // If still no recipients, fall back to first contact with email
        if (empty($recipients)) {
            // Try legacy client email first
            if (!empty($client->email)) {
                $recipients[] = $client->email;
            } else {
                // Get first contact with an email
                $contacts = FS_Client_Contact::get_by_client($client->id);
                foreach ($contacts as $contact) {
                    if (!empty($contact->email)) {
                        $recipients[] = $contact->email;
                        break;
                    }
                }
            }
        }
        
        return array_unique($recipients);
    }

    /**
     * Resolve a contact identifier to email and name
     *
     * @param object $client         Client object
     * @param string|int $identifier 'primary' or a contact ID
     * @return array|null Array with 'email' and 'name' keys, or null if not found
     */
    public static function resolve_contact_info($client, $identifier) {
        if ($identifier === 'primary') {
            // Primary client email
            if (!empty($client->email)) {
                return array(
                    'email' => $client->email,
                    'name'  => $client->company_name ?: $client->name,
                );
            }
            // Look for primary contact in contacts table
            $contacts = FS_Client_Contact::get_by_client($client->id);
            foreach ($contacts as $contact) {
                if (!empty($contact->is_primary) && !empty($contact->email)) {
                    return array(
                        'email' => $contact->email,
                        'name'  => $contact->name ?: ($client->company_name ?: $client->name),
                    );
                }
            }
            // Fall back to first contact with email
            foreach ($contacts as $contact) {
                if (!empty($contact->email)) {
                    return array(
                        'email' => $contact->email,
                        'name'  => $contact->name ?: ($client->company_name ?: $client->name),
                    );
                }
            }
            return null;
        }

        // Numeric contact ID
        $contact_id = intval($identifier);
        if ($contact_id > 0) {
            $contacts = FS_Client_Contact::get_by_client($client->id);
            foreach ($contacts as $contact) {
                if ($contact->id == $contact_id && !empty($contact->email)) {
                    return array(
                        'email' => $contact->email,
                        'name'  => $contact->name ?: ($client->company_name ?: $client->name),
                    );
                }
            }
        }

        return null;
    }

    /**
     * Get recipients with their names for personalized emails
     *
     * @param object $client Client object
     * @param array $contact_ids Specific contact IDs to include
     * @param bool $include_primary Include primary contact
     * @return array Array of arrays with 'email' and 'name' keys
     */
    public static function get_recipients_with_info($client, $contact_ids = array(), $include_primary = true) {
        $recipients = array();
        $added_emails = array();
        
        // Get all contacts for this client
        $contacts = FS_Client_Contact::get_by_client($client->id);
        
        // Add primary contact if requested
        if ($include_primary) {
            // First check for legacy client email field
            if (!empty($client->email)) {
                $recipients[] = array(
                    'email' => $client->email,
                    'name' => $client->name ?: $client->company_name
                );
                $added_emails[] = $client->email;
            } else {
                // Look for primary contact in contacts table
                foreach ($contacts as $contact) {
                    if (!empty($contact->is_primary) && !empty($contact->email)) {
                        $recipients[] = array(
                            'email' => $contact->email,
                            'name' => $contact->name ?: $client->name ?: $client->company_name
                        );
                        $added_emails[] = $contact->email;
                        break;
                    }
                }
            }
        }
        
        // Add specific contact emails if specified
        if (!empty($contact_ids)) {
            foreach ($contacts as $contact) {
                if (in_array($contact->id, $contact_ids) && !empty($contact->email) && !in_array($contact->email, $added_emails)) {
                    $recipients[] = array(
                        'email' => $contact->email,
                        'name' => $contact->name ?: $client->name ?: $client->company_name
                    );
                    $added_emails[] = $contact->email;
                }
            }
        }
        
        // If still no recipients, fall back to first contact with email
        if (empty($recipients)) {
            // Try legacy client email first
            if (!empty($client->email)) {
                $recipients[] = array(
                    'email' => $client->email,
                    'name' => $client->name ?: $client->company_name
                );
            } else {
                // Get first contact with an email
                foreach ($contacts as $contact) {
                    if (!empty($contact->email)) {
                        $recipients[] = array(
                            'email' => $contact->email,
                            'name' => $contact->name ?: $client->name ?: $client->company_name
                        );
                        break;
                    }
                }
            }
        }
        
        return $recipients;
    }

    /**
     * Get invoice email HTML
     *
     * @param object $invoice Invoice object
     * @param object $client Client object
     * @param object|null $project Project object
     * @param array $settings Business settings
     * @param string $invoice_url URL to view invoice
     * @param string $custom_message Optional custom message
     */
    private static function get_invoice_email_html($invoice, $client, $project, $settings, $invoice_url, $custom_message = '') {
        $primary_color = !empty($settings['primary_color']) ? $settings['primary_color'] : '#4173B0';
        $client_name = $client->company_name ?: $client->name;
        
        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
        <body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background-color: #f3f4f6;">
            <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f3f4f6; padding: 40px 20px;">
                <tr>
                    <td align="center">
                        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                            <!-- Header -->
                            <tr>
                                <td style="padding: 32px; text-align: center; background-color: <?php echo esc_attr($primary_color); ?>;">
                                    <?php 
                                        // Use light logo on colored background, fall back to dark logo
                                        $email_header_logo = !empty($settings['business_logo_light']) ? $settings['business_logo_light'] : (!empty($settings['business_logo']) ? $settings['business_logo'] : '');
                                    ?>
                                    <?php if (!empty($email_header_logo)): ?>
                                        <img src="<?php echo esc_url($email_header_logo); ?>" alt="<?php echo esc_attr($settings['business_name']); ?>" style="max-width: 180px; max-height: 60px;">
                                    <?php else: ?>
                                        <h1 style="margin: 0; color: #ffffff; font-size: 24px;"><?php echo esc_html($settings['business_name']); ?></h1>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            
                            <!-- Content -->
                            <tr>
                                <td style="padding: 40px 32px;">
                                    <h2 style="margin: 0 0 16px 0; color: #111827; font-size: 24px;">
                                        <?php esc_html_e('You have a new invoice', 'freelance-studio'); ?>
                                    </h2>
                                    
                                    <p style="margin: 0 0 24px 0; color: #4b5563; font-size: 16px; line-height: 1.6;">
                                        <?php printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                            /* translators: 1. recipient name, 2. date/time */
                                            __('Hello %1$s, please find your invoice from %2$s below.', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                            esc_html($client_name),
                                            esc_html($settings['business_name'])
                                        ); ?>
                                    </p>
                                    
                                    <?php if (!empty($custom_message)): ?>
                                    <!-- Custom Message -->
                                    <div style="margin: 0 0 24px 0; padding: 16px 20px; background-color: #f9fafb; border-left: 4px solid <?php echo esc_attr($primary_color); ?>; border-radius: 0 8px 8px 0;">
                                        <div style="margin: 0; color: #374151; font-size: 15px; line-height: 1.8;"><?php echo nl2br(esc_html($custom_message)); ?></div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <!-- Invoice Details Box -->
                                    <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f9fafb; border-radius: 8px; margin-bottom: 24px;">
                                        <tr>
                                            <td style="padding: 24px;">
                                                <?php if ($project): ?>
                                                <!-- Project Name -->
                                                <div style="margin-bottom: 16px; padding-bottom: 16px; border-bottom: 1px solid #e5e7eb;">
                                                    <strong style="color: #6b7280; font-size: 12px; text-transform: uppercase;"><?php esc_html_e('Project', 'freelance-studio'); ?></strong><br>
                                                    <span style="color: #111827; font-size: 18px; font-weight: 600;"><?php echo esc_html($project->name); ?></span>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <table width="100%" cellpadding="0" cellspacing="0">
                                                    <tr>
                                                        <td style="padding-bottom: 12px;">
                                                            <strong style="color: #6b7280; font-size: 12px; text-transform: uppercase;"><?php esc_html_e('Invoice Number', 'freelance-studio'); ?></strong><br>
                                                            <span style="color: #111827; font-size: 16px;"><?php echo esc_html($invoice->invoice_number); ?></span>
                                                        </td>
                                                        <td style="padding-bottom: 12px; text-align: right;">
                                                            <strong style="color: #6b7280; font-size: 12px; text-transform: uppercase;"><?php esc_html_e('Due Date', 'freelance-studio'); ?></strong><br>
                                                            <span style="color: #111827; font-size: 16px;"><?php echo  esc_html( gmdate('M j, Y', strtotime($invoice->due_date)) ); ?></span>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td colspan="2" style="padding-top: 12px; border-top: 1px solid #e5e7eb;">
                                                            <strong style="color: #6b7280; font-size: 12px; text-transform: uppercase;"><?php esc_html_e('Amount Due', 'freelance-studio'); ?></strong><br>
                                                            <span style="color: <?php echo esc_attr($primary_color); ?>; font-size: 28px; font-weight: 700;">$<?php echo number_format($invoice->total, 2); ?></span>
                                                        </td>
                                                    </tr>
                                                </table>
                                            </td>
                                        </tr>
                                    </table>
                                    
                                    <!-- CTA Button -->
                                    <table width="100%" cellpadding="0" cellspacing="0">
                                        <tr>
                                            <td align="center">
                                                <a href="<?php echo esc_url($invoice_url); ?>" style="display: inline-block; padding: 16px 32px; background-color: <?php echo esc_attr($primary_color); ?>; color: #ffffff; text-decoration: none; border-radius: 8px; font-size: 16px; font-weight: 600;">
                                                    <?php esc_html_e('View Invoice', 'freelance-studio'); ?>
                                                </a>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                            
                            <!-- Footer -->
                            <tr>
                                <td style="padding: 24px 32px; background-color: #f9fafb; border-top: 1px solid #e5e7eb;">
                                    <p style="margin: 0; color: #6b7280; font-size: 14px; text-align: center;">
                                        <?php printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                            /* translators: 1. recipient name */
                                            __('This invoice was sent by %s', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                            esc_html($settings['business_name'])
                                        ); ?>
                                    </p>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Get unified email wrapper HTML
     * This provides consistent styling for all plugin emails
     *
     * @param string $title Email title/heading
     * @param string $content Main content HTML
     * @param array $options Optional: cta_text, cta_url, show_footer_contact, internal (true for admin emails, false for client emails)
     * @return string Complete HTML email
     */
    public static function get_email_wrapper($title, $content, $options = array()) {
        $settings = self::get_business_settings();
        $primary_color = !empty($settings['primary_color']) ? $settings['primary_color'] : '#4173B0';
        
        $cta_text = isset($options['cta_text']) ? $options['cta_text'] : '';
        $cta_url = isset($options['cta_url']) ? $options['cta_url'] : '';
        $show_footer_contact = isset($options['show_footer_contact']) ? $options['show_footer_contact'] : true;
        $is_internal = isset($options['internal']) ? $options['internal'] : false;
        
        // For external (client) emails, sign off with business name
        // For internal (admin) emails, sign off with Freelance Studio
        $signoff = $is_internal ? __('Powered by Freelance Studio', 'freelance-studio') : esc_html($settings['business_name']);
        
        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
        <body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background-color: #f3f4f6;">
            <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f3f4f6; padding: 40px 20px;">
                <tr>
                    <td align="center">
                        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                            <!-- Header -->
                            <tr>
                                <td style="padding: 32px; text-align: center; background-color: <?php echo esc_attr($primary_color); ?>;">
                                    <?php 
                                        // Use light logo on colored background, fall back to dark logo
                                        $email_header_logo = !empty($settings['business_logo_light']) ? $settings['business_logo_light'] : (!empty($settings['business_logo']) ? $settings['business_logo'] : '');
                                    ?>
                                    <?php if (!empty($email_header_logo)): ?>
                                        <img src="<?php echo esc_url($email_header_logo); ?>" alt="<?php echo esc_attr($settings['business_name']); ?>" style="max-width: 180px; max-height: 60px;">
                                    <?php else: ?>
                                        <h1 style="margin: 0; color: #ffffff; font-size: 24px;"><?php echo esc_html($settings['business_name']); ?></h1>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            
                            <!-- Content -->
                            <tr>
                                <td style="padding: 40px 32px;">
                                    <?php if ($title): ?>
                                    <h2 style="margin: 0 0 24px 0; color: #111827; font-size: 24px;">
                                        <?php echo esc_html($title); ?>
                                    </h2>
                                    <?php endif; ?>
                                    
                                    <div style="color: #4b5563; font-size: 16px; line-height: 1.6;">
                                        <?php echo wp_kses_post( $content ); ?>
                                    </div>
                                    
                                    <?php if ($cta_text && $cta_url): ?>
                                    <!-- CTA Button -->
                                    <table width="100%" cellpadding="0" cellspacing="0" style="margin-top: 24px;">
                                        <tr>
                                            <td align="center">
                                                <a href="<?php echo esc_url($cta_url); ?>" style="display: inline-block; padding: 16px 32px; background-color: <?php echo esc_attr($primary_color); ?>; color: #ffffff; text-decoration: none; border-radius: 8px; font-size: 16px; font-weight: 600;">
                                                    <?php echo esc_html($cta_text); ?>
                                                </a>
                                            </td>
                                        </tr>
                                    </table>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            
                            <!-- Footer -->
                            <tr>
                                <td style="padding: 24px 32px; background-color: #f9fafb; border-top: 1px solid #e5e7eb;">
                                    <?php if ($show_footer_contact && !$is_internal): ?>
                                    <p style="margin: 0 0 8px 0; color: #6b7280; font-size: 14px; text-align: center;">
                                        <?php echo esc_html($settings['business_name']); ?>
                                        <?php if (!empty($settings['business_phone'])): ?>
                                            • <?php echo esc_html($settings['business_phone']); ?>
                                        <?php endif; ?>
                                        <?php if (!empty($settings['business_email'])): ?>
                                            • <?php echo esc_html($settings['business_email']); ?>
                                        <?php endif; ?>
                                    </p>
                                    <?php endif; ?>
                                    <p style="margin: 0; color: #9ca3af; font-size: 12px; text-align: center;">
                                        <?php echo  esc_html( $signoff ); ?>
                                    </p>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Send a styled HTML email
     *
     * @param string $to Recipient email
     * @param string $subject Email subject
     * @param string $title Email heading
     * @param string $content Main content HTML
     * @param array $options Optional: cta_text, cta_url, show_footer_contact
     * @return bool
     */
    public static function send_styled_email($to, $subject, $title, $content, $options = array()) {
        $settings = self::get_business_settings();
        
        $message = self::get_email_wrapper($title, $content, $options);
        
        $headers = array(
            'Content-Type: text/html; charset=UTF-8',
        );
        
        if (!empty($settings['business_email'])) {
            $from_name = !empty($settings['business_name']) ? $settings['business_name'] : get_bloginfo('name');
            $headers[] = 'From: ' . $from_name . ' <' . $settings['business_email'] . '>';
            $headers[] = 'Reply-To: ' . $from_name . ' <' . $settings['business_email'] . '>';
        }
        
        // Add CC recipients if provided
        if (!empty($options['cc'])) {
            foreach ((array) $options['cc'] as $cc_email) {
                if (is_email($cc_email) && $cc_email !== $to) {
                    $headers[] = 'Cc: ' . $cc_email;
                }
            }
        }
        
        return wp_mail($to, $subject, $message, $headers);
    }

    /**
     * Send booking confirmation to guest
     *
     * @param int $booking_id Booking ID
     * @return bool
     */
    public static function send_booking_confirmation($booking_id) {
        $booking = FS_Booking::get($booking_id);
        
        if (!$booking) {
            error_log('Freelance Studio: send_booking_confirmation failed - booking not found');
            return false;
        }
        
        $meeting_type = FS_Meeting_Type::get($booking->meeting_type_id);
        $settings = self::get_business_settings();
        
        // Generate confirmation URL
        $permalink_structure = get_option('permalink_structure');
        if (empty($permalink_structure)) {
            $confirmation_url = add_query_arg('fs_booking_confirm', $booking->confirmation_token, home_url('/'));
            $cancel_url = add_query_arg('fs_booking_cancel', $booking->confirmation_token, home_url('/'));
        } else {
            $confirmation_url = home_url('/fs-booking/confirm/' . $booking->confirmation_token);
            $cancel_url = home_url('/fs-booking/cancel/' . $booking->confirmation_token);
        }
        
        // Format date/time
        $date = date_i18n(get_option('date_format'), strtotime($booking->start_datetime));
        $time = date_i18n(get_option('time_format'), strtotime($booking->start_datetime));
        $duration = FS_Meeting_Type::get_duration_display($meeting_type->duration);
        
        /* translators: 1. service name, 2. client name */
        $subject = sprintf(__('Booking Confirmed: %1$s on %2$s', 'freelance-studio'), $meeting_type->name, $date);
        
        // Build email body
        $body = '<div style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif; max-width: 600px; margin: 0 auto;">';
        $body .= '<h2 style="color: #333;">' . __('Your booking is confirmed!', 'freelance-studio') . '</h2>';
        /* translators: 1. recipient name */
        $body .= '<p>' . sprintf(__('Hi %s,', 'freelance-studio'), esc_html($booking->guest_name)) . '</p>';
        /* translators: 1. your value */
        $body .= '<p>' . sprintf(__('Your %s has been scheduled.', 'freelance-studio'), esc_html($meeting_type->name)) . '</p>';
        
        $body .= '<div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;">';
        $body .= '<p><strong>' . __('Date:', 'freelance-studio') . '</strong> ' . esc_html($date) . '</p>';
        $body .= '<p><strong>' . __('Time:', 'freelance-studio') . '</strong> ' . esc_html($time) . '</p>';
        $body .= '<p><strong>' . __('Duration:', 'freelance-studio') . '</strong> ' . esc_html($duration) . '</p>';
        if ($meeting_type->location_type) {
            $location_display = ucfirst($meeting_type->location_type);
            // If there's a Google Meet link, show it
            if (!empty($booking->meet_link)) {
                $body .= '<p><strong>' . __('Location:', 'freelance-studio') . '</strong> ' . __('Video Call', 'freelance-studio') . '</p>';
                $body .= '<p><strong>' . __('Join Meeting:', 'freelance-studio') . '</strong> <a href="' . esc_url($booking->meet_link) . '" style="color: #3ECFB2;">' . esc_html($booking->meet_link) . '</a></p>';
            } else {
                $body .= '<p><strong>' . __('Location:', 'freelance-studio') . '</strong> ' . esc_html($location_display) . '</p>';
            }
        }
        $body .= '</div>';
        
        $body .= '<p style="margin-top: 20px;">';
        $body .= '<a href="' . esc_url($confirmation_url) . '" style="display: inline-block; background: #3ECFB2; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px;">' . __('View Booking Details', 'freelance-studio') . '</a>';
        $body .= '</p>';
        
        /* translators: 1. <a href=" value */
        $body .= '<p style="color: #666; font-size: 14px;">' . sprintf(__('Need to cancel? <a href="%s">Click here</a>', 'freelance-studio'), esc_url($cancel_url)) . '</p>';
        
        $body .= '<hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">';
        $body .= '<p style="color: #999; font-size: 12px;">' . esc_html($settings['business_name']) . '</p>';
        $body .= '</div>';
        
        $headers = array('Content-Type: text/html; charset=UTF-8');
        if (!empty($settings['business_email'])) {
            $headers[] = 'From: ' . $settings['business_name'] . ' <' . $settings['business_email'] . '>';
            $headers[] = 'Reply-To: ' . $settings['business_email'];
        }
        
        // Generate .ics calendar file attachment
        $attachments = array();
        $ics_file = self::generate_booking_ics($booking, $meeting_type, $settings);
        if ($ics_file) {
            $attachments[] = $ics_file;
        }
        
        $result = wp_mail($booking->guest_email, $subject, $body, $headers, $attachments);
        
        // Clean up temporary .ics file
        if ($ics_file && file_exists($ics_file)) {
            wp_delete_file($ics_file);
        }
        
        if ($result) {
            self::log_email($booking->guest_email, $subject, 'booking_confirmation', $booking_id);
        }
        
        return $result;
    }
    
    /**
     * Generate .ics calendar file for booking
     *
     * @param object $booking Booking object
     * @param object $meeting_type Meeting type object
     * @param array $settings Business settings
     * @return string|false Path to .ics file or false on failure
     */
    private static function generate_booking_ics($booking, $meeting_type, $settings) {
        $upload_dir = wp_upload_dir();
        $ics_dir = $upload_dir['basedir'] . '/freelance-studio/ics';
        
        // Create directory if it doesn't exist
        if (!file_exists($ics_dir)) {
            wp_mkdir_p($ics_dir);
        }
        
        $filename = 'booking-' . $booking->id . '-' . time() . '.ics';
        $filepath = $ics_dir . '/' . $filename;
        
        // Format dates for iCalendar (UTC)
        $start_utc = gmdate('Ymd\THis\Z', strtotime($booking->start_datetime));
        $end_utc = gmdate('Ymd\THis\Z', strtotime($booking->end_datetime));
        $now_utc = gmdate('Ymd\THis\Z');
        
        // Build location string
        $location = '';
        if (!empty($booking->meet_link)) {
            $location = $booking->meet_link;
        } elseif ($meeting_type->location_type === 'phone') {
            $location = __('Phone Call', 'freelance-studio');
        } elseif ($meeting_type->location_type === 'video') {
            $location = __('Video Call', 'freelance-studio');
        } elseif ($meeting_type->location_type === 'in_person' && $meeting_type->location_details) {
            $location = $meeting_type->location_details;
        } elseif ($meeting_type->location_details) {
            $location = $meeting_type->location_details;
        }
        
        // Build description
        /* translators: 1. meeting with value */
        $description = sprintf(__('Meeting with %s', 'freelance-studio'), $settings['business_name']);
        if (!empty($booking->meet_link)) {
            $description .= "\\n\\n" . __('Join Meeting:', 'freelance-studio') . ' ' . $booking->meet_link;
        }
        
        // Generate UID for the event
        $uid = 'fs-booking-' . $booking->id . '@' . wp_parse_url(home_url(), PHP_URL_HOST);
        
        // Build .ics content
        $ics = "BEGIN:VCALENDAR\r\n";
        $ics .= "VERSION:2.0\r\n";
        $ics .= "PRODID:-//Freelance Studio//Booking//EN\r\n";
        $ics .= "CALSCALE:GREGORIAN\r\n";
        $ics .= "METHOD:REQUEST\r\n";
        $ics .= "BEGIN:VEVENT\r\n";
        $ics .= "UID:" . $uid . "\r\n";
        $ics .= "DTSTAMP:" . $now_utc . "\r\n";
        $ics .= "DTSTART:" . $start_utc . "\r\n";
        $ics .= "DTEND:" . $end_utc . "\r\n";
        $ics .= "SUMMARY:" . self::escape_ics_text($meeting_type->name . ' - ' . $settings['business_name']) . "\r\n";
        $ics .= "DESCRIPTION:" . self::escape_ics_text($description) . "\r\n";
        if ($location) {
            $ics .= "LOCATION:" . self::escape_ics_text($location) . "\r\n";
        }
        if (!empty($settings['business_email'])) {
            $ics .= "ORGANIZER;CN=" . self::escape_ics_text($settings['business_name']) . ":mailto:" . $settings['business_email'] . "\r\n";
        }
        $ics .= "ATTENDEE;PARTSTAT=ACCEPTED;CN=" . self::escape_ics_text($booking->guest_name) . ":mailto:" . $booking->guest_email . "\r\n";
        $ics .= "STATUS:CONFIRMED\r\n";
        $ics .= "SEQUENCE:0\r\n";
        $ics .= "END:VEVENT\r\n";
        $ics .= "END:VCALENDAR\r\n";
        
        // Write to file
        if (file_put_contents($filepath, $ics) !== false) {
            return $filepath;
        }
        
        return false;
    }
    
    /**
     * Escape text for iCalendar format
     *
     * @param string $text Text to escape
     * @return string Escaped text
     */
    private static function escape_ics_text($text) {
        $text = str_replace('\\', '\\\\', $text);
        $text = str_replace(',', '\\,', $text);
        $text = str_replace(';', '\\;', $text);
        $text = str_replace("\n", '\\n', $text);
        $text = str_replace("\r", '', $text);
        return $text;
    }

    /**
     * Send new booking notification to business owner
     *
     * @param int $booking_id Booking ID
     * @return bool
     */
    public static function send_booking_notification_to_owner($booking_id) {
        $booking = FS_Booking::get($booking_id);
        
        if (!$booking) {
            error_log('Freelance Studio: send_booking_notification_to_owner failed - booking not found');
            return false;
        }
        
        $meeting_type = FS_Meeting_Type::get($booking->meeting_type_id);
        $settings = self::get_business_settings();
        
        // Send to business email
        $owner_email = $settings['business_email'];
        if (empty($owner_email)) {
            $owner_email = get_option('admin_email');
        }
        
        // Format date/time
        $date = date_i18n(get_option('date_format'), strtotime($booking->start_datetime));
        $time = date_i18n(get_option('time_format'), strtotime($booking->start_datetime));
        $duration = FS_Meeting_Type::get_duration_display($meeting_type->duration);
        
        /* translators: 1. new booking value, 2. with value, 3. date/time */
        $subject = sprintf(__('New Booking: %1$s with %2$s on %3$s', 'freelance-studio'), $meeting_type->name, $booking->guest_name, $date);
        
        // Build email body
        $body = '<div style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif; max-width: 600px; margin: 0 auto;">';
        $body .= '<h2 style="color: #333;">' . __('New Booking Received!', 'freelance-studio') . '</h2>';
        /* translators: 1. a new value */
        $body .= '<p>' . sprintf(__('You have a new %s booking.', 'freelance-studio'), esc_html($meeting_type->name)) . '</p>';
        
        $body .= '<div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;">';
        $body .= '<h3 style="margin-top: 0; color: #333;">' . __('Guest Details', 'freelance-studio') . '</h3>';
        $body .= '<p><strong>' . __('Name:', 'freelance-studio') . '</strong> ' . esc_html($booking->guest_name) . '</p>';
        $body .= '<p><strong>' . __('Email:', 'freelance-studio') . '</strong> <a href="mailto:' . esc_attr($booking->guest_email) . '">' . esc_html($booking->guest_email) . '</a></p>';
        if ($booking->guest_phone) {
            $body .= '<p><strong>' . __('Phone:', 'freelance-studio') . '</strong> ' . esc_html($booking->guest_phone) . '</p>';
        }
        $body .= '</div>';
        
        $body .= '<div style="background: #e8f5f3; padding: 20px; border-radius: 8px; margin: 20px 0;">';
        $body .= '<h3 style="margin-top: 0; color: #333;">' . __('Meeting Details', 'freelance-studio') . '</h3>';
        $body .= '<p><strong>' . __('Type:', 'freelance-studio') . '</strong> ' . esc_html($meeting_type->name) . '</p>';
        $body .= '<p><strong>' . __('Date:', 'freelance-studio') . '</strong> ' . esc_html($date) . '</p>';
        $body .= '<p><strong>' . __('Time:', 'freelance-studio') . '</strong> ' . esc_html($time) . '</p>';
        $body .= '<p><strong>' . __('Duration:', 'freelance-studio') . '</strong> ' . esc_html($duration) . '</p>';
        if ($meeting_type->location_type) {
            $location_display = ucfirst($meeting_type->location_type);
            if (!empty($booking->meet_link)) {
                $body .= '<p><strong>' . __('Location:', 'freelance-studio') . '</strong> ' . __('Video Call', 'freelance-studio') . '</p>';
                $body .= '<p><strong>' . __('Google Meet:', 'freelance-studio') . '</strong> <a href="' . esc_url($booking->meet_link) . '" style="color: #3ECFB2;">' . esc_html($booking->meet_link) . '</a></p>';
            } else {
                $body .= '<p><strong>' . __('Location:', 'freelance-studio') . '</strong> ' . esc_html($location_display) . '</p>';
            }
        }
        $body .= '</div>';
        
        if ($booking->notes) {
            $body .= '<div style="background: #fff8e1; padding: 20px; border-radius: 8px; margin: 20px 0;">';
            $body .= '<h3 style="margin-top: 0; color: #333;">' . __('Notes from Guest', 'freelance-studio') . '</h3>';
            $body .= '<p>' . nl2br(esc_html($booking->notes)) . '</p>';
            $body .= '</div>';
        }
        
        $admin_url = admin_url('admin.php?page=fs-bookings&action=view&id=' . $booking_id);
        $body .= '<p style="margin-top: 20px;">';
        $body .= '<a href="' . esc_url($admin_url) . '" style="display: inline-block; background: #3ECFB2; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px;">' . __('View in Dashboard', 'freelance-studio') . '</a>';
        $body .= '</p>';
        
        $body .= '<hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">';
        $body .= '<p style="color: #999; font-size: 12px;">' . __('This notification was sent by Freelance Studio.', 'freelance-studio') . '</p>';
        $body .= '</div>';
        
        $headers = array('Content-Type: text/html; charset=UTF-8');
        
        // Use the actual WordPress admin email as the From address for better deliverability
        // Using fabricated addresses like notifications@domain.com often fails SPF/DKIM checks
        $from_email = get_option('admin_email');
        $from_name = sanitize_text_field($settings['business_name']);
        
        // Only set From header if it's different from the recipient to avoid "sending to yourself" issues
        // Most mail servers handle this fine, but some don't
        if ($from_email !== $owner_email) {
            $headers[] = 'From: ' . $from_name . ' <' . $from_email . '>';
        }
        
        // Set Reply-To as the guest's email so owner can easily reply to them
        if (!empty($booking->guest_email)) {
            $headers[] = 'Reply-To: ' . $booking->guest_name . ' <' . $booking->guest_email . '>';
        }
        
        $result = wp_mail($owner_email, $subject, $body, $headers);
        
        if ($result) {
            self::log_email($owner_email, $subject, 'booking_notification', $booking_id);
        }
        
        return $result;
    }

    /**
     * Send booking cancellation notification
     *
     * @param int $booking_id Booking ID
     * @param string $cancelled_by 'guest' or 'owner'
     * @return bool
     */
    public static function send_booking_cancellation($booking_id, $cancelled_by = 'guest') {
        $booking = FS_Booking::get($booking_id);
        
        if (!$booking) {
            return false;
        }
        
        $meeting_type = FS_Meeting_Type::get($booking->meeting_type_id);
        $settings = self::get_business_settings();
        
        $date = date_i18n(get_option('date_format'), strtotime($booking->start_datetime));
        $time = date_i18n(get_option('time_format'), strtotime($booking->start_datetime));
        
        // If cancelled by guest, notify owner
        if ($cancelled_by === 'guest') {
            $owner_email = $settings['business_email'] ?: get_option('admin_email');
            /* translators: 1. service name, 2. client name, 3. date */
            $subject = sprintf(__('Booking Cancelled: %1$s with %2$s on %3$s', 'freelance-studio'), $meeting_type->name, $booking->guest_name, $date);
            
            $body = '<div style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif; max-width: 600px; margin: 0 auto;">';
            $body .= '<h2 style="color: #E85A5A;">' . __('Booking Cancelled', 'freelance-studio') . '</h2>';
            /* translators: 1. has cancelled value, 2. cancelled their value */
            $body .= '<p>' . sprintf(__('%1$s has cancelled their %2$s booking.', 'freelance-studio'), esc_html($booking->guest_name), esc_html($meeting_type->name)) . '</p>';
            $body .= '<div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;">';
            $body .= '<p><strong>' . __('Date:', 'freelance-studio') . '</strong> ' . esc_html($date) . '</p>';
            $body .= '<p><strong>' . __('Time:', 'freelance-studio') . '</strong> ' . esc_html($time) . '</p>';
            $body .= '</div>';
            $body .= '</div>';
            
            $headers = array('Content-Type: text/html; charset=UTF-8');
            wp_mail($owner_email, $subject, $body, $headers);
        }
        
        // If cancelled by owner, notify guest
        if ($cancelled_by === 'owner') {
            /* translators: 1. date/time */
            $subject = sprintf(__('Your booking on %s has been cancelled', 'freelance-studio'), $date);
            
            $body = '<div style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif; max-width: 600px; margin: 0 auto;">';
            $body .= '<h2 style="color: #E85A5A;">' . __('Booking Cancelled', 'freelance-studio') . '</h2>';
            /* translators: 1. recipient name */
            $body .= '<p>' . sprintf(__('Hi %s,', 'freelance-studio'), esc_html($booking->guest_name)) . '</p>';
            /* translators: 1. your value, 2. date/time, 3. date/time */
            $body .= '<p>' . sprintf(__('Your %1$s booking on %2$s at %3$s has been cancelled.', 'freelance-studio'), esc_html($meeting_type->name), esc_html($date), esc_html($time)) . '</p>';
            $body .= '<p>' . __('If you have any questions, please contact us.', 'freelance-studio') . '</p>';
            $body .= '<hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">';
            $body .= '<p style="color: #999; font-size: 12px;">' . esc_html($settings['business_name']) . '</p>';
            $body .= '</div>';
            
            $headers = array('Content-Type: text/html; charset=UTF-8');
            if (!empty($settings['business_email'])) {
                $headers[] = 'From: ' . $settings['business_name'] . ' <' . $settings['business_email'] . '>';
            }
            
            wp_mail($booking->guest_email, $subject, $body, $headers);
        }
        
        return true;
    }

    /**
     * Log email
     */
    /**
     * Send notification to freelancer when client requests a task
     *
     * @param object $task Task object
     * @param object $client Client object
     * @return bool
     */
    public static function send_task_request_notification($task, $client) {
        $settings = self::get_business_settings();
        
        if (empty($settings['business_email'])) {
            return false;
        }
        
        $client_name = $client->company_name ?: $client->name;
        $project_name = !empty($task->project_name) ? $task->project_name : __('No Project', 'freelance-studio');
        $priority_labels = FS_Task::get_priorities();
        $priority_label = isset($priority_labels[$task->priority]) ? $priority_labels[$task->priority] : $task->priority;
        
        $subject = sprintf(
            /* translators: 1. date/time */
            __('New Task Request from %s', 'freelance-studio'),
            $client_name
        );
        
        $content = '<p>' . sprintf(
            /* translators: 1. has requested value */
            __('%s has requested a new task:', 'freelance-studio'),
            '<strong>' . esc_html($client_name) . '</strong>'
        ) . '</p>';
        
        $content .= '<table style="width:100%; border-collapse:collapse; margin: 16px 0;">';
        $content .= '<tr><td style="padding:8px 12px; border-bottom:1px solid #e5e7eb; color:#6b7280; width:120px;">' . __('Task', 'freelance-studio') . '</td>';
        $content .= '<td style="padding:8px 12px; border-bottom:1px solid #e5e7eb; font-weight:600;">' . esc_html($task->title) . '</td></tr>';
        
        if (!empty($task->description)) {
            $content .= '<tr><td style="padding:8px 12px; border-bottom:1px solid #e5e7eb; color:#6b7280;">' . __('Description', 'freelance-studio') . '</td>';
            $content .= '<td style="padding:8px 12px; border-bottom:1px solid #e5e7eb;">' . nl2br(esc_html($task->description)) . '</td></tr>';
        }
        
        $content .= '<tr><td style="padding:8px 12px; border-bottom:1px solid #e5e7eb; color:#6b7280;">' . __('Project', 'freelance-studio') . '</td>';
        $content .= '<td style="padding:8px 12px; border-bottom:1px solid #e5e7eb;">' . esc_html($project_name) . '</td></tr>';
        
        $content .= '<tr><td style="padding:8px 12px; border-bottom:1px solid #e5e7eb; color:#6b7280;">' . __('Priority', 'freelance-studio') . '</td>';
        $content .= '<td style="padding:8px 12px; border-bottom:1px solid #e5e7eb;">' . esc_html($priority_label) . '</td></tr>';
        
        if (!empty($task->due_date)) {
            $content .= '<tr><td style="padding:8px 12px; border-bottom:1px solid #e5e7eb; color:#6b7280;">' . __('Requested Due Date', 'freelance-studio') . '</td>';
            $content .= '<td style="padding:8px 12px; border-bottom:1px solid #e5e7eb;">' . date_i18n(get_option('date_format'), strtotime($task->due_date)) . '</td></tr>';
        }
        
        $content .= '</table>';
        
        $content .= '<p style="color:#6b7280;">' . __('You can review and accept this request from your Tasks board.', 'freelance-studio') . '</p>';
        
        $tasks_url = admin_url('admin.php?page=fs-tasks&view=kanban');
        
        $result = self::send_styled_email(
            $settings['business_email'],
            $subject,
            __('New Task Request', 'freelance-studio'),
            $content,
            array(
                'cta_text' => __('View Tasks', 'freelance-studio'),
                'cta_url' => $tasks_url,
                'internal' => true,
            )
        );
        
        if ($result) {
            self::log_email($settings['business_email'], $subject, 'task_request', $task->id);
        }
        
        return $result;
    }

    /**
     * Send notification to client when their task request is accepted
     *
     * @param object $task Task object
     * @param object $client Client object
     * @return bool
     */
    public static function send_task_request_accepted($task, $client) {
        $settings = self::get_business_settings();
        
        if (empty($client->email)) {
            return false;
        }
        
        $business_name = !empty($settings['business_name']) ? $settings['business_name'] : get_bloginfo('name');
        
        $subject = sprintf(
            /* translators: 1. accepted — value */
            __('Your task request has been accepted — %s', 'freelance-studio'),
            $task->title
        );
        
        $content = '<p>' . sprintf(
            /* translators: 1. date/time */
            __('Great news! %s has accepted your task request:', 'freelance-studio'),
            '<strong>' . esc_html($business_name) . '</strong>'
        ) . '</p>';
        
        $content .= '<div style="background:#f0fdf4; border-left:4px solid #22c55e; padding:16px; border-radius:4px; margin:16px 0;">';
        $content .= '<p style="margin:0; font-weight:600; color:#166534;">' . esc_html($task->title) . '</p>';
        if (!empty($task->description)) {
            $content .= '<p style="margin:8px 0 0; color:#4b5563;">' . esc_html($task->description) . '</p>';
        }
        $content .= '</div>';
        
        $content .= '<p style="color:#6b7280;">' . __('You can track the progress of this task in your client portal.', 'freelance-studio') . '</p>';
        
        // Build portal URL
        $portal_url = '';
        if (!empty($client->portal_token)) {
            $portal_url = home_url('?fs_portal=' . $client->portal_token);
        }
        
        $options = array();
        if ($portal_url) {
            $options['cta_text'] = __('View Portal', 'freelance-studio');
            $options['cta_url'] = $portal_url;
        }
        
        $result = self::send_styled_email(
            $client->email,
            $subject,
            __('Task Request Accepted', 'freelance-studio'),
            $content,
            $options
        );
        
        if ($result) {
            self::log_email($client->email, $subject, 'task_accepted', $task->id);
        }
        
        return $result;
    }

    public static function log_email($recipient, $subject, $type, $related_id) {
        global $wpdb;
        
        $table = $wpdb->prefix . 'fs_email_log';
        
        // Check if table exists
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$table}'") === $table;
        if (!$table_exists) {
            return;
        }
        
        $wpdb->insert(
            $table,
            array(
                'recipient' => $recipient,
                'subject' => $subject,
                'type' => $type,
                'related_type' => $type,
                'related_id' => $related_id,
                'sent_at' => current_time('mysql'),
                'status' => 'sent'
            )
        );
    }

    /**
     * Get business settings
     */
    private static function get_business_settings() {
        $primary_color = get_option('fs_invoice_primary_color', '');
        if (empty($primary_color) || $primary_color === '#000000') {
            $primary_color = '#4173B0'; // Default color
        }
        
        return array(
            'business_name' => get_option('fs_business_name', get_bloginfo('name')),
            'business_email' => get_option('fs_business_email', get_option('admin_email')),
            'business_phone' => get_option('fs_business_phone', ''),
            'business_logo' => get_option('fs_business_logo', ''),
            'business_logo_light' => get_option('fs_business_logo_light', ''),
            'business_address' => get_option('fs_business_address', ''),
            'business_city' => get_option('fs_business_city', ''),
            'business_state' => get_option('fs_business_state', ''),
            'business_zip' => get_option('fs_business_zip', ''),
            'primary_color' => $primary_color,
        );
    }
}
