<?php
// Device View
$desktop_clicks = $stats->desktop_clicks;
$mobile_clicks = $stats->mobile_clicks;
$total_clicks = $stats->total_clicks;

$desktop_percentage = ($total_clicks > 0) ? ($desktop_clicks / $total_clicks) * 100 : 0;
$mobile_percentage = ($total_clicks > 0) ? ($mobile_clicks / $total_clicks) * 100 : 0;

// Determine which device is better
$better_device = $desktop_clicks > $mobile_clicks ? 'Desktop' : 'Mobile';
$better_percentage = max($desktop_percentage, $mobile_percentage);

// Get device-specific network performance
$device_networks = essb_get_network_performance_by_device($date_from, $date_to);

// Prepare network table data
$network_table_data = array();
foreach($device_networks as $network) {
    $total = $network->desktop_clicks + $network->mobile_clicks;
    $network_table_data[] = array(
        'name' => strtolower($network->network),
        'display_name' => essb_stats_get_network_name($network->network),
        'desktop_clicks' => $network->desktop_clicks,
        'mobile_clicks' => $network->mobile_clicks,
        'total_clicks' => $total,
        'desktop_percent' => round($network->desktop_percentage, 1),
        'mobile_percent' => round($network->mobile_percentage, 1),
        'device_preference' => $network->desktop_clicks > $network->mobile_clicks ? 'Desktop' : 'Mobile'
    );
}

// Get position performance by device - FIXED: Properly iterate through all positions
$position_data = essb_get_position_performance_by_device($date_from, $date_to);
$all_positions = ESSBSocialShareAnalyticsBackEnd::$positions;

foreach($all_positions as $position) {
    $desktop_pos_clicks = essb_get_position_clicks_by_device($position, 'desktop', $date_from, $date_to);
    $mobile_pos_clicks = essb_get_position_clicks_by_device($position, 'mobile', $date_from, $date_to);
    
    // Include positions with any clicks
    if ($desktop_pos_clicks > 0 || $mobile_pos_clicks > 0) {
        $total = $desktop_pos_clicks + $mobile_pos_clicks;
        $desktop_percent = $total > 0 ? round(($desktop_pos_clicks / $total) * 100, 1) : 0;
        $mobile_percent = $total > 0 ? round(($mobile_pos_clicks / $total) * 100, 1) : 0;
        
        $position_data[] = array(
            'name' => strtolower($position),
            'display_name' => ESSBSocialShareAnalyticsBackEnd::position_name($position),
            'desktop_clicks' => $desktop_pos_clicks,
            'mobile_clicks' => $mobile_pos_clicks,
            'total_clicks' => $total,
            'desktop_percent' => $desktop_percent,
            'mobile_percent' => $mobile_percent,
            'device_preference' => $desktop_pos_clicks > $mobile_pos_clicks ? 'Desktop' : ($mobile_pos_clicks > $desktop_pos_clicks ? 'Mobile' : 'Equal')
        );
    }
}

// Sort position data by total clicks
usort($position_data, function($a, $b) {
    return $b['total_clicks'] - $a['total_clicks'];
});

// Get chart data for device comparison
$chart_data = essb_get_device_chart_data($date_from, $date_to);
$chart_labels = array();
$desktop_chart_values = array();
$mobile_chart_values = array();

foreach($chart_data as $data) {
    $chart_labels[] = $data['label'];
    $desktop_chart_values[] = $data['desktop'];
    $mobile_chart_values[] = $data['mobile'];
}
?>

<!-- Device Overview Panel -->
<div class="essb-kpi-grid" style="grid-template-columns: 1fr;">
    <div class="essb-kpi-card">
        <div class="essb-device-comparison">
            <div class="essb-device-stat essb-device-stat-left">
                <div class="essb-kpi-title">Desktop Clicks</div>
                <div class="essb-kpi-value"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($desktop_clicks); ?></div>
            </div>
            <div class="essb-device-stat essb-device-stat-right">
                <div class="essb-kpi-title">Mobile Clicks</div>
                <div class="essb-kpi-value"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($mobile_clicks); ?></div>
            </div>
        </div>
        
        <!-- Comparison Progress Bar -->
        <div class="essb-comparison-bar">
            <div class="essb-comparison-label">
                <span>Desktop</span>
                <span>Mobile</span>
            </div>
            <div class="essb-comparison-track">
                <div class="essb-comparison-fill essb-comparison-desktop" style="width: <?php echo $desktop_percentage; ?>%"></div>
                <div class="essb-comparison-fill essb-comparison-mobile" style="width: <?php echo $mobile_percentage; ?>%"></div>
            </div>
            <div class="essb-comparison-percent">
                <span><?php echo round($desktop_percentage, 1); ?>%</span>
                <span><?php echo round($mobile_percentage, 1); ?>%</span>
            </div>
        </div>
        
        <div class="essb-kpi-sub" style="margin-top: 12px; text-align: center;">
            <?php echo $better_device; ?> is the preferred device with <?php echo round($better_percentage, 1); ?>% of total clicks
        </div>
    </div>
</div>

<!-- Device Performance Comparison Chart -->
<div class="essb-chart-container">
    <div class="essb-chart-title">Device Performance Comparison (<?php echo date('M j, Y', strtotime($date_from)); ?> - <?php echo date('M j, Y', strtotime($date_to)); ?>)</div>
    
    <?php if (!empty($chart_labels) && count($chart_labels) > 0): ?>
    <canvas id="device-comparison-chart" style="height: 400px; width: 100%;"></canvas>
    <?php else: ?>
        <div class="essb-empty-state">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                <path d="M21 16v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2"/>
                <path d="M7 10l3-3 3 3 4-4"/>
                <path d="M17 10V4h-6"/>
            </svg>
            <p>No device data available for this period</p>
            <p class="essb-empty-state-sub">Try selecting a different date range or wait for more data to be collected.</p>
        </div>
    <?php endif; ?>
</div>

<!-- Two Column Layout for Network and Position Performance -->
<div class="essb-two-columns">
    <!-- Network Performance by Device -->
    <div class="essb-chart-container">
        <div class="essb-chart-title">
            Network Performance by Device
            <div class="essb-table-controls">
                <input type="text" id="network-device-search" class="essb-table-search" placeholder="Search networks...">
                <select id="network-device-rows" class="essb-table-rows">
                    <option value="10">10 rows</option>
                    <option value="25" selected>25 rows</option>
                    <option value="50">50 rows</option>
                </select>
            </div>
        </div>
        
        <div class="essb-table-wrapper">
            <table class="essb-modern-table" id="network-device-table">
                <thead>
                    <tr>
                        <th data-sort="name" class="sortable">Network <span class="sort-icon">↕</span></th>
                        <th data-sort="desktop" class="sortable">Desktop <span class="sort-icon">↕</span></th>
                        <th data-sort="desktop_percent" class="sortable">Desktop % <span class="sort-icon">↕</span></th>
                        <th data-sort="mobile" class="sortable">Mobile <span class="sort-icon">↕</span></th>
                        <th data-sort="mobile_percent" class="sortable">Mobile % <span class="sort-icon">↕</span></th>
                        <th data-sort="preference" class="sortable">Preference <span class="sort-icon">↕</span></th>
                    </thead>
                <tbody id="network-device-body">
                    <!-- Table body will be populated by JavaScript -->
                </tbody>
              </table>
            <div class="essb-table-footer">
                <div class="essb-table-info">Showing <span id="network-device-start">0</span> to <span id="network-device-end">0</span> of <span id="network-device-total">0</span> entries</div>
                <div class="essb-table-pagination">
                    <button class="essb-pagination-btn" data-page="prev" data-table="network-device" disabled>Previous</button>
                    <span class="essb-pagination-pages" data-table="network-device"></span>
                    <button class="essb-pagination-btn" data-page="next" data-table="network-device" disabled>Next</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Position Performance by Device -->
    <div class="essb-chart-container">
        <div class="essb-chart-title">
            Position Performance by Device
            <div class="essb-table-controls">
                <input type="text" id="position-device-search" class="essb-table-search" placeholder="Search positions...">
                <select id="position-device-rows" class="essb-table-rows">
                    <option value="10">10 rows</option>
                    <option value="25" selected>25 rows</option>
                    <option value="50">50 rows</option>
                </select>
            </div>
        </div>
        
        <div class="essb-table-wrapper">
            <table class="essb-modern-table" id="position-device-table">
                <thead>
                    <tr>
                        <th data-sort="name" class="sortable">Position <span class="sort-icon">↕</span></th>
                        <th data-sort="desktop" class="sortable">Desktop <span class="sort-icon">↕</span></th>
                        <th data-sort="desktop_percent" class="sortable">Desktop % <span class="sort-icon">↕</span></th>
                        <th data-sort="mobile" class="sortable">Mobile <span class="sort-icon">↕</span></th>
                        <th data-sort="mobile_percent" class="sortable">Mobile % <span class="sort-icon">↕</span></th>
                        <th data-sort="preference" class="sortable">Preference <span class="sort-icon">↕</span></th>
                    </thead>
                <tbody id="position-device-body">
                    <!-- Table body will be populated by JavaScript -->
                </tbody>
              </table>
            <div class="essb-table-footer">
                <div class="essb-table-info">Showing <span id="position-device-start">0</span> to <span id="position-device-end">0</span> of <span id="position-device-total">0</span> entries</div>
                <div class="essb-table-pagination">
                    <button class="essb-pagination-btn" data-page="prev" data-table="position-device" disabled>Previous</button>
                    <span class="essb-pagination-pages" data-table="position-device"></span>
                    <button class="essb-pagination-btn" data-page="next" data-table="position-device" disabled>Next</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
jQuery(document).ready(function($) {
    // Network device table data
    var networkData = <?php echo json_encode($network_table_data); ?>;
    var positionData = <?php echo json_encode($position_data); ?>;
    
    // Helper function to escape HTML
    function escapeHtml(str) {
        if (!str) return '';
        return str.replace(/[&<>]/g, function(m) {
            if (m === '&') return '&amp;';
            if (m === '<') return '&lt;';
            if (m === '>') return '&gt;';
            return m;
        });
    }
    
    // Helper function to format numbers
    function formatNumber(num) {
        if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
        if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
        return num.toString();
    }
    
    // Generic table renderer
    function initDeviceTable(tableId, data, defaultSort) {
        if (!data || data.length === 0) {
            $('#' + tableId + '-body').html('<tr><td colspan="6" style="text-align: center; padding: 40px;">No data available for this period</td></tr>');
            $('#' + tableId + '-total').text('0');
            return;
        }
        
        var currentPage = 1;
        var rowsPerPage = 25;
        var currentSort = defaultSort;
        var currentSearch = '';
        
        function renderRow(item) {
            var preferenceClass = '';
            if (item.device_preference === 'Desktop') {
                preferenceClass = 'essb-chip-network';
            } else if (item.device_preference === 'Mobile') {
                preferenceClass = 'essb-chip-device';
            } else {
                preferenceClass = 'essb-chip';
            }
            return '<tr>' +
                '<td class="essb-table-network"><span class="essb-chip essb-chip-small ' + preferenceClass + '">' + escapeHtml(item.display_name) + '</span></td>' +
                '<td class="essb-table-number"><strong>' + formatNumber(item.desktop_clicks) + '</strong></td>' +
                '<td class="essb-table-number">' + item.desktop_percent + '%</td>' +
                '<td class="essb-table-number"><strong>' + formatNumber(item.mobile_clicks) + '</strong></td>' +
                '<td class="essb-table-number">' + item.mobile_percent + '%</td>' +
                '<td class="essb-table-number"><span class="essb-chip essb-chip-small ' + preferenceClass + '">' + item.device_preference + '</span></td>' +
                '</tr>';
        }
        
        function sortData(data, column, direction) {
            var sorted = [...data];
            sorted.sort(function(a, b) {
                var aVal, bVal;
                
                if (column === 'name') {
                    aVal = a.name || '';
                    bVal = b.name || '';
                    aVal = aVal.toLowerCase();
                    bVal = bVal.toLowerCase();
                } else if (column === 'desktop') {
                    aVal = a.desktop_clicks || 0;
                    bVal = b.desktop_clicks || 0;
                } else if (column === 'desktop_percent') {
                    aVal = a.desktop_percent || 0;
                    bVal = b.desktop_percent || 0;
                } else if (column === 'mobile') {
                    aVal = a.mobile_clicks || 0;
                    bVal = b.mobile_clicks || 0;
                } else if (column === 'mobile_percent') {
                    aVal = a.mobile_percent || 0;
                    bVal = b.mobile_percent || 0;
                } else if (column === 'preference') {
                    aVal = a.device_preference || '';
                    bVal = b.device_preference || '';
                } else {
                    return 0;
                }
                
                if (direction === 'asc') {
                    return aVal > bVal ? 1 : -1;
                } else {
                    return aVal < bVal ? 1 : -1;
                }
            });
            return sorted;
        }
        
        function filterData(data, searchTerm) {
            if (!searchTerm) return data;
            return data.filter(function(item) {
                return item.name.indexOf(searchTerm.toLowerCase()) > -1;
            });
        }
        
        function renderTable() {
            var filteredData = filterData(data, currentSearch);
            var sortedData = sortData(filteredData, currentSort.column, currentSort.direction);
            var totalRows = sortedData.length;
            var totalPages = Math.ceil(totalRows / rowsPerPage);
            
            if (currentPage > totalPages) currentPage = totalPages || 1;
            var start = (currentPage - 1) * rowsPerPage;
            var end = Math.min(start + rowsPerPage, totalRows);
            var pageData = sortedData.slice(start, end);
            
            var $tbody = $('#' + tableId + '-body');
            $tbody.empty();
            
            for (var i = 0; i < pageData.length; i++) {
                $tbody.append(renderRow(pageData[i]));
            }
            
            $('#' + tableId + '-start').text(totalRows > 0 ? start + 1 : 0);
            $('#' + tableId + '-end').text(end);
            $('#' + tableId + '-total').text(totalRows);
            
            var $prevBtn = $('.essb-pagination-btn[data-table="' + tableId + '"][data-page="prev"]');
            var $nextBtn = $('.essb-pagination-btn[data-table="' + tableId + '"][data-page="next"]');
            var $pagesContainer = $('.essb-pagination-pages[data-table="' + tableId + '"]');
            
            $prevBtn.prop('disabled', currentPage === 1);
            $nextBtn.prop('disabled', currentPage === totalPages || totalPages === 0);
            
            $pagesContainer.empty();
            if (totalPages > 0) {
                var maxPages = Math.min(totalPages, 5);
                var startPage = Math.max(1, currentPage - 2);
                var endPage = Math.min(totalPages, startPage + maxPages - 1);
                
                for (var p = startPage; p <= endPage; p++) {
                    var $pageBtn = $('<button>').addClass('essb-page-btn').text(p);
                    if (p === currentPage) $pageBtn.addClass('active');
                    $pageBtn.on('click', function() {
                        currentPage = parseInt($(this).text());
                        renderTable();
                    });
                    $pagesContainer.append($pageBtn);
                }
            }
        }
        
        $('#' + tableId + '-search').on('keyup', function() {
            currentSearch = $(this).val();
            currentPage = 1;
            renderTable();
        });
        
        $('#' + tableId + '-rows').on('change', function() {
            rowsPerPage = parseInt($(this).val());
            currentPage = 1;
            renderTable();
        });
        
        $('#' + tableId + '-table th.sortable').on('click', function() {
            var $th = $(this);
            var column = $th.data('sort');
            var sortIcon = $th.find('.sort-icon');
            
            if (currentSort.column === column) {
                currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
            } else {
                currentSort.column = column;
                currentSort.direction = 'desc';
            }
            
            $('#' + tableId + '-table th .sort-icon').text('↕');
            sortIcon.text(currentSort.direction === 'asc' ? '↑' : '↓');
            
            currentPage = 1;
            renderTable();
        });
        
        $(document).on('click', '.essb-pagination-btn[data-table="' + tableId + '"][data-page="prev"]', function() {
            if (currentPage > 1) {
                currentPage--;
                renderTable();
            }
        });
        
        $(document).on('click', '.essb-pagination-btn[data-table="' + tableId + '"][data-page="next"]', function() {
            var totalPages = Math.ceil(filterData(data, currentSearch).length / rowsPerPage);
            if (currentPage < totalPages) {
                currentPage++;
                renderTable();
            }
        });
        
        renderTable();
    }
    
    // Initialize tables
    initDeviceTable('network-device', networkData, { column: 'desktop', direction: 'desc' });
    initDeviceTable('position-device', positionData, { column: 'desktop', direction: 'desc' });
    
    // Device Comparison Chart with filled dots and no vertical lines
    <?php if (!empty($chart_labels) && count($chart_labels) > 0): ?>
    function createDeviceChart() {
        var ctx = document.getElementById('device-comparison-chart').getContext('2d');
        
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: <?php echo json_encode($chart_labels); ?>,
                datasets: [
                    {
                        label: 'Desktop Clicks',
                        data: <?php echo json_encode($desktop_chart_values); ?>,
                        borderColor: '#3b82f6',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        borderWidth: 3,
                        pointRadius: 4,
                        pointHoverRadius: 6,
                        pointBackgroundColor: '#3b82f6',
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 2,
                        pointHoverBackgroundColor: '#2563eb',
                        pointHoverBorderColor: '#ffffff',
                        tension: 0.4,
                        fill: true
                    },
                    {
                        label: 'Mobile Clicks',
                        data: <?php echo json_encode($mobile_chart_values); ?>,
                        borderColor: '#10b981',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        borderWidth: 3,
                        pointRadius: 4,
                        pointHoverRadius: 6,
                        pointBackgroundColor: '#10b981',
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 2,
                        pointHoverBackgroundColor: '#059669',
                        pointHoverBorderColor: '#ffffff',
                        tension: 0.4,
                        fill: true
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        position: 'top',
                        labels: { usePointStyle: true, boxWidth: 8, font: { size: 12 } }
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': ' + formatNumber(context.parsed.y);
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            display: true,
                            color: '#e2e8f0',
                            drawBorder: false,
                            drawTicks: true
                        },
                        ticks: {
                            callback: function(value) {
                                return formatNumber(value);
                            },
                            font: { size: 11 }
                        }
                    },
                    x: {
                        grid: {
                            display: false // No vertical lines
                        },
                        ticks: {
                            maxRotation: 45,
                            minRotation: 45,
                            autoSkip: true,
                            maxTicksLimit: 15,
                            font: { size: 10 }
                        }
                    }
                }
            }
        });
    }
    
    if (typeof Chart === 'undefined') {
        var script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js';
        script.onload = function() {
            createDeviceChart();
        };
        document.head.appendChild(script);
    } else {
        createDeviceChart();
    }
    <?php endif; ?>
});
</script>