<?php
defined("ABSPATH") || exit;
/**
 * Shared Technical Analysis Widget Builder
 *
 * Used by: oscillators, moving_averages, pivot_points widgets
 * Each widget shows a specific section of the technical analysis component.
 */

/**
 * @param string $slug       Widget slug
 * @param array  $sections   Section visibility for the view (e.g., showAllSections, enableOscillatorsGauge)
 * @param array  $flags      Feature flags: hasGauge, hasTable, hasMetrics, isFull
 */
function vunelix_build_technical_widget(string $slug, array $sections, array $flags = []): array {

    $vunelix_shared = require __DIR__ . '/../_shared_fields.php';

    $hasGauge   = $flags['hasGauge'] ?? false;
    $hasTable   = $flags['hasTable'] ?? false;
    $hasMetrics = $flags['hasMetrics'] ?? false;
    $isFull     = $flags['isFull'] ?? false;

    $vunelix_defaults = array_merge([
        'symbol'                   => 'BINANCE:BTCUSD',
        'default_period'           => '1D',
        'enable_metrics_cards'     => $hasMetrics,
        'enable_summary_gauge'     => true,
        'enable_timeframe_buttons' => true,
        'enable_timeframe_icons'   => true,
        'enable_title'             => $isFull,
        'enable_gauge'             => true,
        'enable_gauge_labels'      => true,
        'enable_signal_label'      => true,
        'enable_stats_counts'      => true,
        'enable_stats_scores'      => true,
        'enable_table'             => true,
        'enable_table_value'       => true,
        'enable_table_score'       => true,
        'enable_table_action'      => true,
    ], $vunelix_shared['defaults']['storage']);


    $vunelix_widget = [
        'slug'      => $slug,
        'component' => 'vunelix-' . $slug,
        'js'        => 'widgets/technical/vunelix-' . $slug . '.js',

        'view' => 'Fx_live/Views/components/technical',

        'icons' => ['trending-up', 'trending-down', 'star', 'minus', 'chevron-up', 'chevron-down', 'strong-buy', 'strong-sell'],

        'lang_key' => 'symbol_detail',

        'branding_position' => 'top-right',
        'branding_offset_x' => 20,
        'branding_offset_y' => 0,

        'defaults' => $vunelix_defaults,

        'config_map' => array_merge([
            'default_period'            => 'defaultPeriod',
            'enable_timeframe_buttons'  => 'enableTimeframeButtons',
            'enable_table_value'        => 'enableTableValue',
            'enable_table_score'        => 'enableTableScore',
            'enable_table_action'       => 'enableTableAction',
        ], $vunelix_shared['config_map']['storage']),

        'view_aliases' => [],

        'buildViewData' => function(array $viewData, array $config) use ($sections, $hasGauge): array {
            // Show symbol header in widget
            $viewData['showSymbolHeader'] = true;

            // Set section visibility variables for the view
            foreach ($sections as $key => $value) {
                $viewData[$key] = $value;
            }

            // Config boolean toggles → override matching section keys
            $boolMap = [
                'enable_metrics_cards'     => 'enableMetricsCards',
                'enable_timeframe_buttons' => 'enableTimeframeButtons',
                'enable_timeframe_icons'   => 'enableTimeframeIcons',
                'enable_summary_gauge'     => 'enableSummaryGauge',
                'enable_title'             => 'enableTitle',
            ];
            foreach ($boolMap as $cfgKey => $viewKey) {
                if (isset($config[$cfgKey])) {
                    $viewData[$viewKey] = (bool)$config[$cfgKey];
                }
            }

            // Default period for active button
            $viewData['defaultPeriod'] = $config['default_period'] ?? '1d';

            // Gauge toggle — force all gauge keys off
            if ($hasGauge && isset($config['enable_gauge']) && !(bool)$config['enable_gauge']) {
                foreach (['enableGaugesSection', 'enableSummaryGauge', 'enableOscillatorsGauge', 'enableMovingAveragesGauge'] as $k) {
                    $viewData[$k] = false;
                }
            }

            // Table toggle — force all table keys off
            if (isset($config['enable_table']) && !(bool)$config['enable_table']) {
                foreach (['enableTablesSection', 'enableOscillatorsTable', 'enableMovingAveragesTable', 'enablePivotsTable'] as $k) {
                    $viewData[$k] = false;
                }
            }

            // Title toggle
            $viewData['enableTitle'] = (bool)($config['enable_title'] ?? ($viewData['enableTitle'] ?? true));

            // Gauge sub-toggles
            $viewData['enableGaugeLabels']  = (bool)($config['enable_gauge_labels'] ?? true);
            $viewData['enableSignalLabel']  = (bool)($config['enable_signal_label'] ?? true);
            $viewData['enableStatsCounts']  = (bool)($config['enable_stats_counts'] ?? true);
            $viewData['enableStatsScores']  = (bool)($config['enable_stats_scores'] ?? true);

            // Table column toggles
            $viewData['enableTableValue']  = (bool)($config['enable_table_value'] ?? true);
            $viewData['enableTableScore']  = (bool)($config['enable_table_score'] ?? true);
            $viewData['enableTableAction'] = (bool)($config['enable_table_action'] ?? true);

            return $viewData;
        },

        'buildJsConfig' => function(array $config): array {
            $jsConfig = [];

            // Parse "EXCHANGE:SYMBOL" format from symbol-picker
            $raw = $config['symbol'] ?? 'BINANCE:BTCUSD';
            if (strpos($raw, ':') !== false) {
                [$exchange, $symbol] = explode(':', $raw, 2);
                $jsConfig['exchange'] = $exchange;
                $jsConfig['symbol']   = $symbol;
            } else {
                $jsConfig['symbol']   = $raw;
                $jsConfig['exchange'] = '';
            }

            return $jsConfig;
        },

        'settings' => [
            'data' => [
                'label' => 'Data',
                'pkg'   => 1,
                'fields' => [
                    'symbol' => [
                        'type'        => 'symbol-picker',
                        'full_width'  => true,
                        'label'       => 'Symbol',
                        'description' => 'Search and pick any stock, crypto, or forex pair to display.',
                        'default'     => 'BINANCE:BTCUSD',
                        'key'         => 'symbol',
                        'pkg'         => 1,
                        'multiple'    => false,
                    ],
                    'default_period' => [
                        'type'        => 'select',
                        'label'       => 'Timeframe',
                        'description' => 'Time interval for technical calculations (e.g. 1 Day analyzes daily data, 1 Hour analyzes hourly data).',
                        'default'     => '1d',
                        'key'         => 'default_period',
                        'pkg'         => 1,
                        'options'     => array_diff_key(vunelix_time_period_list(), ['120' => '']),
                    ],
                ],
            ],
            'display' => [
                'label' => 'Display',
                'pkg'   => 1,
                'fields' => array_merge(
                // --- Metrics Cards ---
                [
                    'enable_metrics_cards' => [
                        'type'        => 'toggle',
                        'label'       => 'Metrics Cards',
                        'description' => 'Show Score, Confidence, Trend, and Volatility summary cards at the top of the widget.',
                        'default'     => $hasMetrics,
                        'key'         => 'enable_metrics_cards',
                        'pkg'         => 1,
                    ],
                ],
                // --- Timeframe ---
                [
                    'enable_timeframe_buttons' => [
                        'type'        => 'toggle',
                        'label'       => 'Timeframe Buttons',
                        'description' => 'Show buttons (1m, 5m, 15m, 1h, 4h, 1D, 1W, 1M) that let visitors switch between timeframes.',
                        'default'     => true,
                        'key'         => 'enable_timeframe_buttons',
                        'pkg'         => 1,
                    ],
                ],
                // --- Timeframe Icons (full only) ---
                $isFull ? [
                    'enable_timeframe_icons' => [
                        'type'        => 'toggle',
                        'label'       => 'Timeframe Signal Icons',
                        'description' => 'Show small up/down arrow icons on each timeframe button indicating the Buy/Sell signal for that timeframe.',
                        'default'     => true,
                        'key'         => 'enable_timeframe_icons',
                        'pkg'         => 1,
                    ],
                ] : [],
                // --- Titles (not for full/metrics) ---
                (!$isFull && !$hasMetrics) ? [
                    'enable_title' => [
                        'type'        => 'toggle',
                        'label'       => 'Section Titles',
                        'description' => 'Show headings like "Oscillators", "Moving Averages", "Pivots" above each section.',
                        'default'     => false,
                        'key'         => 'enable_title',
                        'pkg'         => 1,
                    ],
                ] : [],
                // --- Summary Gauge (full only) ---
                $isFull ? [
                    'enable_summary_gauge' => [
                        'type'        => 'toggle',
                        'label'       => 'Summary Gauge',
                        'description' => 'The main summary gauge combining oscillators and moving averages.',
                        'default'     => true,
                        'key'         => 'enable_summary_gauge',
                        'pkg'         => 1,
                    ],
                ] : [],
                // --- Gauge Chart ---
                $hasGauge ? [
                    'enable_gauge' => [
                        'type'        => 'toggle',
                        'label'       => $isFull ? 'Oscillators & MA Gauges' : ($hasMetrics ? 'Summary Gauge' : 'Gauge Chart'),
                        'description' => $isFull ? 'The oscillators and moving averages gauge charts.' : ($hasMetrics ? 'The overall summary gauge combining all signals.' : 'The gauge chart with needle showing signal direction.'),
                        'default'     => true,
                        'key'         => 'enable_gauge',
                        'pkg'         => 1,
                    ],
                    'enable_gauge_labels' => [
                        'type'        => 'toggle',
                        'label'       => 'Gauge Signal Labels',
                        'description' => 'Show Strong Sell, Sell, Neutral, Buy, Strong Buy labels around the gauge arc.',
                        'default'     => true,
                        'key'         => 'enable_gauge_labels',
                        'pkg'         => 1,
                    ],
                    'enable_signal_label' => [
                        'type'        => 'toggle',
                        'label'       => 'Signal Result Text',
                        'description' => 'Show the overall result text below the needle (e.g. "Strong Buy" or "Sell").',
                        'default'     => true,
                        'key'         => 'enable_signal_label',
                        'pkg'         => 1,
                    ],
                    'enable_stats_counts' => [
                        'type'        => 'toggle',
                        'label'       => 'Sell / Neutral / Buy Counts',
                        'description' => 'Show how many indicators are Sell, Neutral, or Buy below the gauge.',
                        'default'     => true,
                        'key'         => 'enable_stats_counts',
                        'pkg'         => 1,
                    ],
                    'enable_stats_scores' => [
                        'type'        => 'toggle',
                        'label'       => 'Sell / Neutral / Buy Scores',
                        'description' => 'Show the total score numbers for Sell, Neutral, and Buy below the counts.',
                        'default'     => true,
                        'key'         => 'enable_stats_scores',
                        'pkg'         => 1,
                    ],
                ] : [],
                // --- Data Table ---
                $hasTable ? [
                    'enable_table' => [
                        'type'        => 'toggle',
                        'label'       => 'Data Table',
                        'description' => 'Show the detailed indicators table with Name, Value, Score, and Action columns.',
                        'default'     => true,
                        'key'         => 'enable_table',
                        'pkg'         => 1,
                    ],
                ] : [],
                // --- Table Columns (not for pivot_points) ---
                ($hasTable && !$hasMetrics) ? [
                    'enable_table_value' => [
                        'type'        => 'toggle',
                        'label'       => 'Table: Value Column',
                        'description' => 'Show the current indicator value in the table (e.g. RSI 51.4, EMA 71,035).',
                        'default'     => true,
                        'key'         => 'enable_table_value',
                        'pkg'         => 1,
                    ],
                    'enable_table_score' => [
                        'type'        => 'toggle',
                        'label'       => 'Table: Score Column',
                        'description' => 'Show the numerical score for each indicator (e.g. -25, 100). Higher = more bullish.',
                        'default'     => true,
                        'key'         => 'enable_table_score',
                        'pkg'         => 1,
                    ],
                    'enable_table_action' => [
                        'type'        => 'toggle',
                        'label'       => 'Table: Action Column',
                        'description' => 'Show the Buy, Sell, Neutral, or Strong Buy/Sell signal for each indicator in the table.',
                        'default'     => true,
                        'key'         => 'enable_table_action',
                        'pkg'         => 1,
                    ],
                ] : []),
            ],
        ],
    ];

    return $vunelix_widget;
}
