<?php
/**
 * Lead Email Notifier Class
 * 
 * Handles sending email notifications to administrators when new leads are submitted
 * through the chatbot. Supports both English and French based on WordPress locale.
 * 
 * @package Botami_Chatbot
 * @since 1.0.0
 */

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

class Botami_Lead_Email_Notifier {
    
    private static $instance = null;
    
    /**
     * Email templates for different languages
     */
    private static $email_templates = [
        'en' => [
            'subject' => '[{site_name}] New Lead: {lead_name}',
            'title' => 'New Lead from Botami',
            'subtitle' => 'Someone submitted their contact information',
            'field_name' => 'Name',
            'field_email' => 'Email',
            'field_submitted' => 'Submitted',
            'reply_note' => 'At your service.'
        ],
        'fr' => [
            'subject' => '[{site_name}] Nouveau prospect : {lead_name}',
            'title' => 'Nouveau prospect depuis Botami',
            'subtitle' => 'Quelqu\'un a soumis ses informations de contact',
            'field_name' => 'Nom',
            'field_email' => 'Email', 
            'field_submitted' => 'Soumis le',
            'reply_note' => 'A votre service.'
        ]
    ];
    
    /**
     * Singleton pattern
     */
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        // Private constructor to prevent direct instantiation
    }
    
    /**
     * Send lead notification email to admin
     * 
     * @param string $name Lead's name
     * @param string $email Lead's email
     * @param string $custom_field_label Custom field label
     * @param string $custom_field_value Custom field value
     * @return bool True if email was sent successfully
     */
    public function send_notification($name, $email, $custom_field_label = '', $custom_field_value = '') {
        // Check if email notifications are enabled
        if (get_option('botami_lead_email_enabled', '1') !== '1') {
            return false;
        }
        
        // Get admin email from WordPress settings (single email only)
        $admin_email = get_option('admin_email');
        
        if (empty($admin_email) || !is_email($admin_email)) {
            return false;
        }
        
        // Get site language
        $language = $this->get_site_language();
        
        // Get site information
        $site_name = get_bloginfo('name');
        $site_url = get_site_url();
        
        // Prepare email subject
        $subject = $this->get_template_text($language, 'subject', [
            'site_name' => $site_name,
            'lead_name' => $name
        ]);
        
        // Always use HTML email (simplified)
        $message = $this->generate_html_email($language, $name, $email, $custom_field_label, $custom_field_value, $site_name, $site_url);
        $headers = $this->get_html_headers($site_name, $site_url, $name, $email);
        
        // Allow filtering of email components (simplified for single admin email)
        $subject = apply_filters('botami_lead_notification_subject', $subject, $name, $email, $language);
        $message = apply_filters('botami_lead_notification_message', $message, $name, $email, $custom_field_label, $custom_field_value, $language);
        $headers = apply_filters('botami_lead_notification_headers', $headers, $name, $email, $language);
        
        // Send the email
        $sent = wp_mail($admin_email, $subject, $message, $headers);
        
        
        
        // Hook for additional actions after email is sent
        do_action('botami_lead_notification_sent', $sent, $admin_email, $name, $email, $custom_field_label, $custom_field_value, $language);
        
        return $sent;
    }
    
    /**
     * Generate clean HTML email content
     */
    private function generate_html_email($language, $name, $email, $custom_field_label, $custom_field_value, $site_name, $site_url) {
        $current_time = current_time('F j, Y \a\t g:i A');
        
        $html = '<!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>' . esc_html($this->get_template_text($language, 'title')) . '</title>
    </head>
    <body style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background-color: #f8f9fa;">
        <div style="max-width: 500px; margin: 40px auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">
            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 24px; text-align: center;">
                <h1 style="margin: 0; font-size: 20px; font-weight: 600;">' . esc_html($this->get_template_text($language, 'title')) . '</h1>
                <p style="margin: 8px 0 0 0; opacity: 0.9; font-size: 14px;">' . esc_html($this->get_template_text($language, 'subtitle')) . '</p>
            </div>
            
            <div style="padding: 24px;">
                <div style="margin-bottom: 16px;">
                    <div style="font-weight: 600; color: #555; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px;">' . esc_html($this->get_template_text($language, 'field_name')) . '</div>
                    <div style="font-size: 16px; color: #333;">' . esc_html($name) . '</div>
                </div>
                
                <div style="margin-bottom: 16px;">
                    <div style="font-weight: 600; color: #555; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px;">' . esc_html($this->get_template_text($language, 'field_email')) . '</div>
                    <div style="font-size: 16px; color: #333;">' . esc_html($email) . '</div>
                </div>';
        
        // Add custom field if provided
        if (!empty($custom_field_label) && !empty($custom_field_value)) {
            $html .= '
            <div style="margin-bottom: 16px;">
                <div style="font-weight: 600; color: #555; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px;">' . esc_html($custom_field_label) . '</div>
                <div style="font-size: 16px; color: #333;">' . esc_html($custom_field_value) . '</div>
            </div>';
        }
        
        $html .= '
                <div style="margin-bottom: 16px;">
                    <div style="font-weight: 600; color: #555; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px;">' . esc_html($this->get_template_text($language, 'field_submitted')) . '</div>
                    <div style="font-size: 16px; color: #333;">' . esc_html($current_time) . '</div>
                </div>
            </div>
            
            <div style="padding: 16px 24px; background-color: #f8f9fa; border-top: 1px solid #e9ecef; font-size: 13px; color: #666; text-align: center;">
                ' . esc_html($this->get_template_text($language, 'reply_note')) . '
            </div>
        </div>
    </body>
    </html>';
        
        return $html;
    }
    
    /**
     * Get HTML email headers
     */
    private function get_html_headers($site_name, $site_url, $name, $email) {
        $parsed_url = wp_parse_url($site_url);
        return array(
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . $site_name . ' <noreply@' . $parsed_url['host'] . '>',
            'Reply-To: ' . $name . ' <' . $email . '>'
        );
    }
    
    /**
     * Get template text with placeholder replacement
     */
    private function get_template_text($language, $key, $replacements = []) {
        $text = self::$email_templates[$language][$key] ?? self::$email_templates['en'][$key] ?? '';
        
        foreach ($replacements as $placeholder => $value) {
            $text = str_replace('{' . $placeholder . '}', $value, $text);
        }
        
        return $text;
    }
    
    /**
     * Get site language using existing language manager
     */
    private function get_site_language() {
        if (class_exists('Botami_Language_Manager')) {
            return Botami_Language_Manager::get_site_language();
        }
        
        // Fallback if language manager is not available
        $locale = get_locale();
        $lang = substr($locale, 0, 2);
        return in_array($lang, ['en', 'fr']) ? $lang : 'en';
    }
}