<?php

namespace PloverCRM\Modules\Integrations\Helpers;

use PloverCRM\Common\BaseLogViewer;

/**
 * Automations Log Viewer
 * 
 * Displays logs for Google Ads Automations (outgoing conversions)
 */
class AutomationsLogViewer extends BaseLogViewer
{
    public function __construct()
    {
        parent::__construct('automations', 'automations');
    }

    /**
     * Render the log viewer section
     * 
     * @param string|null $platform Filter by platform ('google' or 'meta')
     */
    public static function render(?string $platform = null): void
    {
        $viewer = new self();
        $logs = $viewer->getRecentLogs();
        
        // Filter logs by platform if specified
        if ($platform) {
            foreach ($logs as &$logFile) {
                foreach ($logFile['tasks'] as $taskId => &$task) {
                    // Filter entries within the task to only include matching platform
                    $task = array_filter($task, function($entry) use ($platform) {
                        return isset($entry['context']['platform']) && $entry['context']['platform'] === $platform;
                    });
                    
                    // Remove task if no entries remain
                    if (empty($task)) {
                        unset($logFile['tasks'][$taskId]);
                    }
                }
            }
            unset($logFile, $task);
            
            // Remove log files with no tasks
            $logs = array_filter($logs, function($logFile) {
                return !empty($logFile['tasks']);
            });
        }

        $platformLabel = $platform === 'google' ? 'Google Ads' : ($platform === 'meta' ? 'Meta CAPI' : 'All');
        
        echo '<div class="plvcrm-logs-section">';
        echo '<h3>Recent Activity</h3>';
        echo '<p style="color: #666; margin-bottom: 15px;">View logs for ' . esc_html($platformLabel) . ' automation events.</p>';

        $viewer->renderLogEntries($logs);

        if (!empty($logs)) {
            echo '<div style="margin-top: 15px;">';
            echo \PloverCRM\Common\BaseLogViewer::getDownloadButton('automations');
            echo '</div>';
        }

        echo '</div>';
    }
}
