<?php
// ESSB Analytics Dashboard - Modern Professional Dashboard

// Get current view and parameters
$current_view = isset($_GET['view']) ? sanitize_text_field($_GET['view']) : 'dashboard';
$period = isset($_GET['period']) ? sanitize_text_field($_GET['period']) : '30days';
$date_from = isset($_GET['date_from']) ? sanitize_text_field($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? sanitize_text_field($_GET['date_to']) : '';
$network_filter = isset($_GET['network_filter']) ? sanitize_text_field($_GET['network_filter']) : '';
$position_filter = isset($_GET['position_filter']) ? sanitize_text_field($_GET['position_filter']) : '';
$device_filter = isset($_GET['device_filter']) ? sanitize_text_field($_GET['device_filter']) : '';
$detail_view = isset($_GET['detail_view']) ? sanitize_text_field($_GET['detail_view']) : 'positions';
$detail_item = isset($_GET['detail_item']) ? sanitize_text_field($_GET['detail_item']) : '';

// Include required files FIRST
require_once dirname(__FILE__) . '/essb-analytics-helpers.php';
require_once dirname(__FILE__) . '/essb-analytics-functions.php';

// Calculate date range based on period
list($date_from, $date_to) = essb_calculate_date_range($period, $date_from, $date_to);
$prev_date_from = date('Y-m-d', strtotime($date_from . ' - ' . essb_get_period_days($period) . ' days'));
$prev_date_to = date('Y-m-d', strtotime($date_to . ' - ' . essb_get_period_days($period) . ' days'));

// Get stats based on period
$stats = essb_get_period_stats($date_from, $date_to);
$prev_stats = essb_get_period_stats($prev_date_from, $prev_date_to);

// Output CSS directly
include_once dirname(__FILE__) . '/essb-analytics-styles.php';
essb_render_analytics_styles();
?>

<div class="essb-analytics-wrap">   
    <!-- Navigation Tabs -->
    <div class="essb-analytics-nav">
        <nav class="essb-nav-tabs">
            <a href="<?php echo essb_get_tab_url('dashboard', $period, $date_from, $date_to); ?>" class="essb-nav-tab <?php echo $current_view == 'dashboard' ? 'active' : ''; ?>">
                Dashboard
            </a>
            <a href="<?php echo essb_get_tab_url('networks', $period, $date_from, $date_to); ?>" class="essb-nav-tab <?php echo $current_view == 'networks' ? 'active' : ''; ?>">
                Networks
            </a>
            <a href="<?php echo essb_get_tab_url('positions', $period, $date_from, $date_to); ?>" class="essb-nav-tab <?php echo $current_view == 'positions' ? 'active' : ''; ?>">
                Positions
            </a>
            <a href="<?php echo essb_get_tab_url('content', $period, $date_from, $date_to); ?>" class="essb-nav-tab <?php echo $current_view == 'content' ? 'active' : ''; ?>">
                Content
            </a>
            <a href="<?php echo essb_get_tab_url('device', $period, $date_from, $date_to); ?>" class="essb-nav-tab <?php echo $current_view == 'device' ? 'active' : ''; ?>">
                Device
            </a>
            <a href="<?php echo essb_get_tab_url('heatmap', $period, $date_from, $date_to); ?>" class="essb-nav-tab <?php echo $current_view == 'heatmap' ? 'active' : ''; ?>">
                Heatmap
            </a>
            <a href="<?php echo essb_get_tab_url('trends', $period, $date_from, $date_to); ?>" class="essb-nav-tab <?php echo $current_view == 'trends' ? 'active' : ''; ?>">
                Trends
            </a>

        <div class="essb-period-filter">
            <div class="essb-period-select-wrapper">
                <select id="essb-period-select" class="essb-period-select">
                    <option value="today" <?php echo $period == 'today' ? 'selected' : ''; ?>>Today</option>
                    <option value="yesterday" <?php echo $period == 'yesterday' ? 'selected' : ''; ?>>Yesterday</option>
                    <option value="7days" <?php echo $period == '7days' ? 'selected' : ''; ?>>Last 7 Days</option>
                    <option value="14days" <?php echo $period == '14days' ? 'selected' : ''; ?>>Last 14 Days</option>
                    <option value="30days" <?php echo $period == '30days' ? 'selected' : ''; ?>>Last 30 Days</option>
                    <option value="year" <?php echo $period == 'year' ? 'selected' : ''; ?>>This Year</option>
                    <option value="all" <?php echo $period == 'all' ? 'selected' : ''; ?>>All Time</option>
                    <option value="custom" <?php echo $period == 'custom' ? 'selected' : ''; ?>>Custom Range</option>
                </select>
                
                <div id="custom-range-container" class="essb-custom-range" style="<?php echo $period == 'custom' ? '' : 'display: none;'; ?>">
                    <input type="date" id="custom-date-from" value="<?php echo esc_attr($date_from); ?>" placeholder="Start date">
                    <span>to</span>
                    <input type="date" id="custom-date-to" value="<?php echo esc_attr($date_to); ?>" placeholder="End date">
                    <button id="apply-custom-range" class="essb-btn essb-btn-primary">Apply</button>
                </div>
            </div>
        </div>			
        </nav>
    </div>
    
    <div class="essb-analytics-content">
        <?php
        // Load the appropriate view
        $view_file = dirname(__FILE__) . '/views/view-' . $current_view . '.php';
        if (file_exists($view_file)) {
            include_once $view_file;
        } else {
            include_once dirname(__FILE__) . '/views/view-dashboard.php';
        }
        ?>
    </div>
</div>

<script type="text/javascript">
jQuery(document).ready(function($) {
    // Store the current period and dates
    var currentPeriod = '<?php echo esc_js($period); ?>';
    var currentDateFrom = '<?php echo esc_js($date_from); ?>';
    var currentDateTo = '<?php echo esc_js($date_to); ?>';
    var currentView = '<?php echo esc_js($current_view); ?>';
    
    // Store the original dropdown value to prevent auto-submit
    var $periodSelect = $('#essb-period-select');
    var originalValue = $periodSelect.val();
    
    // Helper function to build URL with parameters
    function buildAnalyticsUrl(view, period, dateFrom, dateTo, additionalParams) {
        var params = new URLSearchParams();
        params.set('page', 'essb_redirect_analytics');
        params.set('tab', 'analytics');
        params.set('view', view);
        params.set('period', period);
        
        // Only add date_from and date_to if period is custom AND dates are provided
        if (period === 'custom' && dateFrom && dateTo) {
            params.set('date_from', dateFrom);
            params.set('date_to', dateTo);
        }
        
        // Add additional parameters
        if (additionalParams) {
            for (var key in additionalParams) {
                if (additionalParams[key]) {
                    params.set(key, additionalParams[key]);
                }
            }
        }
        
        var url = 'admin.php?' + params.toString();
        console.log('Building URL:', url);
        return url;
    }
    
    // Handle period select change - prevent default and handle manually
    $periodSelect.on('mousedown', function(e) {
        // Store the current value before change
        originalValue = $periodSelect.val();
    });
    
    $periodSelect.on('change', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        var selectedPeriod = $(this).val();
        var $customRange = $('#custom-range-container');
        
        console.log('Period changed to:', selectedPeriod);
        
        if (selectedPeriod === 'custom') {
            // Show custom range inputs
            $customRange.show();
            // Reset the select back to the original value (don't actually change it)
            $periodSelect.val(originalValue);
            // Focus on the first date input
            $('#custom-date-from').focus();
        } else {
            // Hide custom range if visible
            $customRange.hide();
            // Build URL and redirect with the selected period
            var url = buildAnalyticsUrl(currentView, selectedPeriod, '', '');
            console.log('Redirecting to:', url);
            window.location.href = url;
        }
    });
    
    // Handle custom range apply
    $('#apply-custom-range').on('click', function(e) {
        e.preventDefault();
        
        var dateFrom = $('#custom-date-from').val();
        var dateTo = $('#custom-date-to').val();
        
        console.log('Apply custom range clicked:', dateFrom, dateTo);
        
        if (!dateFrom || !dateTo) {
            alert('Please select both start and end dates');
            return;
        }
        
        if (dateFrom > dateTo) {
            alert('Start date must be before or equal to end date');
            return;
        }
        
        // Build URL with custom period and dates
        var url = buildAnalyticsUrl(currentView, 'custom', dateFrom, dateTo);
        console.log('Redirecting to custom range URL:', url);
        window.location.href = url;
    });
    
    // Handle filter forms (network, position, device filters)
    $('form.essb-filter-form, .essb-filter-bar form').each(function() {
        var $form = $(this);
        
        $form.on('submit', function(e) {
            e.preventDefault();
            
            // Get form data
            var formData = $(this).serializeArray();
            var additionalParams = {};
            
            $.each(formData, function(i, field) {
                if (field.name !== 'page' && field.name !== 'tab' && field.name !== 'view' && 
                    field.name !== 'period' && field.name !== 'date_from' && field.name !== 'date_to') {
                    additionalParams[field.name] = field.value;
                }
            });
            
            var url = buildAnalyticsUrl(currentView, currentPeriod, currentDateFrom, currentDateTo, additionalParams);
            window.location.href = url;
        });
    });
    
    // Handle filter selects that don't have a form
    $('.essb-filter-select').on('change', function() {
        var $select = $(this);
        var paramName = $select.attr('name');
        var paramValue = $select.val();
        
        var additionalParams = {};
        if (paramName && paramValue) {
            additionalParams[paramName] = paramValue;
        }
        
        var url = buildAnalyticsUrl(currentView, currentPeriod, currentDateFrom, currentDateTo, additionalParams);
        window.location.href = url;
    });
    
    // Prevent any other form submissions that might interfere
    $('form').on('submit', function(e) {
        // Allow our specific forms, but prevent others
        if (!$(this).hasClass('essb-filter-form') && !$(this).closest('.essb-filter-bar').length) {
            // Check if this is the period filter form
            if ($(this).find('#essb-period-select').length) {
                e.preventDefault();
                return false;
            }
        }
    });
});
</script>