<?php
/**
 * Email Notifications
 *
 * @package Spin_Wheel
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * SWP_Email Class
 */
// Direct query below reads a single row from the plugin's own swp_entries table
// (prepared, internal identifier) with no applicable caching layer.
// phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL, PluginCheck.Security.DirectDB, WordPress.NamingConventions.PrefixAllGlobals
class SWP_Email {
    
    /**
     * Instance
     *
     * @var SWP_Email
     */
    private static $instance = null;
    
    /**
     * Get instance
     *
     * @return SWP_Email
     */
    public static function instance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        // Hook for email customization
        add_filter('swp_email_content', [$this, 'apply_template'], 10, 3);
    }
    
    /**
     * Send winner email
     *
     * @param int $wheel_id Wheel ID
     * @param int $entry_id Entry ID
     * @return bool Success
     */
    public function send_winner_email($wheel_id, $entry_id) {
        global $wpdb;
        
        // Get entry
        $entry = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}swp_entries WHERE id = %d",
            $entry_id
        ));
        
        if (!$entry) {
            return false;
        }
        
        // Get wheel settings
        $wheel_title = get_the_title($wheel_id);
        
        // Get global email settings from Settings page
        $global_settings = get_option('swp_settings', []);
        $subject = !empty($global_settings['default_email_subject']) 
            ? $global_settings['default_email_subject']
            /* translators: %s: prize label */
            : sprintf(__('Congratulations! You won: %s', 'spin-wheel'), $entry->prize_label);
        $custom_message = !empty($global_settings['default_email_message']) 
            ? $global_settings['default_email_message'] 
            : '';
        
        // Email details
        $to = $entry->user_email;
        
        // Email content
        $content = $this->get_winner_email_content($entry, $wheel_title, $custom_message);
        
        // Apply filter
        $content = apply_filters('swp_email_content', $content, $entry, $wheel_id);
        
        // Headers
        $headers = ['Content-Type: text/html; charset=UTF-8'];
        
        // Send email
        return wp_mail($to, $subject, $content, $headers);
    }
    
    /**
     * Get winner email content
     *
     * @param object $entry Entry data
     * @param string $wheel_title Wheel title
     * @param string $custom_message Custom email message from global settings
     * @return string Email content
     */
    private function get_winner_email_content($entry, $wheel_title, $custom_message) {
        
        // Replace placeholders in custom message
        if ($custom_message) {
            $placeholders = [
                '{user_name}'   => $entry->user_name,
                '{prize_label}' => $entry->prize_label,
                '{prize_code}'  => $entry->prize_code,
                '{wheel_name}'  => $wheel_title,
            ];
            $custom_message = str_replace(array_keys($placeholders), array_values($placeholders), $custom_message);
        }
        
        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title><?php echo esc_html__('Winner Notification', 'spin-wheel'); ?></title>
        </head>
        <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 30px; border-radius: 10px 10px 0 0; text-align: center;">
                <h1 style="color: #fff; margin: 0; font-size: 28px;">🎉 Congratulations!</h1>
            </div>
            
            <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px;">
                <p style="font-size: 18px; margin-bottom: 20px;">
                    <?php
                    /* translators: %s: user's name */
                    printf(esc_html__('Hello %s!', 'spin-wheel'), esc_html($entry->user_name)); ?>
                </p>
                
                <?php if ($custom_message) : ?>
                    <p style="font-size: 16px; margin-bottom: 20px;">
                        <?php echo wp_kses_post($custom_message); ?>
                    </p>
                <?php else : ?>
                    <p style="font-size: 16px; margin-bottom: 20px;">
                        <?php esc_html_e('You have won an amazing prize from our spin wheel!', 'spin-wheel'); ?>
                    </p>
                <?php endif; ?>
                
                <div style="background: #fff; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #667eea;">
                    <h2 style="margin-top: 0; color: #667eea; font-size: 20px;">
                        <?php esc_html_e('Your Prize:', 'spin-wheel'); ?>
                    </h2>
                    <p style="font-size: 24px; font-weight: bold; margin: 10px 0; color: #333;">
                        <?php echo esc_html($entry->prize_label); ?>
                    </p>
                    
                    <?php if (!empty($entry->prize_code)) : ?>
                        <div style="background: #f0f0f0; padding: 15px; border-radius: 5px; margin-top: 15px;">
                            <p style="margin: 0 0 5px 0; font-size: 14px; color: #666;">
                                <?php esc_html_e('Your Coupon Code:', 'spin-wheel'); ?>
                            </p>
                            <p style="margin: 0; font-size: 20px; font-weight: bold; color: #667eea; font-family: 'Courier New', monospace;">
                                <?php echo esc_html($entry->prize_code); ?>
                            </p>
                        </div>
                    <?php endif; ?>
                </div>
                
                <p style="font-size: 14px; color: #666; margin-top: 30px;">
                    <?php esc_html_e('Thank you for participating!', 'spin-wheel'); ?>
                </p>
                
                <p style="font-size: 14px; color: #666;">
                    <?php
                    /* translators: %s: site name */
                    printf(wp_kses(__('Best regards,<br>%s', 'spin-wheel'), ['br' => []]), esc_html(get_bloginfo('name'))); ?>
                </p>
            </div>
            
            <div style="text-align: center; margin-top: 20px; font-size: 12px; color: #999;">
                <p>
                    <?php
                    /* translators: %s: site name */
                    printf(esc_html__('This email was sent from %s', 'spin-wheel'), esc_html(get_bloginfo('name'))); ?>
                </p>
            </div>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }
    
    /**
     * Apply email template
     *
     * @param string $content Email content
     * @param object $entry Entry data
     * @param int $wheel_id Wheel ID
     * @return string Modified content
     */
    public function apply_template($content, $entry, $wheel_id) {
        // Allow customization via filter
        return $content;
    }
}

// phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL, PluginCheck.Security.DirectDB, WordPress.NamingConventions.PrefixAllGlobals
