<?php
/**
 * Dashboard Shortcode
 * 
 * @package Spacetree
 * @subpackage Dashboard
 */

// Include the Dashboard class
require_once plugin_dir_path( __FILE__ ) . 'class-dashboard.php';

// Include AJAX handlers
require_once plugin_dir_path( __FILE__ ) . 'dashboard-ajax.php';

add_shortcode('proqyz-dashboard', 'shortcode_proqyz_dashboard');
add_shortcode('ilms-dashboard', 'shortcode_proqyz_dashboard');

function shortcode_proqyz_dashboard( $atts = [], $content = null, $tag = '' ) {
    // Check if user is logged in
    if ( ! is_user_logged_in() ) {
        return proqyz_dashboard_login_notice();
    }
    
        // Enqueue st-grid.css (will only load once even if multiple shortcodes)
        proqyz_enqueue_st_grid_styles();
        
    // Enqueue dashboard JavaScript
    proqyz_enqueue_dashboard_scripts();
    
    // Parse shortcode attributes
    $atts = array_change_key_case( (array) $atts, CASE_LOWER );
        $wporg_atts = shortcode_atts(
            array(
                'type' => 'dashboard'
        ), $atts, $tag
    );

    // Initialize dashboard class with current user ID
    $dashboard = new ST_Dashboard( get_current_user_id() );
    
    // Get current user data
    $current_user = $dashboard->get_current_user();
    $user_role = $dashboard->get_role();
    
    // Get courses
    $courses = $dashboard->get_courses();
    $courses_count = $dashboard->get_courses_count();
    
    // Get quiz analytics
    $quizzes_analytics = $dashboard->get_quizzes_analytics();
    
    // Get memory usage
    $memory_usage = $dashboard->get_memory_usage();
    
    // Get widgets
    $widgets = $dashboard->get_widgets_by_role();
    $widgets_html = $dashboard->render_widgets( $widgets );

        // Start output buffering
        ob_start(); ?>

        <div class="st dashboard-page my-dashboard-page test-history-page">
            <div id="overlay-region">&nbsp;</div>
            <div class="st-container">
                <div class="st-row">
                    <div class="st-col-xs-12 st-col-sm-3 st-col-left">
                        <div class="dashboard-menu">
                            <div class="dashboard-menu__mobile visible-xs" id="js-menudb-mobile"> 
                                <a class="dashboard-menu__link" href="javascript:;">
                                    <span class="st-icon ioticon-home"></span> My Dashboard
                                </a>
                            </div>
                            <ul class="dashboard-menu__list" id="dashboard-menu__list" aria-expanded="true" style="">
                                <li class="dashboard-menu__item active"> 
                                    <a class="dashboard-menu__link" href="javascript:;" data-proqyz-type="router" data-proqyz-action="proqyz-ajax-my-dashboard"> 
                                        <span class="st-icon ioticon-home"></span>My Dashboard
                                    </a>
                                </li>
                                <li class="dashboard-menu__item"> 
                                    <a class="dashboard-menu__link" href="javascript:;" data-proqyz-type="router" data-proqyz-action="proqyz-ajax-ielts-listening"> 
                                        <span class="st-icon ioticon-live-support-agent-headset"></span> Listening
                                    </a>
                                </li>
                                <li class="dashboard-menu__item"> 
                                    <a class="dashboard-menu__link" href="javascript:;" data-proqyz-type="router" data-proqyz-action="proqyz-ajax-ielts-reading"> 
                                        <span class="st-icon ioticon-book-open"></span> Reading
                                    </a>
                                </li>
                                <li class="dashboard-menu__item"> 
                                    <a class="dashboard-menu__link" href="javascript:;" data-proqyz-type="router" data-proqyz-action="proqyz-ajax-ielts-writing"> 
                                        <span class="st-icon ioticon-edit-3"></span> Writing
                                    </a>
                                </li>
                                <li class="dashboard-menu__item"> 
                                    <a class="dashboard-menu__link" href="javascript:;" data-proqyz-type="router" data-proqyz-action="proqyz-ajax-ielts-speaking"> 
                                        <span class="st-icon ioticon-announcement-speaker"></span> Speaking
                                    </a>
                                </li>
                                <li class="dashboard-menu__item"> 
                                    <a class="dashboard-menu__link" href="javascript:;" data-proqyz-type="router" data-proqyz-action="proqyz-ajax-load-gov-sectional-non-sectional-timing"> 
                                        <span class="st-icon ioticon-competitive-exams"></span> Competitive Exams
                                    </a>
                                </li>
                                <li class="dashboard-menu__item"> 
                                    <a class="dashboard-menu__link" href="javascript:;" data-proqyz-type="router" data-proqyz-action="proqyz-ajax-load-pdf-quiz"> 
                                        <span class="st-icon ioticon-pdf-quiz"></span> PDF Quiz
                                    </a>
                                </li>
                                <?php if ( $dashboard->get_role() === 'admin' ) : ?>
                                <li class="dashboard-menu__item"> 
                                    <a class="dashboard-menu__link" href="javascript:;" data-proqyz-type="router" data-proqyz-action="proqyz-ajax-abandoned-tests"> 
                                        <span class="st-icon ioticon-trash-3"></span> Abandoned Tests
                                    </a>
                                </li>
                                <?php endif; ?>
                            </ul>
                        </div>
                    </div>
                
                    <div class="st-col-xs-12 st-col-sm-9 st-col-right">
                        <div class="dashboard-content">
                            <!-- Dashboard Tab Content -->
                            <div class="dashboard-tab-content" data-tab="dashboard" data-ajax-response="true">
                                <!-- Preloader Skeleton -->
                                <div class="dashboard-preloader">
                                    <h1 class="section-title skeleton-title"></h1>
                                    
                                    <!-- Widgets Skeleton -->
                                    <section class="performance-board">
                                        <div class="performance-board__item-wrap">
                                            <div class="performance-board__item skeleton-widget">
                                                <div class="skeleton-icon"></div>
                                                <div class="skeleton-text skeleton-text-sm"></div>
                                                <div class="skeleton-text skeleton-text-lg"></div>
                                            </div>
                                            <div class="performance-board__item skeleton-widget">
                                                <div class="skeleton-icon"></div>
                                                <div class="skeleton-text skeleton-text-sm"></div>
                                                <div class="skeleton-text skeleton-text-lg"></div>
                                            </div>
                                            <div class="performance-board__item skeleton-widget">
                                                <div class="skeleton-icon"></div>
                                                <div class="skeleton-text skeleton-text-sm"></div>
                                                <div class="skeleton-text skeleton-text-lg"></div>
                                            </div>
                                            <div class="performance-board__item skeleton-widget">
                                                <div class="skeleton-icon"></div>
                                                <div class="skeleton-text skeleton-text-sm"></div>
                                                <div class="skeleton-text skeleton-text-lg"></div>
                                            </div>
                                        </div>
                                    </section>
                                    
                                    <br />
                                    
                                    <h1 class="section-title skeleton-title"></h1>
                                    
                                    <!-- Table Skeleton -->
                                    <section class="test-history">
                                        <div class="test-history__filter skeleton-filters">
                                            <div class="skeleton-filter"></div>
                                            <div class="skeleton-filter"></div>
                                            <div class="skeleton-filter"></div>
                                            <div class="skeleton-button"></div>
                                            <div class="skeleton-button-round"></div>
                                        </div>
                                        
                                        <table class="table table-hover history-table iot-responsive-table skeleton-table">
                                            <thead>
                                                <tr>
                                                    <th><div class="skeleton-text"></div></th>
                                                    <th><div class="skeleton-text"></div></th>
                                                    <th><div class="skeleton-text"></div></th>
                                                    <th><div class="skeleton-text"></div></th>
                                                    <th><div class="skeleton-text"></div></th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td><div class="skeleton-text"></div></td>
                                                    <td><div class="skeleton-text skeleton-text-long"></div></td>
                                                    <td><div class="skeleton-text"></div></td>
                                                    <td><div class="skeleton-text"></div></td>
                                                    <td><div class="skeleton-text"></div></td>
                                                </tr>
                                                <tr>
                                                    <td><div class="skeleton-text"></div></td>
                                                    <td><div class="skeleton-text skeleton-text-long"></div></td>
                                                    <td><div class="skeleton-text"></div></td>
                                                    <td><div class="skeleton-text"></div></td>
                                                    <td><div class="skeleton-text"></div></td>
                                                </tr>
                                                <tr>
                                                    <td><div class="skeleton-text"></div></td>
                                                    <td><div class="skeleton-text skeleton-text-long"></div></td>
                                                    <td><div class="skeleton-text"></div></td>
                                                    <td><div class="skeleton-text"></div></td>
                                                    <td><div class="skeleton-text"></div></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                        
                                        <!-- Pagination Skeleton -->
                                        <div class="test-history__bottom">
                                            <div class="test-history__per-page">
                                                <div class="skeleton-text" style="width: 50px; height: 16px; margin-right: 8px;"></div>
                                                <div class="skeleton-filter" style="width: 80px; height: 32px;"></div>
                                            </div>
                                            <div class="pager">
                                                <ul class="pager__items">
                                                    <li class="pager__item"><div class="skeleton-button" style="width: 60px; height: 32px;"></div></li>
                                                    <li class="pager__item"><div class="skeleton-button" style="width: 60px; height: 32px;"></div></li>
                                                    <li class="pager__item"><div class="skeleton-button" style="width: 35px; height: 32px;"></div></li>
                                                    <li class="pager__item"><div class="skeleton-button" style="width: 60px; height: 32px;"></div></li>
                                                    <li class="pager__item"><div class="skeleton-button" style="width: 60px; height: 32px;"></div></li>
                                                </ul>
                                            </div>
                                        </div>
                                    </section>
                                </div>
                            </div>
                            <!-- Memory Usage (Debug Info) -->
                            <div style="background: #f0f0f1; padding: 15px; margin: 20px 0; border-radius: 5px; border-left: 4px solid #2271b1; display: none;">
                                <h3 style="margin-top: 0;">📊 Memory Usage</h3>
                                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                                    <div style="background: white; padding: 10px; border-radius: 4px;">
                                        <strong>Current:</strong> <?php echo $memory_usage->current; ?>
                                    </div>
                                    <div style="background: white; padding: 10px; border-radius: 4px;">
                                        <strong>Peak:</strong> <?php echo $memory_usage->peak; ?>
                                    </div>
                                    <div style="background: white; padding: 10px; border-radius: 4px;">
                                        <strong>Limit:</strong> <?php echo $memory_usage->limit; ?>
                                    </div>
                                    <div style="background: white; padding: 10px; border-radius: 4px;">
                                        <strong>Usage:</strong> <?php echo $memory_usage->percentage; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Debug Data -->
                            <details style="margin: 20px 0; display: none;">
                                <summary style="cursor: pointer; font-weight: 600; padding: 10px; background: #f0f0f1; border-radius: 4px;">Debug Data (Click to expand)</summary>
                                <div style="margin-top: 10px;">
                                    <h3>User Details</h3>
                                    <pre><?php echo print_r($current_user, true); ?></pre>
                                    
                                    <h3>Courses (<?php echo $courses_count; ?>)</h3>
                                    <pre><?php echo print_r($courses, true); ?></pre>
                                    
                                    <h3>Quiz Analytics</h3>
                                    <pre><?php echo print_r($quizzes_analytics, true); ?></pre>
                                    
                                    <h3>Widgets</h3>
                                    <pre><?php echo print_r($widgets, true); ?></pre>
                                </div>
                            </details>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 
        Hidden JSON Data for AJAX/JavaScript Access 
        Usage in JavaScript:
        var userData = JSON.parse(document.getElementById('json-users-data').textContent);
        var courses = JSON.parse(document.getElementById('json-courses-data').textContent);
        var quizzes = JSON.parse(document.getElementById('json-quizz-data').textContent);
        var widgets = JSON.parse(document.getElementById('json-widgets-data').textContent);
        var memory = JSON.parse(document.getElementById('json-memory-data').textContent);
        -->
        <script id="json-users-data" type="application/json"><?php echo wp_json_encode( $current_user ); ?></script>
        <script id="json-courses-data" type="application/json"><?php echo wp_json_encode( $courses ); ?></script>
        <script id="json-quizz-data" type="application/json"><?php echo wp_json_encode( $quizzes_analytics ); ?></script>
        <script id="json-widgets-data" type="application/json"><?php echo wp_json_encode( $widgets ); ?></script>
        <script id="json-memory-data" type="application/json"><?php echo wp_json_encode( $memory_usage ); ?></script>
        
        <!-- AJAX Configuration -->
        <script type="text/javascript">
            var proqyzDashboard = {
                ajaxUrl: '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>',
                nonce: '<?php echo wp_create_nonce( 'proqyz_dashboard_ajax' ); ?>',
                currentUser: <?php echo wp_json_encode( $current_user ); ?>
            };
        </script>
        
        <?php 
        // Get the buffered content and clean the buffer
    $html_content = ob_get_clean();
    
        // Return the HTML content
        return $html_content;
}

/**
 * Display Bootstrap-style login notice
 * 
 * Returns a simple alert notice when user is not logged in
 * 
 * @return string HTML notice
 */
function proqyz_dashboard_login_notice() {
    ob_start(); ?>
    <div class="st-alert st-alert-warning" role="alert" style="display: flex; align-items: center; justify-content: space-between; padding: 12px 20px; background-color: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; color: #856404; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; margin: 20px 0;">
        <span style="font-size: 15px; font-weight: 500;">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: text-bottom; margin-right: 8px;">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                <circle cx="12" cy="7" r="4"></circle>
            </svg>
            Please log in to access your dashboard and continue your learning journey.
        </span>
        <a href="<?php echo esc_url( wp_login_url( get_permalink() ) ); ?>" style="display: inline-block; background-color: #856404; color: #ffffff; padding: 8px 20px; border-radius: 4px; text-decoration: none; font-weight: 600; font-size: 14px; white-space: nowrap; margin-left: 15px; transition: background-color 0.3s ease;">
            Log In
        </a>
    </div>
    <?php
    return ob_get_clean();
}

/**
 * Enqueue st-grid.css for shortcodes
 * Uses static variable to ensure it only enqueues once per page load
 */
function proqyz_enqueue_st_grid_styles() {
    static $enqueued = false;
    
    if ( $enqueued ) {
        return; // Already enqueued, skip
    }
    
    // Get plugin directory URL
    $plugin_dir = plugin_dir_url( ST_PROQYZ_PLUGIN_FILE );
    $css_url = $plugin_dir . 'includes/public/shortcodes/dashboard/dist/css/st-grid.css';
    $menu_css_url = $plugin_dir . 'includes/public/shortcodes/dashboard/dist/css/dashboard-menu.css';
    $utils_css_url = $plugin_dir . 'includes/public/shortcodes/dashboard/dist/css/st-utils.css';
    $fonts_css_url = $plugin_dir . 'includes/public/shortcodes/dashboard/dist/css/st-fonts.css';
    $dashboard_css_url = $plugin_dir . 'includes/public/shortcodes/dashboard/dist/css/dashboard.css';
    $icons_css_url = $plugin_dir . 'includes/public/shortcodes/dashboard/dist/css/st-icons.css';
    $chart_css_url = $plugin_dir . 'includes/public/shortcodes/dashboard/dist/css/dashboard-chartjs.css';
    
    // Enqueue the stylesheet
    wp_enqueue_style( 
        'st-grid', 
        $css_url, 
        array(), 
        ST_VERSION 
    );

    wp_enqueue_style( 
        'st-dashboard-menu', 
        $menu_css_url, 
        array(), 
        ST_VERSION 
    );

    wp_enqueue_style( 
        'st-utils', 
        $utils_css_url, 
        array(), 
        ST_VERSION 
    );
    
    wp_enqueue_style( 
        'st-dashboard-fonts', 
        $fonts_css_url, 
        array(), 
        ST_VERSION 
    );

    wp_enqueue_style( 
        'st-dashboard', 
        $dashboard_css_url, 
        array(), 
        ST_VERSION 
    );

    wp_enqueue_style( 
        'st-icons', 
        $icons_css_url, 
        array(), 
        ST_VERSION 
    );

    wp_enqueue_style( 
        'st-dashboard-chartjs', 
        $chart_css_url, 
        array(), 
        ST_VERSION 
    );

    $enqueued = true; // Mark as enqueued
}

/**
 * Enqueue dashboard JavaScript
 * Uses static variable to ensure it only enqueues once per page load
 */
function proqyz_enqueue_dashboard_scripts() {
    static $enqueued = false;
    
    if ( $enqueued ) {
        return; // Already enqueued, skip
    }
    
    // Get plugin directory URL
    $plugin_dir = plugin_dir_url( ST_PROQYZ_PLUGIN_FILE );
    
    // CDN URLs - Bootstrap 3.4.1 and Bootstrap Select 1.13.14
    $bootstrap_js = 'https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/js/bootstrap.min.js';
    $bootstrap_select_css_url = $plugin_dir . 'includes/public/shortcodes/dashboard/dist/css/st-bootstrap-select.css'; // custom styling
    $bootstrap_select_js = 'https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js';
    
    // Dashboard JS and Chart.js
    $js_url = $plugin_dir . 'includes/public/shortcodes/dashboard/dist/js/dashboard.js';
    $chart_js_url = $plugin_dir . 'includes/public/shortcodes/dashboard/dist/js/Chart.bundle.js';
    
    // 1. Enqueue custom Bootstrap Select CSS
    wp_enqueue_style( 
        'st-bootstrap-select', 
        $bootstrap_select_css_url, 
        array(), 
        ST_VERSION 
    );
    
    // 2. Enqueue Bootstrap 3.4.1 JS (requires jQuery, no Popper needed for Bootstrap 3)
    wp_enqueue_script( 
        'bootstrap', 
        $bootstrap_js, 
        array( 'jquery' ), 
        '3.4.1',
        true
    );
    
    // 3. Enqueue Bootstrap Select 1.13.14 JS (requires jQuery and Bootstrap)
    wp_enqueue_script( 
        'bootstrap-select', 
        $bootstrap_select_js, 
        array( 'jquery', 'bootstrap' ), 
        '1.13.14',
        true
    );
    
    // 4. Enqueue Chart.js Bundle for progress analytics charts
    wp_enqueue_script( 
        'st-chart-js', 
        $chart_js_url, 
        array( 'jquery' ), 
        ST_VERSION,
        true // Load in footer
    );
    
    // 5. Enqueue Dashboard JavaScript
    wp_enqueue_script( 
        'st-dashboard-js', 
        $js_url, 
        array( 'jquery', 'bootstrap', 'bootstrap-select', 'st-chart-js' ), 
        ST_VERSION,
        true // Load in footer
    );

    $enqueued = true; // Mark as enqueued
}
