<?php
/**
 * Email Confirmation Integration
 *
 * Sends confirmation emails to form submitters with optional PDF attachments
 * based on field selection values.
 *
 * @package SPAI_Contact_Form
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Load the base integration class
require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'includes/integrations/class-spai-integration-base.php';

class SPAI_Email_Integration extends SPAI_Integration_Base {

    /**
     * Email settings
     */
    private $settings;

    /**
     * Temp directory for downloaded attachments
     */
    private $temp_dir;

    /**
     * Constructor
     */
    public function __construct($settings = array()) {
        $this->settings = $settings;
        $this->temp_dir = wp_upload_dir()['basedir'] . '/spai-temp/';

        // Ensure temp directory exists
        if (!file_exists($this->temp_dir)) {
            wp_mkdir_p($this->temp_dir);
        }
    }

    /**
     * Get integration name
     */
    public function get_name() {
        return 'Email Confirmation';
    }

    /**
     * Get integration description
     */
    public function get_description() {
        return __('Send confirmation emails to form submitters with optional PDF attachments', 'spai-contact-form');
    }

    /**
     * Get settings fields for this integration
     */
    public function get_settings_fields() {
        return array(
            'enabled' => array(
                'type' => 'checkbox',
                'label' => __('Enable Email Confirmation', 'spai-contact-form'),
                'description' => __('Send confirmation email to user after form submission', 'spai-contact-form'),
                'default' => false
            ),
            'subject' => array(
                'type' => 'text',
                'label' => __('Email Subject', 'spai-contact-form'),
                'default' => __('Thank you for contacting us!', 'spai-contact-form'),
                'placeholder' => 'Thank you for contacting us!'
            ),
            'from_name' => array(
                'type' => 'text',
                'label' => __('From Name', 'spai-contact-form'),
                'default' => get_bloginfo('name'),
                'placeholder' => get_bloginfo('name')
            ),
            'from_email' => array(
                'type' => 'email',
                'label' => __('From Email', 'spai-contact-form'),
                'default' => get_option('admin_email'),
                'placeholder' => get_option('admin_email')
            ),
            'reply_to' => array(
                'type' => 'email',
                'label' => __('Reply-To Email', 'spai-contact-form'),
                'description' => __('When recipient clicks Reply, email goes here (e.g., sales@company.com)', 'spai-contact-form'),
                'placeholder' => 'sales@example.com'
            ),
            'logo_url' => array(
                'type' => 'url',
                'label' => __('Logo URL (optional)', 'spai-contact-form'),
                'description' => __('URL to your company logo for the email header', 'spai-contact-form'),
                'placeholder' => 'https://example.com/logo.png'
            ),
            'phone_number' => array(
                'type' => 'text',
                'label' => __('Phone Number (optional)', 'spai-contact-form'),
                'description' => __('Shows "Questions? Call us at..." in the email. Use {phone} placeholder in body text.', 'spai-contact-form'),
                'placeholder' => '(312) 555-1234'
            ),
            'body_text' => array(
                'type' => 'textarea',
                'label' => __('Email Body Text', 'spai-contact-form'),
                'description' => __('Use {first_name} as placeholder for the submitter\'s name', 'spai-contact-form'),
                'default' => "Thank you for your interest! One of our specialists will be in touch with you shortly to discuss your project.\n\nIn the meantime, we've attached our Buyer's Guide to help you learn more about our products."
            ),
            'footer_text' => array(
                'type' => 'textarea',
                'label' => __('Footer Text', 'spai-contact-form'),
                'default' => '',
                'placeholder' => 'Company Name\n123 Main St, City, State\nwww.example.com'
            ),
            'attachment_field' => array(
                'type' => 'select',
                'label' => __('Attachment Based On Field', 'spai-contact-form'),
                'description' => __('Select which field determines the PDF attachment', 'spai-contact-form'),
                'options' => array() // Populated dynamically from form fields
            ),
            'attachment_mapping' => array(
                'type' => 'mapping',
                'label' => __('Attachment Mapping', 'spai-contact-form'),
                'description' => __('Map field values to PDF URLs', 'spai-contact-form')
            )
        );
    }

    /**
     * Get field mapping configuration
     */
    public function get_fields_config() {
        // Email doesn't need field mapping - it uses form data directly
        return array();
    }

    /**
     * Process submission - send confirmation email
     */
    public function process_submission($form_data, $mapping = array()) {
        // Get recipient email from form data
        $to_email = $this->get_recipient_email($form_data);

        if (empty($to_email)) {
            $this->log('No recipient email found in form data', 'error');
            return array(
                'success' => false,
                'error' => 'No email address found in form submission'
            );
        }

        // Validate recipient email
        if (!is_email($to_email)) {
            $this->log('Invalid recipient email: ' . $to_email, 'error');
            return array(
                'success' => false,
                'error' => 'Invalid email address'
            );
        }

        // Get settings with defaults
        $subject = !empty($this->settings['subject'])
            ? $this->settings['subject']
            : __('Thank you for contacting us!', 'spai-contact-form');

        $from_name = !empty($this->settings['from_name'])
            ? $this->settings['from_name']
            : get_bloginfo('name');

        $from_email = !empty($this->settings['from_email'])
            ? $this->settings['from_email']
            : get_option('admin_email');

        // Build email content
        $html_body = $this->render_email_template($form_data);

        // Set headers
        $headers = array(
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . $from_name . ' <' . $from_email . '>'
        );

        // Add Reply-To header if set
        if (!empty($this->settings['reply_to']) && is_email($this->settings['reply_to'])) {
            $headers[] = 'Reply-To: ' . $this->settings['reply_to'];
        }

        // Handle attachment
        $attachments = array();
        $temp_file = null;

        $attachment_url = $this->get_attachment_url($form_data);
        if ($attachment_url) {
            $temp_file = $this->download_attachment($attachment_url);
            if ($temp_file) {
                $attachments[] = $temp_file;
                $this->log('Attachment prepared: ' . basename($temp_file), 'info');
            }
        }

        // Send email
        $sent = wp_mail($to_email, $subject, $html_body, $headers, $attachments);

        // Cleanup temp file
        if ($temp_file) {
            $this->cleanup_temp_file($temp_file);
        }

        if ($sent) {
            $this->log('Email sent successfully to: ' . $to_email, 'info');
            return array(
                'success' => true,
                'email_id' => uniqid('email_', true),
                'recipient' => $to_email
            );
        } else {
            $this->log('Failed to send email to: ' . $to_email, 'error');
            return array(
                'success' => false,
                'error' => 'Failed to send email. Check server mail configuration.'
            );
        }
    }

    /**
     * Test connection - send test email
     */
    public function test_connection() {
        $to_email = !empty($this->settings['test_email'])
            ? $this->settings['test_email']
            : get_option('admin_email');

        $subject = __('Test Email from SPAI Contact Form', 'spai-contact-form');
        $message = '<p>This is a test email from the SPAI Contact Form plugin.</p><p>If you received this, email sending is working correctly.</p>';

        $from_name = !empty($this->settings['from_name'])
            ? $this->settings['from_name']
            : get_bloginfo('name');

        $from_email = !empty($this->settings['from_email'])
            ? $this->settings['from_email']
            : get_option('admin_email');

        $headers = array(
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . $from_name . ' <' . $from_email . '>'
        );

        $sent = wp_mail($to_email, $subject, $message, $headers);

        if ($sent) {
            return array(
                'success' => true,
                'message' => sprintf(__('Test email sent successfully to %s', 'spai-contact-form'), $to_email)
            );
        } else {
            return array(
                'success' => false,
                'message' => __('Failed to send test email. Check your server mail configuration.', 'spai-contact-form')
            );
        }
    }

    /**
     * Get recipient email from form data
     */
    private function get_recipient_email($form_data) {
        // Try common email field names
        $email_fields = array('email', 'user_email', 'contact_email', 'your_email', 'e-mail');

        foreach ($email_fields as $field) {
            if (!empty($form_data[$field])) {
                return sanitize_email($form_data[$field]);
            }
        }

        return null;
    }

    /**
     * Get attachment URL based on field value
     */
    private function get_attachment_url($form_data) {
        $attachment_field = !empty($this->settings['attachment_field'])
            ? $this->settings['attachment_field']
            : '';

        $attachment_mapping = !empty($this->settings['attachment_mapping'])
            ? $this->settings['attachment_mapping']
            : array();

        if (empty($attachment_field) || empty($attachment_mapping)) {
            return null;
        }

        // Get the field value from form data
        $field_value = isset($form_data[$attachment_field])
            ? $form_data[$attachment_field]
            : '';

        if (empty($field_value)) {
            return null;
        }

        // Look up the PDF URL for this value
        if (isset($attachment_mapping[$field_value])) {
            $url = $attachment_mapping[$field_value];

            // Validate URL
            if (filter_var($url, FILTER_VALIDATE_URL)) {
                return $url;
            }
        }

        $this->log('No attachment mapping found for value: ' . $field_value, 'info');
        return null;
    }

    /**
     * Download attachment to temp folder
     */
    private function download_attachment($url) {
        // Validate URL extension (only PDFs)
        $path_info = pathinfo(parse_url($url, PHP_URL_PATH));
        $extension = strtolower($path_info['extension'] ?? '');

        if ($extension !== 'pdf') {
            $this->log('Attachment URL is not a PDF: ' . $url, 'error');
            return null;
        }

        // Generate unique temp filename
        $filename = 'spai_' . uniqid() . '_' . sanitize_file_name($path_info['basename']);
        $temp_path = $this->temp_dir . $filename;

        // Download file
        $response = wp_remote_get($url, array(
            'timeout' => 30,
            'sslverify' => false
        ));

        if (is_wp_error($response)) {
            $this->log('Failed to download attachment: ' . $response->get_error_message(), 'error');
            return null;
        }

        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            $this->log('Attachment URL returned HTTP ' . $response_code, 'error');
            return null;
        }

        $body = wp_remote_retrieve_body($response);

        // Verify it's a PDF (check magic bytes)
        if (substr($body, 0, 4) !== '%PDF') {
            $this->log('Downloaded file is not a valid PDF', 'error');
            return null;
        }

        // Save to temp file
        $saved = file_put_contents($temp_path, $body);

        if ($saved === false) {
            $this->log('Failed to save attachment to temp file', 'error');
            return null;
        }

        $this->log('Attachment downloaded: ' . $filename . ' (' . size_format($saved) . ')', 'info');
        return $temp_path;
    }

    /**
     * Cleanup temp file
     */
    private function cleanup_temp_file($path) {
        if (file_exists($path)) {
            unlink($path);
            $this->log('Temp file cleaned up: ' . basename($path), 'info');
        }
    }

    /**
     * Render HTML email template
     */
    private function render_email_template($form_data) {
        // Get settings (stripslashes to remove escaping from database)
        $logo_url = !empty($this->settings['logo_url']) ? esc_url($this->settings['logo_url']) : '';
        $body_text = !empty($this->settings['body_text'])
            ? stripslashes($this->settings['body_text'])
            : "Thank you for your interest! One of our specialists will be in touch with you shortly.";
        $footer_text = !empty($this->settings['footer_text']) ? stripslashes($this->settings['footer_text']) : '';
        $phone_number = !empty($this->settings['phone_number']) ? $this->settings['phone_number'] : '';

        // Get first name for greeting
        $first_name = '';
        if (!empty($form_data['first_name'])) {
            $first_name = sanitize_text_field($form_data['first_name']);
        } elseif (!empty($form_data['name'])) {
            $first_name = sanitize_text_field(explode(' ', $form_data['name'])[0]);
        }

        // Replace placeholders in body text
        $body_text = str_replace('{first_name}', $first_name, $body_text);
        $body_text = str_replace('{phone}', $phone_number, $body_text);

        // Convert body text line breaks to paragraphs for better formatting
        $body_paragraphs = array_filter(array_map('trim', explode("\n", $body_text)));
        $body_html = '';
        foreach ($body_paragraphs as $paragraph) {
            $body_html .= '<p style="margin: 0 0 16px 0; font-size: 16px; line-height: 1.7; color: #333333;">' . esc_html($paragraph) . '</p>';
        }

        // Convert footer text line breaks to HTML
        $footer_html = !empty($footer_text) ? nl2br(esc_html($footer_text)) : '';

        // Get attachment info for display
        $attachment_name = $this->get_attachment_display_name($form_data);

        // Build HTML email
        $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Thank You</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif; font-size: 16px; line-height: 1.6; color: #333333; background-color: #f4f4f5;">
    <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background-color: #f4f4f5;">
        <tr>
            <td style="padding: 40px 20px;">
                <table role="presentation" width="600" cellspacing="0" cellpadding="0" border="0" align="center" style="background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 16px rgba(0,0,0,0.08);">
                    ';

        // Logo section (if provided)
        if (!empty($logo_url)) {
            $html .= '
                    <!-- Logo -->
                    <tr>
                        <td style="padding: 32px 40px 24px 40px; text-align: center; background-color: #ffffff; border-bottom: 1px solid #e5e7eb;">
                            <img src="' . $logo_url . '" alt="Logo" style="max-width: 180px; max-height: 60px; height: auto;">
                        </td>
                    </tr>';
        }

        $html .= '
                    <!-- Content -->
                    <tr>
                        <td style="padding: 40px 48px 32px 48px;">
                            ' . $body_html . '
                        </td>
                    </tr>';

        // Attachment box (if attachment exists)
        if (!empty($attachment_name)) {
            $html .= '
                    <!-- Attachment -->
                    <tr>
                        <td style="padding: 0 48px 40px 48px;">
                            <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px;">
                                <tr>
                                    <td style="padding: 16px 20px;">
                                        <table role="presentation" cellspacing="0" cellpadding="0" border="0">
                                            <tr>
                                                <td style="vertical-align: middle; padding-right: 12px;">
                                                    <span style="font-size: 20px;">&#128206;</span>
                                                </td>
                                                <td style="vertical-align: middle;">
                                                    <span style="font-size: 14px; font-weight: 500; color: #374151;">' . esc_html($attachment_name) . '</span>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>';
        }

        // Phone number callout (if provided)
        if (!empty($phone_number)) {
            $html .= '
                    <!-- Contact -->
                    <tr>
                        <td style="padding: 0 48px 40px 48px;">
                            <p style="margin: 0; font-size: 15px; color: #6b7280;">Questions? Call us/text at <strong style="color: #333333;">' . esc_html($phone_number) . '</strong></p>
                        </td>
                    </tr>';
        }

        // Footer section (if provided)
        if (!empty($footer_html)) {
            $html .= '
                    <!-- Footer -->
                    <tr>
                        <td style="padding: 28px 48px; background-color: #f9fafb; border-top: 1px solid #e5e7eb;">
                            <p style="margin: 0; font-size: 14px; line-height: 1.6; color: #6b7280; text-align: center;">' . $footer_html . '</p>
                        </td>
                    </tr>';
        }

        $html .= '
                </table>
            </td>
        </tr>
    </table>
</body>
</html>';

        return $html;
    }

    /**
     * Get display name for attachment (for showing in email body)
     */
    private function get_attachment_display_name($form_data) {
        $attachment_url = $this->get_attachment_url($form_data);

        if (empty($attachment_url)) {
            return '';
        }

        // Extract filename from URL
        $path_info = pathinfo(parse_url($attachment_url, PHP_URL_PATH));
        $filename = $path_info['basename'] ?? '';

        // Clean up filename for display (remove URL encoding, etc.)
        $filename = urldecode($filename);

        return $filename;
    }

    /**
     * Static method to cleanup old temp files (called via cron)
     */
    public static function cleanup_old_temp_files() {
        $temp_dir = wp_upload_dir()['basedir'] . '/spai-temp/';

        if (!is_dir($temp_dir)) {
            return;
        }

        $files = glob($temp_dir . 'spai_*');
        $now = time();

        foreach ($files as $file) {
            // Delete files older than 1 hour
            if ($now - filemtime($file) > 3600) {
                unlink($file);
            }
        }
    }
}

// Register cleanup cron
add_action('spai_cleanup_temp_files', array('SPAI_Email_Integration', 'cleanup_old_temp_files'));

if (!wp_next_scheduled('spai_cleanup_temp_files')) {
    wp_schedule_event(time(), 'hourly', 'spai_cleanup_temp_files');
}
