<?php
/**
 * AntivirusDashboard — Main antivirus overview page.
 * @package UltraguardPro\modules\antivirus\pages
 */
namespace UltraguardPro\modules\antivirus\pages;
use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;
use UltraguardPro\support\UpgradeManager;
use UltraguardPro\support\LicenseInfo;
if ( ! defined( 'ABSPATH' ) ) { exit; }

class AntivirusDashboard extends BasePage {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
        $this->ajax_nonce_action = 'ultraguard_admin_nonce';
    }

    public function get_scheme( $context ): array {
        $nonce      = $this->create_nonce( 'ultraguard_admin_nonce' );
        $scan_t     = $this->plugin->modules->get_db_tables()->get_table( 'scan_results' );
        $quar_t     = $this->plugin->modules->get_db_tables()->get_table( 'quarantine' );
        $sig_t      = $this->plugin->modules->get_db_tables()->get_table( 'malware_signatures' );
        $vuln_t     = $this->plugin->modules->get_db_tables()->get_table( 'vulnerability_scans' );

        $total_scanned  = $scan_t ? $scan_t->count() : 0;
        $threats        = $scan_t ? $scan_t->count( [ 'status' => 'infected' ] ) : 0;
        $quarantined    = $quar_t ? $quar_t->count( [ 'status' => 'active' ] ) : 0;
        $signatures     = $sig_t  ? $sig_t->count( [ 'is_active' => 1 ] ) : 0;
        $open_vulns     = $vuln_t ? $vuln_t->count( [ 'status' => 'open' ] ) : 0;
        $critical_vulns = $vuln_t ? $vuln_t->count( [ 'status' => 'open', 'severity' => 'critical' ] ) : 0;

        // ── Chart data ────────────────────────────────────────────────────────
        // Threats detected per day over the last 30 days
        $threat_trend = $scan_t
            ? $scan_t->get_chart_data( 'created_at', 'id', 'day', [ 'status' => 'infected' ], 30 )
            : [ 'labels' => [], 'data' => [] ];

        // Breakdown of scan results by status (infected / suspicious / clean)
        $status_breakdown = $scan_t
            ? $scan_t->get_pie_chart_data( 'status', 'id', 'COUNT', [], 5 )
            : [ 'labels' => [], 'data' => [], 'colors' => [] ];

        // Threat types distribution (top 8 malware families)
        $threat_types = $scan_t
            ? $scan_t->get_pie_chart_data( 'threat_type', 'id', 'COUNT', [ 'status' => 'infected' ], 8 )
            : [ 'labels' => [], 'data' => [], 'colors' => [] ];
        $active_scan    = get_option( 'ultraguard_active_scan', [] );
        // Treat stale scans as idle in the initial page render.
        // JS will confirm via AJAX and auto-cancel them on first poll.
        if ( ( $active_scan['status'] ?? '' ) === 'running' ) {
            $started = isset( $active_scan['started_at'] )
                ? strtotime( $active_scan['started_at'] ) : 0;
            $elapsed = $started ? ( time() - $started ) : 9999;
            $prog    = (int) ( $active_scan['progress'] ?? 0 );
            if ( ( $elapsed > 600 && $prog <= 5 ) || $elapsed > 1200 ) {
                $active_scan['status'] = 'cancelled'; // treat as idle for render only
            }
        }
        $is_running     = ( $active_scan['status'] ?? '' ) === 'running';
        $last_scan_at   = $scan_t ? ( $scan_t->get_last()['created_at'] ?? __( 'Never', 'ultraguard-security-suite' ) ) : __( 'Never', 'ultraguard-security-suite' );

        // Recent threats (last 5)
        $recent_threats = $scan_t ? $scan_t->get_by( [ 'status' => 'infected' ], 5, 'created_at', 'DESC' ) : [];

        // Threat level badge
        $threat_badge_type = $threats > 0 ? ( $threats > 5 ? 'danger' : 'warning' ) : 'success';
        $threat_badge_text = $threats > 0
            /* translators: %d: number */
            ? sprintf( _n( '%d threat', '%d threats', $threats, 'ultraguard-security-suite' ), $threats )
            : __( 'Clean', 'ultraguard-security-suite' );

        $is_pro = \UltraguardPro\support\LicenseInfo::instance()->isPro();

        // For free users, calculate scan cooldown status
        $free_cooldown_info = [];
        if ( ! $is_pro ) {
            $last_manual    = (int) get_option( 'ultraguard_av_last_manual_scan', 0 );
            $cooldown_secs  = 48 * HOUR_IN_SECONDS;
            $next_available = $last_manual ? $last_manual + $cooldown_secs : 0;
            $can_scan_now   = ! $last_manual || ( time() >= $next_available );
            if ( ! $can_scan_now ) {
                $diff    = $next_available - time();
                $hours   = (int) floor( $diff / HOUR_IN_SECONDS );
                $minutes = (int) floor( ( $diff % HOUR_IN_SECONDS ) / MINUTE_IN_SECONDS );
                $free_cooldown_info = [
                    'type'       => 'alert-box',
                    'alert_type' => 'warning',
                    'title'      => sprintf(
                        /* translators: Placeholder values are inserted into this string. */
                        __( '⏱ Free Plan: Next scan available in %s', 'ultraguard-security-suite' ),
                        $hours > 0
                            /* translators: %1$d: integer, %2$d: integer */
                            ? sprintf( __( '%1$dh %2$dm', 'ultraguard-security-suite' ), $hours, $minutes )
                            /* translators: %d: integer */
                            : sprintf( __( '%dm', 'ultraguard-security-suite' ), $minutes )
                    ),
                    'message'    => __( 'Free plan scans are limited to once every 48 hours. Upgrade to Pro for unlimited scheduled scans.', 'ultraguard-security-suite' ),
                    'actions'    => [
                        [
                            'type'         => 'button',
                            'text'         => __( 'Upgrade to Pro — Unlimited Scans →', 'ultraguard-security-suite' ),
                            'button_style' => 'secondary',
                            'url'          => \UltraguardPro\support\UpgradeManager::upgrade_page_url(),
                        ],
                    ],
                ];
            }
        }

        $scheme = [
            'type'      => 'page',
            'id'        => 'ultraguard-antivirus-dashboard',
            'page_slug' => 'antivirus',
            'class'     => 'ultraguard-antivirus-dashboard-page ultraguard-page-no-sidebar',
            'header'    => [
                'title'    => __( 'Antivirus Scanner', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Real-time malware scanning, quarantine management and vulnerability detection', 'ultraguard-security-suite' ),
                'icon'     => 'dashicons-shield',
                'badge'    => [ 'text' => $threat_badge_text, 'badge_type' => $threat_badge_type ],
                'actions'  => [
                    $this->create_ajax_button( __( 'Quick Scan', 'ultraguard-security-suite' ),    'ultraguard_antivirus_start_scan', [ 'scan_type' => 'quick', 'nonce' => $nonce ], 'primary',   'dashicons-search'     ),
                    $this->create_ajax_button( __( 'Full Scan',  'ultraguard-security-suite' ),    'ultraguard_antivirus_start_scan', [ 'scan_type' => 'full',  'nonce' => $nonce ], 'secondary', 'dashicons-shield'     ),
                    $this->create_ajax_button( __( 'Update Signatures', 'ultraguard-security-suite' ), 'ultraguard_antivirus_update_signatures', [ 'nonce' => $nonce ], 'secondary', 'dashicons-update' ),
                ],
            ],
            'data' => array_values( array_filter( [
                // Pro upsell card for free users (shows scheduled scanning benefit)
                $is_pro ? [] : $this->pro_upsell_card( 'scheduled_av_scan' ),

                // Cooldown notice when free user's scan is rate-limited
                $free_cooldown_info ?: [],
                $is_running ? [
                    'type'       => 'alert-box',
                    'alert_type' => 'info',
                    'title'      => __( 'Scan in Progress', 'ultraguard-security-suite' ),
                    /* translators: %s: string */
                    'message'    => sprintf( __( 'Scan ID: %s — The scan is running in the background. This page will update automatically.', 'ultraguard-security-suite' ), $active_scan['scan_id'] ?? '' ),
                ] : [],

                // Stat cards
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Files Scanned',  'ultraguard-security-suite' ), 'value' => $total_scanned,  'format' => 'number', 'icon' => 'dashicons-media-code',       'class' => 'info',    'id' => 'stat-files-scanned','hide_when_empty' => true, ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Threats Found',  'ultraguard-security-suite' ), 'value' => $threats,         'format' => 'number', 'icon' => 'dashicons-warning',          'class' => $threats > 0 ? 'warning' : 'success', 'id' => 'stat-threats','hide_when_empty' => true, ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Quarantined',    'ultraguard-security-suite' ), 'value' => $quarantined,     'format' => 'number', 'icon' => 'dashicons-lock',             'class' => $quarantined > 0 ? 'warning' : 'success', 'id' => 'stat-quarantined','hide_when_empty' => true, ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Signatures',     'ultraguard-security-suite' ), 'value' => $signatures,      'format' => 'number', 'icon' => 'dashicons-admin-network',    'class' => 'info',    'id' => 'stat-signatures','hide_when_empty' => true, ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Open Vulns',     'ultraguard-security-suite' ), 'value' => $open_vulns,      'format' => 'number', 'icon' => 'dashicons-unlock',           'class' => $open_vulns > 0 ? 'warning' : 'success','hide_when_empty' => true, ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Critical Vulns', 'ultraguard-security-suite' ), 'value' => $critical_vulns,  'format' => 'number', 'icon' => 'dashicons-warning',          'class' => $critical_vulns > 0 ? 'error' : 'success','hide_when_empty' => true, ] ],
                    ],
                ],

                // Scan status panel — rendered via RenderEngine (progress + structured buttons)
                $this->build_scan_panel_scheme( $active_scan, $is_running, $nonce, $last_scan_at ),

                // ── Charts row: Threat trend (line) + Scan breakdown (doughnut) ──
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 8,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Threats Detected — Last 30 Days', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-line',
                                'data'  => [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'line',
                                        'height'         => '240px',
                                        'labels'         => $threat_trend['labels'],
                                        'datasets'       => [
                                            [
                                                'label'           => __( 'Threats', 'ultraguard-security-suite' ),
                                                'data'            => $threat_trend['data'],
                                                'borderColor'     => '#ef4444',
                                                'backgroundColor' => 'rgba(239,68,68,0.12)',
                                                'fill'            => true,
                                                'tension'         => 0.4,
                                                'pointRadius'     => 3,
                                            ],
                                        ],
                                        'x_axis_title'   => __( 'Date', 'ultraguard-security-suite' ),
                                        'y_axis_title'   => __( 'Threats', 'ultraguard-security-suite' ),
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Scan Results by Status', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-pie',
                                'data'  => empty( $status_breakdown['data'] ) ? [
                                    [ 'type' => 'paragraph', 'content' => __( 'No scan data yet. Run your first scan to see results here.', 'ultraguard-security-suite' ) ],
                                ] : [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'doughnut',
                                        'height'         => '240px',
                                        'labels'         => $status_breakdown['labels'],
                                        'datasets'       => [
                                            [
                                                'data'            => $status_breakdown['data'],
                                                'backgroundColor' => $status_breakdown['colors'],
                                                'borderWidth'     => 2,
                                            ],
                                        ],
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],

                // ── Charts row: Threat type breakdown (bar) ───────────────────
                ! empty( $threat_types['data'] ) ? [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 12,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Top Threat Types', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-bar',
                                'data'  => [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'bar',
                                        'height'         => '220px',
                                        'labels'         => $threat_types['labels'],
                                        'datasets'       => [
                                            [
                                                'label'           => __( 'Occurrences', 'ultraguard-security-suite' ),
                                                'data'            => $threat_types['data'],
                                                'backgroundColor' => array_map(
                                                    fn( $c ) => str_replace( ')', ',0.75)', str_replace( 'rgb', 'rgba', $c ) ),
                                                    $threat_types['colors']
                                                ),
                                                'borderColor'     => $threat_types['colors'],
                                                'borderWidth'     => 1,
                                            ],
                                        ],
                                        'x_axis_title'   => __( 'Threat Type', 'ultraguard-security-suite' ),
                                        'y_axis_title'   => __( 'Count', 'ultraguard-security-suite' ),
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                    ],
                ] : [],
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 8,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Recent Threats', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-warning',
                                'actions' => [
                                    [ 'type' => 'button', 'text' => __( 'View All', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'size' => 'small', 'url' => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=malware-detection' ) ],
                                ],
                                'data'  => $this->build_recent_threats( $recent_threats, $nonce ),
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Quick Actions', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-admin-tools',
                                'data'  => [
                                    [
                                        'type'      => 'html',
                                        'content'   => $this->build_quick_actions( $nonce ),
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],
            ] ) ),
        ];

        return $scheme;
    }

    /**
     * Build the scan status card with table-based stats layout.
     * Uses allow_unsafe_html:true so inline style on the progress fill is preserved.
     */
    private function build_scan_panel_scheme( array $scan, bool $running, string $nonce, string $last_scan_at ): array {
        $progress  = (int) ( $scan['progress'] ?? 0 );
        $scan_id   = esc_attr( $scan['scan_id'] ?? '' );
        $scan_type = ! empty( $scan['scan_type'] ) ? ucfirst( (string) $scan['scan_type'] ) : '';

        $data = [
            [
                'type'          => 'progress',
                'id'            => 'ug-progress-fill',
                'class'         => $running ? '' : 'ug-hidden',
                'value'         => $progress,
                'max'           => 100,
                'progress_type' => 'bar',
                'status'        => $running ? 'primary' : 'secondary',
                'animated'      => $running,
                'striped'       => $running,
                'label'         => $running
                    /* translators: %d: integer */
                    ? sprintf( __( 'Scanning… %d%%', 'ultraguard-security-suite' ), $progress )
                    : __( 'Scanning… 0%', 'ultraguard-security-suite' ),
                'show_value'    => true,
            ],
        ];

        if ( $running ) {
            $data[] = [
                'type'  => 'list',
                'class' => 'ug-scan-live-stats',
                'items' => [
                    [
                        'icon'  => 'dashicons-media-code',
                        'text'  => __( 'Files Scanned', 'ultraguard-security-suite' ),
                        'badge' => [
                            'text'       => number_format_i18n( (int) ( $scan['files_scanned'] ?? 0 ) ),
                            'badge_type' => 'info',
                        ],
                    ],
                    [
                        'icon'  => 'dashicons-warning',
                        'text'  => __( 'Threats Found', 'ultraguard-security-suite' ),
                        'badge' => [
                            'text'       => number_format_i18n( (int) ( $scan['threats_found'] ?? 0 ) ),
                            'badge_type' => ( (int) ( $scan['threats_found'] ?? 0 ) > 0 ) ? 'danger' : 'success',
                        ],
                    ],
                ],
            ];

            if ( ! empty( $scan['current_file'] ) ) {
                $data[] = [
                    'type'    => 'paragraph',
                    'class'   => 'ug-scan-current-file',
                    'content' => esc_html( '…' . substr( (string) $scan['current_file'], -60 ) ),
                ];
            }
        } else {
            $data[] = [
                'type'    => 'paragraph',
                'class'   => 'ug-scan-status-note',
                'content' => __( 'No scan in progress. Run a scan to check your site.', 'ultraguard-security-suite' ),
            ];
        }

        $buttons = [];
        if ( $running ) {
            $buttons[] = [
                'type'         => 'button',
                'text'         => __( 'Stop Scan', 'ultraguard-security-suite' ),
                'button_style' => 'secondary',
                'icon'         => 'dashicons-no-alt',
                'id'           => 'ug-stop-scan-btn',
                'class'        => 'ug-stop-scan-btn',
                'ajax'         => [
                    'action' => 'ultraguard_antivirus_stop_scan',
                    'nonce'  => $nonce,
                    'data'   => [ 'scan_id' => $scan_id ],
                ],
            ];
        } else {
            $buttons[] = [ 'type' => 'button', 'text' => __( 'Quick Scan', 'ultraguard-security-suite' ), 'button_style' => 'primary', 'icon' => 'dashicons-search', 'class' => 'ultraguard-start-scan-btn', 'attributes' => [ 'data-rt' => 'antivirus-scan-btn' ], 'ajax' => [ 'action' => 'ultraguard_antivirus_start_scan', 'nonce' => $nonce, 'data' => [ 'scan_type' => 'quick' ] ] ];
            $buttons[] = [ 'type' => 'button', 'text' => __( 'Full Scan', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'icon' => 'dashicons-shield', 'class' => 'ultraguard-start-scan-btn', 'ajax' => [ 'action' => 'ultraguard_antivirus_start_scan', 'nonce' => $nonce, 'data' => [ 'scan_type' => 'full' ] ] ];
            $buttons[] = [ 'type' => 'button', 'text' => __( 'Custom Path', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'icon' => 'dashicons-folder-open', 'class' => 'ultraguard-start-scan-btn', 'ajax' => [ 'action' => 'ultraguard_antivirus_start_scan', 'nonce' => $nonce, 'data' => [ 'scan_type' => 'custom' ] ], 'attributes' => [ 'data-custom-path-input' => 'ug-custom-path-input' ] ];
        }
        $data[] = [ 'type' => 'button-group', 'alignment' => 'left', 'id' => 'ug-scan-actions', 'buttons' => $buttons ];

        return [
            'type'       => 'card',
            'id'         => 'ug-scan-panel',
            'title'      => __( 'Scan Status', 'ultraguard-security-suite' ),
            'icon'       => 'dashicons-search',
            'badge'      => [
                'text'       => $running ? ( $scan_type ? $scan_type . ' — ' . __( 'Running', 'ultraguard-security-suite' ) : __( 'Running', 'ultraguard-security-suite' ) ) : __( 'Idle', 'ultraguard-security-suite' ),
                'badge_type' => $running ? 'warning' : 'secondary',
            ],
            'attributes' => [ 'data-scan-id' => $scan_id, 'data-nonce' => $nonce, 'data-running' => $running ? '1' : '0' ],
            'data'       => $data,
            'footer'     => /* translators: %1$s: label, %2$s: date/time value */
            esc_html( sprintf( '%1$s %2$s', __( 'Last scan:', 'ultraguard-security-suite' ), $last_scan_at ) ),
        ];
    }

    private function build_recent_threats( array $threats, string $nonce ): array {
        if ( empty( $threats ) ) {
            return [ [ 'type' => 'paragraph', 'content' => __( '✓ No threats found. Your site appears clean.', 'ultraguard-security-suite' ) ] ];
        }
        $rows = array_map( function( $r ) use ( $nonce ) {
            $level_class = match ( $r['threat_level'] ?? 'medium' ) {
                'critical' => 'danger', 'high' => 'warning', default => 'info'
            };
            return [
                'file'    => basename( $r['file_path'] ),
                'path'    => $r['file_path'],
                'threat'  => $r['threat_type'] ?? 'Unknown',
                'level'   => [ 'content' => ucfirst( $r['threat_level'] ?? 'unknown' ), 'class' => $level_class ],
                'found'   => $r['created_at'],
                'actions' => [
                    $this->create_ajax_button( __( 'Quarantine', 'ultraguard-security-suite' ), 'ultraguard_antivirus_quarantine_file', [ 'result_id' => $r['id'] ], 'warning', 'dashicons-lock', __( 'Move this file to quarantine?', 'ultraguard-security-suite' ) ),
                    $this->create_ajax_button( __( 'False Positive', 'ultraguard-security-suite' ), 'ultraguard_antivirus_mark_false_positive', [ 'result_id' => $r['id'] ], 'secondary' ),
                ],
            ];
        }, $threats );

        return [ [
            'type'    => 'data-table',
            'id'      => 'recent-threats-table',
            'columns' => [
                'file'   => [ 'title' => __( 'File',         'ultraguard-security-suite' ) ],
                'threat' => [ 'title' => __( 'Threat',       'ultraguard-security-suite' ) ],
                'level'  => [ 'title' => __( 'Severity',     'ultraguard-security-suite' ) ],
                'found'  => [ 'title' => __( 'Detected At',  'ultraguard-security-suite' ), 'sortable' => true ],
                'actions'=> [ 'title' => __( 'Actions',      'ultraguard-security-suite' ) ],
            ],
            'data'    => $rows,
        ] ];
    }

    private function build_quick_actions( string $nonce ): string {
        $links = [
            [ 'icon' => 'dashicons-search',       'label' => __( 'File Scanner',      'ultraguard-security-suite' ), 'url' => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=file-scanner' ) ],
            [ 'icon' => 'dashicons-warning',      'label' => __( 'Detections',        'ultraguard-security-suite' ), 'url' => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=malware-detection' ) ],
            [ 'icon' => 'dashicons-unlock',       'label' => __( 'Vulnerabilities',   'ultraguard-security-suite' ), 'url' => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=vulnerability-scanner' ) ],
            [ 'icon' => 'dashicons-lock',         'label' => __( 'Quarantine',        'ultraguard-security-suite' ), 'url' => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=quarantine' ) ],
            [ 'icon' => 'dashicons-admin-settings','label' => __( 'Settings',         'ultraguard-security-suite' ), 'url' => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=scanner-settings' ) ],
        ];
        $out = '<div class="ug-quick-action-list">';
        foreach ( $links as $l ) {
            $out .= sprintf(
                '<a href="%s" class="ug-quick-action-item"><span class="dashicons %s"></span><span>%s</span><span class="dashicons dashicons-arrow-right-alt2"></span></a>',
                esc_url( $l['url'] ), esc_attr( $l['icon'] ), esc_html( $l['label'] )
            );
        }
        $out .= '</div>';
        return $out;
    }
}
