<?php
/**
 * Name: WP Mail Logging
 * Description: Log all emails sent from WordPress including recipient, subject, content, and timestamps for debugging email delivery issues and monitoring notification system without services
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Add Useful Functionality",
 *     "description": "Extend WordPress with helpful tools that make site management easier."
 *   },
 *   {
 *     "title": "Save Time",
 *     "description": "Automate or simplify tasks that would otherwise require manual work or additional tools."
 *   }
 * ]
 * Added: 2025-10-08
 * Tags: email, logging, mail, debug, smtp
 * WhereToFind: {
 *   "location": "Switchboard Settings",
 *   "url": "",
 *   "instructions": "Set log limit in module settings. Works automatically to log all outgoing emails with subject, recipient, headers, and message content.",
 *   "newTab": false
 * }
 */

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

class SwitchboardWpMailLogging {
    
    public function __construct() {
        add_action('wp_mail', [$this, 'log_email'], 10, 1);
        // Admin page removed - use Switchboard settings panel instead
        $this->create_table();
    }
    
    private function create_table() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'switchboard_mail_log';
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            to_email varchar(255) NOT NULL,
            subject varchar(255) NOT NULL,
            message longtext NOT NULL,
            headers text,
            sent_date datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    public function log_email($args) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'switchboard_mail_log';
        
        $to = is_array($args['to']) ? implode(', ', $args['to']) : $args['to'];
        $headers = is_array($args['headers']) ? implode("\n", $args['headers']) : $args['headers'];
        
        $wpdb->insert($table_name, [
            'to_email' => $to,
            'subject' => $args['subject'],
            'message' => $args['message'],
            'headers' => $headers,
        ]);
        
        // Keep only last 100 emails
        $settings = get_option('switchboard_wp-mail-logging_settings', []);
        $limit = isset($settings['limit']) ? intval($settings['limit']) : 100;
        
        // Get IDs to keep
        $keep_ids = $wpdb->get_col($wpdb->prepare(
            "SELECT id FROM $table_name ORDER BY id DESC LIMIT %d",
            $limit
        ));
        
        // Delete old emails
        if (!empty($keep_ids)) {
            $ids_placeholder = implode(',', array_map('intval', $keep_ids));
            $wpdb->query("DELETE FROM $table_name WHERE id NOT IN ($ids_placeholder)");
        }
        
        return $args;
    }
    
    public function add_admin_page() {
        add_management_page(
            'Email Logs',
            'Email Logs',
            'manage_options',
            'switchboard-mail-logs',
            [$this, 'render_page']
        );
    }
    
    public function render_page() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'switchboard_mail_log';
        
        $logs = $wpdb->get_results("SELECT * FROM $table_name ORDER BY id DESC LIMIT 100");
        
        ?>
        <div class="wrap">
            <h1>Email Logs</h1>
            <p>Last 100 emails sent from WordPress.</p>
            
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>To</th>
                        <th>Subject</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($logs)): ?>
                        <tr><td colspan="4">No emails logged yet.</td></tr>
                    <?php else: ?>
                        <?php foreach ($logs as $log): ?>
                            <tr>
                                <td><?php echo esc_html($log->sent_date); ?></td>
                                <td><?php echo esc_html($log->to_email); ?></td>
                                <td><?php echo esc_html($log->subject); ?></td>
                                <td>
                                    <button type="button" class="button" onclick="showEmailDetails(<?php echo $log->id; ?>)">View</button>
                                </td>
                            </tr>
                            <tr id="email-details-<?php echo $log->id; ?>" style="display:none;">
                                <td colspan="4">
                                    <strong>Message:</strong><br>
                                    <pre class="sb-sp-code-block"><?php echo esc_html($log->message); ?></pre>
                                    <?php if ($log->headers): ?>
                                        <strong>Headers:</strong><br>
                                        <pre class="sb-sp-code-block"><?php echo esc_html($log->headers); ?></pre>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <script>
        function showEmailDetails(id) {
            var row = document.getElementById('email-details-' + id);
            row.style.display = row.style.display === 'none' ? 'table-row' : 'none';
        }
        </script>
        <?php
    }

    /**
     * Render settings panel
     *
     * @param array $settings Current module settings
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'switchboard_mail_log';
        $limit = isset($settings['limit']) ? intval($settings['limit']) : 100;
        
        // Get all logs
        $logs = $wpdb->get_results("SELECT * FROM $table_name ORDER BY id DESC LIMIT 500");
        ?>
        <input type="hidden" name="module" value="wp-mail-logging">

        <div class="sb-sp-info-box sb-sp-info-box-info" style="margin-bottom: 24px;">
            <h4 class="sb-sp-heading-sm">How It Works</h4>
            <p class="sb-sp-description" style="margin: 0;">Automatically logs all emails sent through WordPress (password resets, notifications, etc.) so you can track delivery, debug issues, and verify that emails are being sent correctly.</p>
        </div>

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">Settings</h3>
            
            <div style="display: flex; gap: 16px; flex-wrap: wrap; align-items: flex-start;">
                <div style="flex: 0 0 auto;">
                    <label for="setting_limit" class="sb-sp-label"><?php esc_html_e('Log Limit', 'wpswitchboard'); ?></label>
                    <input type="number" name="setting_limit" id="setting_limit" value="<?php echo esc_attr($limit); ?>" min="10" max="1000" class="sb-sp-input" style="width: 120px;">
                    <p class="sb-sp-description"><?php esc_html_e('Max emails to keep', 'wpswitchboard'); ?></p>
                </div>
                <div style="flex: 1; min-width: 250px;">
                    <label for="mail-log-search" class="sb-sp-label"><?php esc_html_e('Search Logs', 'wpswitchboard'); ?></label>
                    <input type="text" id="mail-log-search" placeholder="<?php esc_attr_e('Search by subject or recipient...', 'wpswitchboard'); ?>" class="sb-sp-input">
                    <p class="sb-sp-description"><?php esc_html_e('Filter emails in real-time', 'wpswitchboard'); ?></p>
                </div>
            </div>
        </div>

        <hr class="sb-sp-divider">

        <div class="sb-sp-group" style="margin-bottom: 24px;">
            <h3 class="sb-sp-heading">
                <?php esc_html_e('Email Logs', 'wpswitchboard'); ?>
                <span id="mail-log-count" class="sb-sp-text-sm" style="font-weight: normal; color: #64748b; margin-left: 8px;"><?php echo count($logs); ?> <?php esc_html_e('emails', 'wpswitchboard'); ?></span>
            </h3>

            <div id="mail-logs-container" style="max-height: 500px; overflow-y: auto; border: 1px solid #e5e7eb; border-radius: 8px; background: white;">
                    
        <?php if (empty($logs)): ?>
            <div style="text-align: center; padding: 40px 20px;">
                <div style="font-size: 48px; margin-bottom: 16px; opacity: 0.3;"><span class="dashicons dashicons-email-alt" style="font-size: 48px; width: 48px; height: 48px;"></span></div>
                <p style="margin: 0; color: #64748b;"><?php esc_html_e('No emails logged yet', 'wpswitchboard'); ?></p>
            </div>
        <?php else: ?>
            <?php foreach ($logs as $log): 
                $date = date('M j, Y g:i A', strtotime($log->sent_date));
            ?>
            <div class="mail-log-item" data-subject="<?php echo esc_attr(strtolower($log->subject)); ?>" data-to="<?php echo esc_attr(strtolower($log->to_email)); ?>" style="border-bottom: 1px solid #e5e7eb; padding: 0;">
                <div class="mail-log-header" onclick="toggleMailLog(this)" style="cursor: pointer; padding: 16px; display: flex; align-items: center; justify-content: space-between; transition: background-color 0.15s;">
                    <div style="flex: 1;">
                        <div style="font-weight: 600; color: #111827; margin-bottom: 4px;"><?php echo esc_html($log->subject); ?></div>
                        <div style="font-size: 12px; color: #64748b;">
                            <span style="margin-right: 16px;"><?php echo esc_html($log->to_email); ?></span>
                            <span><?php echo esc_html($date); ?></span>
                        </div>
                    </div>
                    <button type="button" class="mail-copy-btn" onclick="event.stopPropagation(); copyEmailContent(<?php echo esc_attr($log->id); ?>)" title="<?php esc_attr_e('Copy email', 'wpswitchboard'); ?>">
                        <span class="dashicons dashicons-admin-page"></span>
                    </button>
                    <div style="color: #94a3b8; font-size: 20px; transition: transform 0.2s;" class="mail-log-arrow">▼</div>
                </div>
                <div class="mail-log-content" style="display: none; padding: 16px; background: #f9fafb; border-top: 1px solid #e5e7eb;">
                    <?php
                    // Check if message contains HTML
                    $is_html = preg_match('/<[^>]+>/', $log->message);
                    ?>
                    <div style="margin-bottom: 16px;">
                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
                            <strong class="sb-sp-label" style="margin: 0;"><?php esc_html_e('Message:', 'wpswitchboard'); ?></strong>
                            <?php if ($is_html): ?>
                            <button type="button" class="mail-preview-btn" onclick="previewHtmlEmail(<?php echo esc_attr($log->id); ?>)">
                                <span class="dashicons dashicons-visibility"></span>
                                <?php esc_html_e('Preview HTML', 'wpswitchboard'); ?>
                            </button>
                            <?php endif; ?>
                        </div>
                        <div class="sb-sp-card" style="padding: 12px; font-family: monospace; font-size: 13px; white-space: pre-wrap; word-wrap: break-word;"><?php echo esc_html($log->message); ?></div>
                        <?php if ($is_html): ?>
                        <textarea id="mail-html-source-<?php echo esc_attr($log->id); ?>" style="display: none;"><?php echo esc_textarea($log->message); ?></textarea>
                        <?php endif; ?>
                    </div>
                    <!-- Hidden email content for copying -->
                    <textarea id="mail-copy-content-<?php echo esc_attr($log->id); ?>" style="display: none;">To: <?php echo esc_textarea($log->to_email); ?>

Subject: <?php echo esc_textarea($log->subject); ?>

Date: <?php echo esc_textarea($log->sent_date); ?>

<?php if (!empty($log->headers)): ?>Headers:
<?php echo esc_textarea($log->headers); ?>

<?php endif; ?>Message:
<?php echo esc_textarea($log->message); ?></textarea>
                    <?php if (!empty($log->headers)): ?>
                    <div>
                        <strong class="sb-sp-label"><?php esc_html_e('Headers:', 'wpswitchboard'); ?></strong>
                        <div class="sb-sp-card" style="margin-top: 8px; padding: 12px; font-family: monospace; font-size: 13px; white-space: pre-wrap; word-wrap: break-word;"><?php echo esc_html($log->headers); ?></div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
        </div>

        <!-- HTML Email Preview Modal -->
        <style>
            /* Preview HTML Button - Outline style with Tailwind blue */
            .mail-preview-btn {
                display: inline-flex;
                align-items: center;
                gap: 5px;
                padding: 5px 10px;
                font-size: 12px;
                font-weight: 500;
                color: #3b82f6; /* blue-500 */
                background: transparent;
                border: 1px solid #93c5fd; /* blue-300 */
                border-radius: 5px;
                cursor: pointer;
                transition: all 0.15s ease;
            }
            .mail-preview-btn:hover {
                background: #eff6ff; /* blue-50 */
                border-color: #3b82f6; /* blue-500 */
            }
            .mail-preview-btn .dashicons {
                font-size: 14px;
                width: 14px;
                height: 14px;
            }

            /* Modal Device Toggle Buttons - Outline style */
            .mail-device-btn {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                width: 32px;
                height: 32px;
                padding: 0;
                background: transparent;
                border: 1px solid #e5e7eb; /* gray-200 */
                border-radius: 6px;
                cursor: pointer;
                transition: all 0.15s ease;
                color: #9ca3af; /* gray-400 */
            }
            .mail-device-btn:hover {
                border-color: #93c5fd; /* blue-300 */
                color: #3b82f6; /* blue-500 */
            }
            .mail-device-btn.active {
                background: transparent;
                border-color: #3b82f6; /* blue-500 */
                color: #3b82f6; /* blue-500 */
            }
            .mail-device-btn .dashicons {
                font-size: 16px;
                width: 16px;
                height: 16px;
                line-height: 16px;
            }

            /* Close Button - Outline style */
            .mail-close-btn {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                width: 32px;
                height: 32px;
                padding: 0;
                background: transparent;
                border: 1px solid #e5e7eb; /* gray-200 */
                border-radius: 6px;
                cursor: pointer;
                transition: all 0.15s ease;
                color: #9ca3af; /* gray-400 */
            }
            .mail-close-btn:hover {
                border-color: #fca5a5; /* red-300 */
                color: #ef4444; /* red-500 */
            }
            .mail-close-btn .dashicons {
                font-size: 18px;
                width: 18px;
                height: 18px;
                line-height: 18px;
            }

            /* Copy Button - Outline style */
            .mail-copy-btn {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                width: 32px;
                height: 32px;
                padding: 0;
                margin-right: 8px;
                background: transparent;
                border: 1px solid #e5e7eb; /* gray-200 */
                border-radius: 6px;
                cursor: pointer;
                transition: all 0.15s ease;
                color: #9ca3af; /* gray-400 */
            }
            .mail-copy-btn:hover {
                border-color: #93c5fd; /* blue-300 */
                color: #3b82f6; /* blue-500 */
            }
            .mail-copy-btn.copied {
                border-color: #86efac; /* green-300 */
                color: #22c55e; /* green-500 */
            }
            .mail-copy-btn .dashicons {
                font-size: 16px;
                width: 16px;
                height: 16px;
                line-height: 16px;
            }
        </style>
        <div id="mail-html-preview-modal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.6); z-index: 100000; padding: 20px;">
            <div style="background: white; border-radius: 12px; max-width: 900px; width: 100%; max-height: 90vh; margin: auto; display: flex; flex-direction: column; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1), 0 10px 10px -5px rgba(0,0,0,0.04);">
                <div style="padding: 16px 20px; border-bottom: 1px solid #e5e7eb; display: flex; justify-content: space-between; align-items: center;">
                    <h3 style="margin: 0; font-size: 16px; font-weight: 600; color: #111827;">
                        <span class="dashicons dashicons-email" style="margin-right: 8px; vertical-align: middle; color: #3b82f6;"></span>
                        <?php esc_html_e('HTML Email Preview', 'wpswitchboard'); ?>
                    </h3>
                    <div style="display: flex; gap: 4px; align-items: center;">
                        <button type="button" id="mail-preview-mobile" class="mail-device-btn" onclick="setPreviewSize('mobile')" title="<?php esc_attr_e('Mobile (375px)', 'wpswitchboard'); ?>">
                            <span class="dashicons dashicons-smartphone"></span>
                        </button>
                        <button type="button" id="mail-preview-tablet" class="mail-device-btn" onclick="setPreviewSize('tablet')" title="<?php esc_attr_e('Tablet (768px)', 'wpswitchboard'); ?>">
                            <span class="dashicons dashicons-tablet"></span>
                        </button>
                        <button type="button" id="mail-preview-desktop" class="mail-device-btn active" onclick="setPreviewSize('desktop')" title="<?php esc_attr_e('Desktop (100%)', 'wpswitchboard'); ?>">
                            <span class="dashicons dashicons-desktop"></span>
                        </button>
                        <div style="width: 1px; height: 24px; background: #e5e7eb; margin: 0 8px;"></div>
                        <button type="button" onclick="closeHtmlPreview()" class="mail-close-btn" title="<?php esc_attr_e('Close', 'wpswitchboard'); ?>">
                            <span class="dashicons dashicons-no-alt"></span>
                        </button>
                    </div>
                </div>
                <div style="flex: 1; overflow: auto; padding: 20px; background: #f3f4f6; display: flex; justify-content: center; align-items: flex-start;">
                    <iframe id="mail-html-preview-frame" style="background: white; border: 1px solid #e5e7eb; border-radius: 4px; width: 100%; height: 500px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);"></iframe>
                </div>
            </div>
        </div>

        <script>
        function copyEmailContent(id) {
            var content = document.getElementById("mail-copy-content-" + id);
            if (!content) return;

            var btn = event.currentTarget;
            var icon = btn.querySelector(".dashicons");

            navigator.clipboard.writeText(content.value).then(function() {
                // Show success state
                btn.classList.add("copied");
                icon.classList.remove("dashicons-admin-page");
                icon.classList.add("dashicons-yes");

                // Reset after 2 seconds
                setTimeout(function() {
                    btn.classList.remove("copied");
                    icon.classList.remove("dashicons-yes");
                    icon.classList.add("dashicons-admin-page");
                }, 2000);
            }).catch(function(err) {
                console.error("Failed to copy: ", err);
            });
        }

        function previewHtmlEmail(id) {
            var htmlSource = document.getElementById("mail-html-source-" + id);
            if (!htmlSource) return;

            var modal = document.getElementById("mail-html-preview-modal");
            var iframe = document.getElementById("mail-html-preview-frame");

            // Write HTML to iframe (sandbox for security)
            var doc = iframe.contentDocument || iframe.contentWindow.document;
            doc.open();
            doc.write(htmlSource.value);
            doc.close();

            // Show modal
            modal.style.display = "flex";
            document.body.style.overflow = "hidden";

            // Reset to desktop view
            setPreviewSize("desktop");
        }

        function closeHtmlPreview() {
            var modal = document.getElementById("mail-html-preview-modal");
            modal.style.display = "none";
            document.body.style.overflow = "";
        }

        function setPreviewSize(size) {
            var iframe = document.getElementById("mail-html-preview-frame");
            var sizes = {
                mobile: { width: "375px", height: "667px" },
                tablet: { width: "768px", height: "500px" },
                desktop: { width: "100%", height: "500px" }
            };

            iframe.style.width = sizes[size].width;
            iframe.style.height = sizes[size].height;

            // Update button states
            ["mobile", "tablet", "desktop"].forEach(function(s) {
                var btn = document.getElementById("mail-preview-" + s);
                if (s === size) {
                    btn.classList.add("active");
                } else {
                    btn.classList.remove("active");
                }
            });
        }

        // Close modal on escape key
        document.addEventListener("keydown", function(e) {
            if (e.key === "Escape") {
                closeHtmlPreview();
            }
        });

        // Close modal on background click
        document.getElementById("mail-html-preview-modal").addEventListener("click", function(e) {
            if (e.target === this) {
                closeHtmlPreview();
            }
        });

        function toggleMailLog(header) {
            var content = header.nextElementSibling;
            var arrow = header.querySelector(".mail-log-arrow");
            var isOpen = content.style.display === "block";
            
            if (isOpen) {
                content.style.display = "none";
                arrow.style.transform = "rotate(0deg)";
                header.style.background = "";
            } else {
                content.style.display = "block";
                arrow.style.transform = "rotate(180deg)";
                header.style.background = "#f9fafb";
            }
        }
        
        jQuery(document).ready(function($) {
            var totalLogs = $(".mail-log-item").length;
            
            $("#mail-log-search").on("input", function() {
                var searchTerm = $(this).val().toLowerCase();
                var visibleCount = 0;
                
                $(".mail-log-item").each(function() {
                    var subject = $(this).data("subject");
                    var to = $(this).data("to");
                    
                    if (subject.includes(searchTerm) || to.includes(searchTerm)) {
                        $(this).show();
                        visibleCount++;
                    } else {
                        $(this).hide();
                    }
                });
                
                // Update count
                if (searchTerm) {
                    $("#mail-log-count").text(visibleCount + " <?php esc_html_e('of', 'wpswitchboard'); ?> " + totalLogs + " <?php esc_html_e('emails', 'wpswitchboard'); ?>");
                } else {
                    $("#mail-log-count").text(totalLogs + " <?php esc_html_e('emails', 'wpswitchboard'); ?>");
                }
            });
            
            // Add hover effect
            $(".mail-log-header").hover(
                                function() {
                                    if ($(this).next().css("display") === "none") {
                                        $(this).css("background", "#f9fafb");
                                    }
                                },
                                function() {
                                    if ($(this).next().css("display") === "none") {
                                        $(this).css("background", "");
                                    }
                                }
                            );
                        });
        </script>
        <?php
                
    }

    /**
     * Register data locations for cleanup system
     *
     * @return array Data storage locations
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_wp-mail-logging_settings',
            ],
            'option_patterns' => [],
            'tables' => [
                'switchboard_mail_log',
            ],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }
}

$switchboard_instance = new SwitchboardWpMailLogging();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
