<?php
/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * Copyright (c) 2025 CastConductor.com. All Rights Reserved.
 * See LICENSE and EULA-v5.2.md for full terms.
 */

/**
 * CastConductor Analytics Dashboard
 * 
 * Admin dashboard page for viewing analytics, managing settings,
 * and exporting reports. Uses Vanilla ES6 + Chart.js.
 * 
 * @package CastConductor
 * @subpackage Analytics
 * @since 5.8.0
 */

if (!defined('ABSPATH')) {
    exit;
}

class CC_Analytics_Dashboard {

    /**
     * Single instance
     */
    private static $instance = null;

    /**
     * Menu slug
     */
    const MENU_SLUG = 'castconductor-analytics';

    /**
     * Get singleton instance
     */
    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct() {
        add_action('admin_menu', [$this, 'register_menu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
    }

    /**
     * Register admin menu item
     */
    public function register_menu() {
        add_submenu_page(
            'castconductor',           // Parent slug
            'Analytics',               // Page title
            'Analytics',               // Menu title
            'manage_options',          // Capability
            self::MENU_SLUG,           // Menu slug
            [$this, 'render_dashboard'] // Callback
        );
    }

    /**
     * Enqueue dashboard assets
     */
    public function enqueue_assets($hook) {
        // Only load on our page
        if ($hook !== 'castconductor_page_' . self::MENU_SLUG) {
            return;
        }
        
        $asset_url = CASTCONDUCTOR_PLUGIN_URL . 'assets/';
        $version = CASTCONDUCTOR_VERSION;
        
        // Chart.js from CDN
        wp_enqueue_script(
            'chartjs',
            'https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js',
            [],
            '4.4.1',
            true
        );
        
        // Leaflet.js for interactive maps (Pro+)
        if (in_array('geo_heatmap', CC_Analytics_Helpers::get_available_features())) {
            wp_enqueue_style(
                'leaflet',
                'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css',
                [],
                '1.9.4'
            );
            wp_enqueue_script(
                'leaflet',
                'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js',
                [],
                '1.9.4',
                true
            );
        }
        
        // Our analytics dashboard JS
        wp_enqueue_script(
            'cc-analytics-dashboard',
            $asset_url . 'js/admin-analytics/index.js',
            ['chartjs', 'wp-api-fetch'],
            $version,
            true
        );
        
        // Dashboard CSS
        wp_enqueue_style(
            'cc-analytics-dashboard',
            $asset_url . 'css/admin-analytics.css',
            [],
            $version
        );
        
        // Localize script with config
        wp_localize_script('cc-analytics-dashboard', 'ccAnalyticsConfig', [
            'apiBase'    => rest_url('castconductor/v5/analytics'),
            'nonce'      => wp_create_nonce('wp_rest'),
            'plan'       => CC_Analytics_Helpers::get_current_plan(),
            'features'   => CC_Analytics_Helpers::get_available_features(),
            'adminUrl'   => admin_url(),
            'upgradeUrl' => 'https://castconductor.com/pricing',
        ]);
    }

    /**
     * Render the dashboard page
     */
    public function render_dashboard() {
        $plan = CC_Analytics_Helpers::get_current_plan();
        $features = CC_Analytics_Helpers::get_available_features();
        ?>
        <div class="wrap cc-analytics-wrap">
            <h1>
                <span class="dashicons dashicons-chart-area"></span>
                CastConductor Analytics
            </h1>
            
            <?php $this->render_plan_badge($plan); ?>
            
            <!-- Period Selector -->
            <div class="cc-analytics-toolbar">
                <div class="cc-period-selector">
                    <button class="cc-period-btn active" data-period="7d">7 Days</button>
                    <button class="cc-period-btn" data-period="30d">30 Days</button>
                    <button class="cc-period-btn" data-period="90d">90 Days</button>
                    <button class="cc-period-btn" data-period="custom">Custom</button>
                </div>
                
                <div class="cc-custom-dates" style="display: none;">
                    <input type="date" id="cc-start-date" />
                    <span>to</span>
                    <input type="date" id="cc-end-date" />
                    <button id="cc-apply-dates" class="button">Apply</button>
                </div>
                
                <div class="cc-toolbar-actions">
                    <button id="cc-export-csv" class="button">
                        <span class="dashicons dashicons-download"></span>
                        Export CSV
                    </button>
                    <button id="cc-refresh" class="button">
                        <span class="dashicons dashicons-update"></span>
                        Refresh
                    </button>
                </div>
            </div>
            
            <!-- Summary Cards -->
            <div class="cc-summary-cards">
                <div class="cc-summary-card" id="card-sessions">
                    <div class="cc-card-icon">
                        <span class="dashicons dashicons-visibility"></span>
                    </div>
                    <div class="cc-card-content">
                        <div class="cc-card-value" id="total-sessions">--</div>
                        <div class="cc-card-label">Total Sessions</div>
                    </div>
                </div>
                
                <div class="cc-summary-card" id="card-devices">
                    <div class="cc-card-icon">
                        <span class="dashicons dashicons-desktop"></span>
                    </div>
                    <div class="cc-card-content">
                        <div class="cc-card-value" id="unique-devices">--</div>
                        <div class="cc-card-label">Unique Devices</div>
                    </div>
                </div>
                
                <div class="cc-summary-card" id="card-duration">
                    <div class="cc-card-icon">
                        <span class="dashicons dashicons-clock"></span>
                    </div>
                    <div class="cc-card-content">
                        <div class="cc-card-value" id="avg-duration">--</div>
                        <div class="cc-card-label">Avg. Duration</div>
                    </div>
                </div>
                
                <div class="cc-summary-card" id="card-views">
                    <div class="cc-card-icon">
                        <span class="dashicons dashicons-images-alt2"></span>
                    </div>
                    <div class="cc-card-content">
                        <div class="cc-card-value" id="total-views">--</div>
                        <div class="cc-card-label">Scene Views</div>
                    </div>
                </div>
            </div>
            
            <!-- Main Charts Row -->
            <div class="cc-charts-row">
                <div class="cc-chart-container cc-chart-large">
                    <h3>Sessions Over Time</h3>
                    <canvas id="sessions-chart"></canvas>
                </div>
                
                <div class="cc-chart-container cc-chart-small">
                    <h3>Device Breakdown</h3>
                    <canvas id="devices-chart"></canvas>
                </div>
            </div>
            
            <!-- Content Performance -->
            <div class="cc-section">
                <h3>
                    <span class="dashicons dashicons-format-video"></span>
                    Content Performance
                </h3>
                <div class="cc-content-filters">
                    <div class="cc-filter-row">
                        <label class="cc-filter-label">Filter by type:</label>
                        <div class="cc-filter-toggles" id="content-type-filters">
                            <!-- Populated dynamically from available_types -->
                        </div>
                    </div>
                    <div class="cc-filter-row cc-search-row">
                        <label class="cc-filter-label">Search:</label>
                        <input type="text" id="content-search" placeholder="Search by name..." class="cc-search-input" />
                        <button type="button" id="content-search-clear" class="button button-small cc-search-clear" style="display:none;">✕</button>
                    </div>
                </div>
                <div class="cc-content-table-wrapper">
                    <table class="wp-list-table widefat fixed striped" id="content-table">
                        <thead>
                            <tr>
                                <th>Content</th>
                                <th>Type</th>
                                <th>Impressions</th>
                                <th>Viewers</th>
                                <th>QR Scans</th>
                            </tr>
                        </thead>
                        <tbody id="content-table-body">
                            <tr><td colspan="5" class="cc-loading">Loading...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Geographic Section (Pro+) -->
            <?php if (in_array('geo_heatmap', $features)): ?>
            <div class="cc-section">
                <h3>
                    <span class="dashicons dashicons-location"></span>
                    Geographic Distribution
                    <button type="button" id="cc-geo-map-toggle" class="button button-secondary cc-geo-map-btn" title="Toggle Map View">
                        <span class="dashicons dashicons-location-alt"></span> Show Map
                    </button>
                </h3>
                
                <!-- Interactive Map (hidden by default, toggled) -->
                <div id="cc-geo-map-container" class="cc-geo-map-container" style="display: none;">
                    <div class="cc-geo-map-toolbar">
                        <div class="cc-geo-map-overlays">
                            <label><input type="checkbox" id="cc-overlay-sessions" checked> Sessions</label>
                            <label><input type="checkbox" id="cc-overlay-heatmap"> Heatmap</label>
                        </div>
                        <button type="button" id="cc-geo-fullscreen" class="button" title="Fullscreen">
                            <span class="dashicons dashicons-fullscreen-alt"></span>
                        </button>
                    </div>
                    <div id="cc-geo-map" class="cc-geo-map"></div>
                </div>
                
                <!-- Geographic Data Tables -->
                <div class="cc-geo-tables-grid">
                    <!-- Countries Table -->
                    <div class="cc-geo-table-wrapper">
                        <h4><span class="dashicons dashicons-admin-site"></span> By Country</h4>
                        <table class="cc-geo-table" id="geo-countries-table">
                            <thead>
                                <tr>
                                    <th>Country</th>
                                    <th>Sessions</th>
                                    <th>Devices</th>
                                </tr>
                            </thead>
                            <tbody id="geo-countries-body">
                                <tr><td colspan="3" class="cc-loading">Loading...</td></tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Cities Table -->
                    <div class="cc-geo-table-wrapper">
                        <h4><span class="dashicons dashicons-building"></span> Top Cities</h4>
                        <table class="cc-geo-table" id="geo-cities-table">
                            <thead>
                                <tr>
                                    <th>City</th>
                                    <th>Country</th>
                                    <th>Sessions</th>
                                </tr>
                            </thead>
                            <tbody id="geo-cities-body">
                                <tr><td colspan="3" class="cc-loading">Loading...</td></tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- DMA Table (US Markets) -->
                    <div class="cc-geo-table-wrapper">
                        <h4><span class="dashicons dashicons-megaphone"></span> US Markets (DMA)</h4>
                        <table class="cc-geo-table" id="geo-dmas-table">
                            <thead>
                                <tr>
                                    <th>Market</th>
                                    <th>Sessions</th>
                                    <th>Devices</th>
                                </tr>
                            </thead>
                            <tbody id="geo-dmas-body">
                                <tr><td colspan="3" class="cc-loading">Loading...</td></tr>
                            </tbody>
                        </table>
                        <p class="cc-geo-dma-note">DMA data requires Roku Ad Framework integration</p>
                    </div>
                </div>
            </div>
            
            <!-- Fullscreen Map Modal -->
            <div id="cc-geo-modal" class="cc-geo-modal" style="display: none;">
                <div class="cc-geo-modal-content">
                    <div class="cc-geo-modal-header">
                        <h2>Geographic Distribution</h2>
                        <button type="button" id="cc-geo-modal-close" class="cc-geo-modal-close" title="Close (ESC)">
                            <span class="dashicons dashicons-no-alt"></span>
                        </button>
                    </div>
                    <div class="cc-geo-modal-toolbar">
                        <label><input type="checkbox" id="cc-modal-overlay-sessions" checked> Sessions</label>
                        <label><input type="checkbox" id="cc-modal-overlay-heatmap"> Heatmap</label>
                    </div>
                    <div id="cc-geo-modal-map" class="cc-geo-modal-map"></div>
                </div>
            </div>
            <?php else: ?>
            <div class="cc-section cc-locked">
                <h3>
                    <span class="dashicons dashicons-location"></span>
                    Geographic Distribution
                    <span class="cc-lock-badge">
                        <span class="dashicons dashicons-lock"></span>
                        Pro
                    </span>
                </h3>
                <div class="cc-upgrade-prompt">
                    <p>See where your viewers are located with geographic heatmaps.</p>
                    <a href="https://castconductor.com/pricing" class="button button-primary">
                        Upgrade to Pro
                    </a>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- Active Sessions (Real-time) -->
            <div class="cc-section">
                <h3>
                    <span class="dashicons dashicons-groups"></span>
                    Active Sessions
                    <span class="cc-badge cc-badge-live" id="active-count-badge">0 active</span>
                </h3>
                <div class="cc-active-sessions-wrapper">
                    <table class="wp-list-table widefat fixed striped" id="active-sessions-table">
                        <thead>
                            <tr>
                                <th>Device</th>
                                <th>Model</th>
                                <th>City</th>
                                <th>Country</th>
                                <th>Zip</th>
                                <th>Duration</th>
                                <th>Scene</th>
                            </tr>
                        </thead>
                        <tbody id="active-sessions-body">
                            <tr><td colspan="7" class="cc-loading">Loading...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Promotional Performance widget removed in v5.8.0 -->
            <!-- Content Performance now shows all content blocks with QR scans column -->
            <!-- Use type filters to view sponsors, promos, shoutouts separately -->
            
            <!-- Settings Section -->
            <div class="cc-section cc-settings-section">
                <h3>
                    <span class="dashicons dashicons-admin-settings"></span>
                    Analytics Settings
                </h3>
                
                <div class="cc-settings-grid">
                    <div class="cc-setting-group">
                        <h4>Data Retention</h4>
                        <p class="description">Configure how long analytics data is stored.</p>
                        
                        <table class="form-table">
                            <tr>
                                <th>Raw Events</th>
                                <td>
                                    <select id="retention-raw-events">
                                        <option value="1">1 day</option>
                                        <option value="7" selected>7 days (recommended)</option>
                                        <option value="14">14 days</option>
                                        <option value="30">30 days</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th>Sessions</th>
                                <td>
                                    <select id="retention-sessions">
                                        <option value="7">7 days</option>
                                        <option value="30" selected>30 days (recommended)</option>
                                        <option value="60">60 days</option>
                                        <option value="90">90 days</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th>Hourly Aggregates</th>
                                <td>
                                    <select id="retention-hourly">
                                        <option value="30">30 days</option>
                                        <option value="90" selected>90 days (recommended)</option>
                                        <option value="180">180 days</option>
                                        <option value="365">365 days</option>
                                    </select>
                                </td>
                            </tr>
                        </table>
                        
                        <button id="save-retention" class="button button-primary">Save Retention Settings</button>
                    </div>
                    
                    <div class="cc-setting-group">
                        <h4>Collection Settings</h4>
                        <p class="description">Choose which content block types to track. Disabling high-volume types (like track info) reduces database size.</p>
                        
                        <div class="cc-collection-toggles" id="collection-settings">
                            <!-- Populated dynamically from settings API -->
                            <p class="cc-loading">Loading...</p>
                        </div>
                        
                        <button id="save-collection" class="button button-primary">Save Collection Settings</button>
                    </div>
                    
                    <div class="cc-setting-group">
                        <h4>Aggregation Status</h4>
                        
                        <div class="cc-status-item">
                            <span class="cc-status-label">Last Hourly:</span>
                            <span class="cc-status-value" id="last-hourly">--</span>
                        </div>
                        <div class="cc-status-item">
                            <span class="cc-status-label">Last Daily:</span>
                            <span class="cc-status-value" id="last-daily">--</span>
                        </div>
                        <div class="cc-status-item">
                            <span class="cc-status-label">Last Pruning:</span>
                            <span class="cc-status-value" id="last-prune">--</span>
                        </div>
                        
                        <button id="run-aggregation" class="button">
                            <span class="dashicons dashicons-update"></span>
                            Run Aggregation Now
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render plan badge
     */
    private function render_plan_badge($plan) {
        $badges = [
            'creator'    => ['label' => 'Creator', 'class' => 'cc-badge-creator'],
            'pro'        => ['label' => 'Pro', 'class' => 'cc-badge-pro'],
            'business'   => ['label' => 'Business', 'class' => 'cc-badge-business'],
            'agency'     => ['label' => 'Agency', 'class' => 'cc-badge-agency'],
            'enterprise' => ['label' => 'Enterprise', 'class' => 'cc-badge-enterprise'],
        ];
        
        $badge = $badges[$plan] ?? ['label' => 'Free', 'class' => 'cc-badge-free'];
        ?>
        <span class="cc-plan-badge <?php echo esc_attr($badge['class']); ?>">
            <?php echo esc_html($badge['label']); ?> Plan
        </span>
        <?php
    }
}
