<?php
/**
 * Email Template Model
 * Handles customizable email templates
 *
 * @package Freelance_Studio
 */

class FS_Email_Template {
    
    /**
     * Available template types
     */
    public static function get_template_types() {
        return array(
            'invoice_sent' => array(
                'label' => __('Invoice Sent', 'freelance-studio'),
                'description' => __('Email sent when an invoice is delivered to a client', 'freelance-studio'),
                'variables' => array(
                    '{client_name}' => __('Client name or company', 'freelance-studio'),
                    '{invoice_number}' => __('Invoice number', 'freelance-studio'),
                    '{amount}' => __('Invoice total amount', 'freelance-studio'),
                    '{due_date}' => __('Payment due date', 'freelance-studio'),
                    '{project_name}' => __('Associated project name', 'freelance-studio'),
                    '{current_month}' => __('Current month name', 'freelance-studio'),
                    '{view_link}' => __('Link to view invoice', 'freelance-studio'),
                    '{business_name}' => __('Your business name', 'freelance-studio'),
                ),
            ),
            'payment_reminder' => array(
                'label' => __('Payment Reminder', 'freelance-studio'),
                'description' => __('Friendly reminder before an invoice is due', 'freelance-studio'),
                'variables' => array(
                    '{client_name}' => __('Client name or company', 'freelance-studio'),
                    '{invoice_number}' => __('Invoice number', 'freelance-studio'),
                    '{amount}' => __('Invoice total amount', 'freelance-studio'),
                    '{due_date}' => __('Payment due date', 'freelance-studio'),
                    '{days_until_due}' => __('Days until due', 'freelance-studio'),
                    '{project_name}' => __('Associated project name', 'freelance-studio'),
                    '{current_month}' => __('Current month name', 'freelance-studio'),
                    '{view_link}' => __('Link to view invoice', 'freelance-studio'),
                    '{business_name}' => __('Your business name', 'freelance-studio'),
                ),
            ),
            'payment_overdue' => array(
                'label' => __('Payment Overdue', 'freelance-studio'),
                'description' => __('Notice sent when payment is past due', 'freelance-studio'),
                'variables' => array(
                    '{client_name}' => __('Client name or company', 'freelance-studio'),
                    '{invoice_number}' => __('Invoice number', 'freelance-studio'),
                    '{amount}' => __('Invoice total amount', 'freelance-studio'),
                    '{due_date}' => __('Original due date', 'freelance-studio'),
                    '{days_overdue}' => __('Days past due', 'freelance-studio'),
                    '{view_link}' => __('Link to view invoice', 'freelance-studio'),
                    '{business_name}' => __('Your business name', 'freelance-studio'),
                ),
            ),
            'proposal_sent' => array(
                'label' => __('Proposal Sent', 'freelance-studio'),
                'description' => __('Email sent when a proposal is delivered', 'freelance-studio'),
                'variables' => array(
                    '{client_name}' => __('Client name or company', 'freelance-studio'),
                    '{proposal_title}' => __('Proposal title', 'freelance-studio'),
                    '{amount}' => __('Proposal total', 'freelance-studio'),
                    '{project_name}' => __('Associated project name', 'freelance-studio'),
                    '{current_month}' => __('Current month name', 'freelance-studio'),
                    '{view_link}' => __('Link to view proposal', 'freelance-studio'),
                    '{business_name}' => __('Your business name', 'freelance-studio'),
                ),
            ),
            'contract_sent' => array(
                'label' => __('Contract Sent', 'freelance-studio'),
                'description' => __('Email sent when a contract requires signature', 'freelance-studio'),
                'variables' => array(
                    '{client_name}' => __('Client name or company', 'freelance-studio'),
                    '{contract_title}' => __('Contract title', 'freelance-studio'),
                    '{expires_date}' => __('Contract expiration date', 'freelance-studio'),
                    '{project_name}' => __('Associated project name', 'freelance-studio'),
                    '{current_month}' => __('Current month name', 'freelance-studio'),
                    '{view_link}' => __('Link to view/sign contract', 'freelance-studio'),
                    '{business_name}' => __('Your business name', 'freelance-studio'),
                ),
            ),
            'payment_received' => array(
                'label' => __('Payment Received', 'freelance-studio'),
                'description' => __('Thank you email sent when payment is received', 'freelance-studio'),
                'variables' => array(
                    '{client_name}' => __('Client name or company', 'freelance-studio'),
                    '{invoice_number}' => __('Invoice number', 'freelance-studio'),
                    '{amount}' => __('Payment amount', 'freelance-studio'),
                    '{payment_date}' => __('Date payment was recorded', 'freelance-studio'),
                    '{project_name}' => __('Associated project name', 'freelance-studio'),
                    '{view_link}' => __('Link to view invoice', 'freelance-studio'),
                    '{business_name}' => __('Your business name', 'freelance-studio'),
                ),
            ),
            'quarterly_tax_reminder' => array(
                'label' => __('Quarterly Tax Reminder', 'freelance-studio'),
                'description' => __('Reminder sent to yourself before quarterly tax deadlines', 'freelance-studio'),
                'variables' => array(
                    '{quarter}' => __('Quarter name (Q1, Q2, Q3, Q4)', 'freelance-studio'),
                    '{deadline}' => __('Payment deadline date', 'freelance-studio'),
                    '{days_until}' => __('Days until deadline', 'freelance-studio'),
                    '{recommended_amount}' => __('Recommended payment amount', 'freelance-studio'),
                    '{ytd_income}' => __('Year-to-date income', 'freelance-studio'),
                    '{total_paid}' => __('Total paid so far this year', 'freelance-studio'),
                    '{business_name}' => __('Your business name', 'freelance-studio'),
                ),
            ),
        );
    }

    /**
     * Get a template
     *
     * @param string $type Template type
     * @return array Template data with subject and body
     */
    public static function get($type) {
        $saved = get_option('fs_email_template_' . $type, array());
        $defaults = self::get_defaults();
        
        if (isset($defaults[$type])) {
            return array(
                'subject' => isset($saved['subject']) && !empty($saved['subject']) 
                    ? $saved['subject'] 
                    : $defaults[$type]['subject'],
                'body' => isset($saved['body']) && !empty($saved['body']) 
                    ? $saved['body'] 
                    : $defaults[$type]['body'],
                'is_custom' => !empty($saved['subject']) || !empty($saved['body']),
            );
        }
        
        return array(
            'subject' => '',
            'body' => '',
            'is_custom' => false,
        );
    }

    /**
     * Save a template
     *
     * @param string $type    Template type
     * @param string $subject Email subject
     * @param string $body    Email body (HTML)
     * @return bool
     */
    public static function save($type, $subject, $body) {
        // Use wp_kses_post which allows standard post HTML and preserves newlines
        // wp_unslash is needed because WordPress adds magic quotes to $_POST data
        $sanitized_body = wp_kses_post(wp_unslash($body));
        
        return update_option('fs_email_template_' . $type, array(
            'subject' => sanitize_text_field(wp_unslash($subject)),
            'body' => $sanitized_body,
        ));
    }

    /**
     * Reset a template to default
     *
     * @param string $type Template type
     * @return bool
     */
    public static function reset($type) {
        return delete_option('fs_email_template_' . $type);
    }

    /**
     * Get default templates
     *
     * @return array
     */
    public static function get_defaults() {
        return array(
            'invoice_sent' => array(
                'subject' => __('Invoice {invoice_number} from {business_name}', 'freelance-studio'),
                'body' => self::get_default_invoice_sent_body(),
            ),
            'payment_reminder' => array(
                'subject' => __('Friendly Reminder: Invoice {invoice_number} due in {days_until_due} days', 'freelance-studio'),
                'body' => self::get_default_payment_reminder_body(),
            ),
            'payment_overdue' => array(
                'subject' => __('Invoice {invoice_number} is {days_overdue} days overdue', 'freelance-studio'),
                'body' => self::get_default_payment_overdue_body(),
            ),
            'proposal_sent' => array(
                'subject' => __('Proposal: {proposal_title} from {business_name}', 'freelance-studio'),
                'body' => self::get_default_proposal_sent_body(),
            ),
            'contract_sent' => array(
                'subject' => __('Contract Ready for Signature: {contract_title}', 'freelance-studio'),
                'body' => self::get_default_contract_sent_body(),
            ),
            'payment_received' => array(
                'subject' => __('Payment Received - Thank You!', 'freelance-studio'),
                'body' => self::get_default_payment_received_body(),
            ),
            'quarterly_tax_reminder' => array(
                'subject' => __('Reminder: {quarter} Estimated Tax Payment Due {deadline}', 'freelance-studio'),
                'body' => self::get_default_quarterly_tax_reminder_body(),
            ),
        );
    }

    /**
     * Process template variables
     *
     * @param string $content Template content
     * @param array  $data    Variable data
     * @return string
     */
    public static function process_variables($content, $data) {
        // Handle null or empty content
        if ($content === null || $content === '') {
            return '';
        }
        foreach ($data as $key => $value) {
            // Ensure value is a string to avoid PHP 8.1+ deprecation warnings
            $content = str_replace($key, (string) $value, $content);
        }
        return $content;
    }

    /**
     * Default invoice sent body
     */
    private static function get_default_invoice_sent_body() {
        return '<p>Hello {client_name},</p>
<p>Please find your invoice from {business_name} below.</p>
<table style="margin: 20px 0; border-collapse: collapse;">
<tr><td style="padding: 8px 0;"><strong>Invoice:</strong></td><td style="padding: 8px 0 8px 15px;">{invoice_number}</td></tr>
<tr><td style="padding: 8px 0;"><strong>Amount Due:</strong></td><td style="padding: 8px 0 8px 15px;">{amount}</td></tr>
<tr><td style="padding: 8px 0;"><strong>Due Date:</strong></td><td style="padding: 8px 0 8px 15px;">{due_date}</td></tr>
</table>
<p style="margin: 25px 0;"><a href="{view_link}" style="display: inline-block; padding: 12px 24px; background-color: #4173B0; color: #ffffff; text-decoration: none; border-radius: 6px;">View Invoice</a></p>
<p>Thank you for your business!</p>
<p>Best regards,<br>{business_name}</p>';
    }

    /**
     * Default payment reminder body
     */
    private static function get_default_payment_reminder_body() {
        return '<p>Hello {client_name},</p>
<p>This is a friendly reminder that invoice {invoice_number} for {amount} is due in {days_until_due} days on {due_date}.</p>
<p style="margin: 25px 0;"><a href="{view_link}" style="display: inline-block; padding: 12px 24px; background-color: #4173B0; color: #ffffff; text-decoration: none; border-radius: 6px;">View &amp; Pay Invoice</a></p>
<p>If you have already sent payment, please disregard this notice.</p>
<p>Thank you,<br>{business_name}</p>';
    }

    /**
     * Default payment overdue body
     */
    private static function get_default_payment_overdue_body() {
        return '<p>Hello {client_name},</p>
<p>Our records indicate that invoice {invoice_number} for {amount} is now {days_overdue} days past due. The original due date was {due_date}.</p>
<p>Please remit payment at your earliest convenience to avoid any late fees.</p>
<p style="margin: 25px 0;"><a href="{view_link}" style="display: inline-block; padding: 12px 24px; background-color: #c53030; color: #ffffff; text-decoration: none; border-radius: 6px;">View &amp; Pay Invoice</a></p>
<p>If you have any questions about this invoice or have already sent payment, please contact us.</p>
<p>Thank you,<br>{business_name}</p>';
    }

    /**
     * Default proposal sent body
     */
    private static function get_default_proposal_sent_body() {
        return <<<'HTML'
<p>Hello {client_name},</p>
<p>Thank you for the opportunity to work together. Please find our proposal for {proposal_title} attached.</p>
<p><strong>Proposed Total:</strong> {amount}</p>
<p style="margin: 25px 0;"><a href="{view_link}" style="display: inline-block; padding: 12px 24px; background-color: #4173B0; color: #ffffff; text-decoration: none; border-radius: 6px;">View Proposal</a></p>
<p>Please review the proposal at your convenience. If you have any questions or would like to discuss modifications, don't hesitate to reach out.</p>
<p>Looking forward to working with you!</p>
<p>Best regards,<br>{business_name}</p>
HTML;
    }

    /**
     * Default contract sent body
     */
    private static function get_default_contract_sent_body() {
        return <<<'HTML'
<p>Hello {client_name},</p>
<p>Your contract for {contract_title} is ready for review and signature.</p>
<p>Please review the terms carefully. This offer expires on {expires_date}.</p>
<p style="margin: 25px 0;"><a href="{view_link}" style="display: inline-block; padding: 12px 24px; background-color: #4173B0; color: #ffffff; text-decoration: none; border-radius: 6px;">Review &amp; Sign Contract</a></p>
<p>If you have any questions, please don't hesitate to contact us.</p>
<p>Best regards,<br>{business_name}</p>
HTML;
    }

    /**
     * Default payment received body
     */
    private static function get_default_payment_received_body() {
        return '<p>Hello {client_name},</p>
<p>Thank you! We have received your payment of {amount} for invoice {invoice_number}.</p>
<p><strong>Payment Date:</strong> {payment_date}</p>
<p>We appreciate your prompt payment and look forward to continuing to work with you.</p>
<p>Best regards,<br>{business_name}</p>';
    }

    /**
     * Default quarterly tax reminder body
     */
    private static function get_default_quarterly_tax_reminder_body() {
        return '<p>Hi there,</p>
<p>This is a reminder that your <strong>{quarter} estimated tax payment</strong> is due in <strong>{days_until} days</strong> on <strong>{deadline}</strong>.</p>
<table style="margin: 20px 0; border-collapse: collapse; background: #f9fafb; border-radius: 8px;">
<tr><td style="padding: 12px 15px;"><strong>Recommended Payment:</strong></td><td style="padding: 12px 15px; font-size: 18px; color: #059669;">{recommended_amount}</td></tr>
<tr><td style="padding: 12px 15px;"><strong>YTD Income:</strong></td><td style="padding: 12px 15px;">{ytd_income}</td></tr>
<tr><td style="padding: 12px 15px;"><strong>Already Paid This Year:</strong></td><td style="padding: 12px 15px;">{total_paid}</td></tr>
</table>
<p><strong>Payment Options:</strong></p>
<ul>
<li>IRS Direct Pay: <a href="https://www.irs.gov/payments/direct-pay">irs.gov/payments/direct-pay</a></li>
<li>EFTPS: <a href="https://www.eftps.gov">eftps.gov</a></li>
<li>Mail check with Form 1040-ES</li>
</ul>
<p style="color: #6b7280; font-size: 14px;"><em>Note: This is an automated reminder from Freelance Studio. The recommended amount is an estimate based on your tracked income and may not reflect your actual tax liability. Please consult with your tax professional for accurate payment amounts.</em></p>
<p>Best regards,<br>{business_name}</p>';
    }

    /**
     * Wrap content in email HTML wrapper
     *
     * @param string $content   Body content
     * @param string $preheader Preview text for email clients
     * @param bool   $internal  True for admin emails, false for client emails
     * @return string
     */
    public static function wrap_in_template($content, $preheader = '', $internal = false) {
        // Handle null content
        if ($content === null) {
            $content = '';
        }
        
        $primary_color = get_option('fs_invoice_primary_color', '');
        if (empty($primary_color)) {
            $primary_color = '#4173B0';
        }
        
        $settings = array(
            'business_name' => get_option('fs_business_name', get_bloginfo('name')),
            'business_logo' => get_option('fs_business_logo', ''),
            'business_logo_light' => get_option('fs_business_logo_light', ''),
            'primary_color' => $primary_color,
        );
        
        // For external (client) emails, sign off with business name
        // For internal (admin) emails, sign off with Freelance Studio
        $signoff = $internal ? __('Powered by Freelance Studio', 'freelance-studio') : esc_html($settings['business_name']);
        
        // If content has no block-level elements at all, wrap in a basic paragraph
        // (This handles edge cases where content is just plain text without any HTML)
        $has_block_elements = (
            strpos($content, '<p') !== false || 
            strpos($content, '<div') !== false || 
            strpos($content, '<br') !== false ||
            strpos($content, '<table') !== false
        );
        
        if (!$has_block_elements) {
            $content = '<p style="margin: 0 0 16px 0;">' . nl2br($content) . '</p>';
        }
        
        // Replace button background colors with primary color
        // Match common button patterns: background-color: #XXXXXX or background: #XXXXXX
        $content = preg_replace(
            '/(<a[^>]*style="[^"]*)(background-color:\s*#[0-9a-fA-F]{3,6})([^"]*"[^>]*>)/i',
            '$1background-color: ' . esc_attr($primary_color) . '$3',
            $content
        );
        $content = preg_replace(
            '/(<a[^>]*style="[^"]*)(background:\s*#[0-9a-fA-F]{3,6})([^"]*"[^>]*>)/i',
            '$1background: ' . esc_attr($primary_color) . '$3',
            $content
        );
        
        // Ensure links have proper styling
        $content = preg_replace(
            '/<a\s+href="([^"]+)"(?![^>]*style)([^>]*)>/',
            '<a href="$1" style="color: ' . esc_attr($settings['primary_color']) . ';"$2>',
            $content
        );
        
        ob_start();
        ?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <?php if ($preheader): ?>
    <span style="display: none !important; visibility: hidden; mso-hide: all; font-size: 1px; line-height: 1px; max-height: 0; max-width: 0; opacity: 0; overflow: hidden;">
        <?php echo esc_html($preheader); ?>
    </span>
    <?php endif; ?>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background-color: #f3f4f6; -webkit-font-smoothing: antialiased;">
    <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($settings['primary_color']); ?>;">
                            <?php 
                                // Use light logo on colored background, fall back to dark logo
                                $header_logo = !empty($settings['business_logo_light']) ? $settings['business_logo_light'] : (!empty($settings['business_logo']) ? $settings['business_logo'] : '');
                            ?>
                            <?php if (!empty($header_logo)): ?>
                                <img src="<?php echo esc_url($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; color: #374151; font-size: 16px; line-height: 1.6;">
                            <?php echo wp_kses_post( $content ); ?>
                        </td>
                    </tr>
                    
                    <!-- Footer -->
                    <tr>
                        <td style="padding: 24px 32px; background-color: #f9fafb; border-top: 1px solid #e5e7eb;">
                            <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();
    }
}
