<?php
// Positions View
$total_clicks = $stats->total_clicks;
$positions_data = array();

foreach($stats->positions as $position => $clicks) {
    $percentage = ($total_clicks > 0) ? ($clicks / $total_clicks) * 100 : 0;
    $positions_data[] = (object)array(
        'name' => $position,
        'label' => ESSBSocialShareAnalyticsBackEnd::position_name($position),
        'clicks' => $clicks,
        'percentage' => $percentage
    );
}

usort($positions_data, function($a, $b) {
    return $b->clicks - $a->clicks;
});

// Get top positions by device
$desktop_positions = array();
$mobile_positions = array();

foreach($stats->positions as $position => $clicks) {
    // Get desktop and mobile breakdown for each position
    $desktop_clicks = essb_get_position_clicks_by_device($position, 'desktop', $date_from, $date_to);
    $mobile_clicks = essb_get_position_clicks_by_device($position, 'mobile', $date_from, $date_to);
    
    if ($desktop_clicks > 0) {
        $desktop_positions[] = (object)array(
            'name' => $position,
            'label' => ESSBSocialShareAnalyticsBackEnd::position_name($position),
            'clicks' => $desktop_clicks
        );
    }
    
    if ($mobile_clicks > 0) {
        $mobile_positions[] = (object)array(
            'name' => $position,
            'label' => ESSBSocialShareAnalyticsBackEnd::position_name($position),
            'clicks' => $mobile_clicks
        );
    }
}

usort($desktop_positions, function($a, $b) {
    return $b->clicks - $a->clicks;
});

usort($mobile_positions, function($a, $b) {
    return $b->clicks - $a->clicks;
});

$top_all = !empty($positions_data) ? $positions_data[0] : null;
$top_desktop = !empty($desktop_positions) ? $desktop_positions[0] : null;
$top_mobile = !empty($mobile_positions) ? $mobile_positions[0] : null;

// Prepare table data as JavaScript array
$table_data = array();
foreach($positions_data as $position) {
    $top_network = essb_get_top_network_for_position($position->name, $date_from, $date_to);
    $top_content = essb_get_top_content_for_position($position->name, $date_from, $date_to);
    
    $table_data[] = array(
        'name' => strtolower($position->label),
        'display_name' => $position->label,
        'clicks' => $position->clicks,
        'percent' => round($position->percentage, 1),
        'percent_raw' => $position->percentage,
        'top_network' => $top_network ? essb_stats_get_network_name($top_network) : '-',
        'top_content' => ($top_content && isset($top_content->essb_post_id)) ? array(
            'id' => $top_content->essb_post_id,
            'title' => substr(get_the_title($top_content->essb_post_id), 0, 40),
            'url' => get_permalink($top_content->essb_post_id)
        ) : null,
        'detail_url' => essb_get_tab_url('detail', $period, $date_from, $date_to) . '&detail_type=position&detail_item=' . urlencode($position->name)
    );
}
?>

<!-- Top Positions Panel -->
<div class="essb-kpi-grid">
    <!-- All Positions -->
    <div class="essb-kpi-card">
        <div class="essb-kpi-title">Top Position (All)</div>
        <div class="essb-chip-wrapper">
            <div class="essb-chip essb-chip-position"><?php echo $top_all ? esc_html($top_all->label) : 'No Data'; ?></div>
            <div class="essb-value-wrapper">
                <div class="essb-kpi-value-small"><?php echo $top_all ? ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($top_all->clicks) : '0'; ?></div>
                <div class="essb-kpi-label-small">clicks</div>
            </div>
        </div>
        <?php if ($top_all && $total_clicks > 0): ?>
        <div class="essb-progress-bar" style="margin-top: 12px;">
            <div class="essb-progress-fill" style="width: <?php echo $top_all->percentage; ?>%"></div>
        </div>
        <div class="essb-kpi-percent"><?php echo round($top_all->percentage, 1); ?>% of total</div>
        <?php endif; ?>
    </div>
    
    <!-- Desktop Positions -->
    <div class="essb-kpi-card">
        <div class="essb-kpi-title">Top Position (Desktop)</div>
        <div class="essb-chip-wrapper">
            <div class="essb-chip essb-chip-position"><?php echo $top_desktop ? esc_html($top_desktop->label) : 'No Data'; ?></div>
            <div class="essb-value-wrapper">
                <div class="essb-kpi-value-small"><?php echo $top_desktop ? ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($top_desktop->clicks) : '0'; ?></div>
                <div class="essb-kpi-label-small">clicks</div>
            </div>
        </div>
        <?php if ($top_desktop && $stats->desktop_clicks > 0): ?>
        <div class="essb-progress-bar" style="margin-top: 12px;">
            <div class="essb-progress-fill" style="width: <?php echo ($top_desktop->clicks / $stats->desktop_clicks) * 100; ?>%"></div>
        </div>
        <div class="essb-kpi-percent"><?php echo round(($top_desktop->clicks / $stats->desktop_clicks) * 100, 1); ?>% of desktop clicks</div>
        <?php endif; ?>
    </div>
    
    <!-- Mobile Positions -->
    <div class="essb-kpi-card">
        <div class="essb-kpi-title">Top Position (Mobile)</div>
        <div class="essb-chip-wrapper">
            <div class="essb-chip essb-chip-position"><?php echo $top_mobile ? esc_html($top_mobile->label) : 'No Data'; ?></div>
            <div class="essb-value-wrapper">
                <div class="essb-kpi-value-small"><?php echo $top_mobile ? ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($top_mobile->clicks) : '0'; ?></div>
                <div class="essb-kpi-label-small">clicks</div>
            </div>
        </div>
        <?php if ($top_mobile && $stats->mobile_clicks > 0): ?>
        <div class="essb-progress-bar" style="margin-top: 12px;">
            <div class="essb-progress-fill" style="width: <?php echo ($top_mobile->clicks / $stats->mobile_clicks) * 100; ?>%"></div>
        </div>
        <div class="essb-kpi-percent"><?php echo round(($top_mobile->clicks / $stats->mobile_clicks) * 100, 1); ?>% of mobile clicks</div>
        <?php endif; ?>
    </div>
</div>

<!-- Positions Table -->
<div class="essb-chart-container">
    <div class="essb-chart-title">
        Detailed Position Report
        <div class="essb-table-controls">
            <input type="text" id="position-table-search" class="essb-table-search" placeholder="Search positions...">
            <select id="position-table-rows" class="essb-table-rows">
                <option value="10">10 rows</option>
                <option value="25" selected>25 rows</option>
                <option value="50">50 rows</option>
                <option value="100">100 rows</option>
            </select>
        </div>
    </div>
    
    <div class="essb-table-wrapper">
        <table class="essb-modern-table" id="positions-table">
            <thead>
                <tr>
                    <th data-sort="name" class="sortable">Position <span class="sort-icon">↕</span></th>
                    <th data-sort="clicks" class="sortable">Total Clicks <span class="sort-icon">↕</span></th>
                    <th data-sort="percent" class="sortable">% of Total <span class="sort-icon">↕</span></th>
                    <th>Top Network</th>
                    <th>Top Content</th>
                    <th>Actions</th>
                </thead>
            <tbody id="positions-table-body">
                <!-- Table body will be populated by JavaScript -->
            </tbody>
        </table>
        <div class="essb-table-footer">
            <div class="essb-table-info">Showing <span id="position-table-start">0</span> to <span id="position-table-end">0</span> of <span id="position-table-total">0</span> entries</div>
            <div class="essb-table-pagination">
                <button class="essb-pagination-btn" data-page="prev" disabled>Previous</button>
                <span class="essb-pagination-pages"></span>
                <button class="essb-pagination-btn" data-page="next" disabled>Next</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
jQuery(document).ready(function($) {
    // Table data from PHP
    var tableData = <?php echo json_encode($table_data); ?>;
    var currentPage = 1;
    var rowsPerPage = 25;
    var currentSort = { column: 'clicks', direction: 'desc' };
    var currentSearch = '';
    
    // Function to render a single row
    function renderRow(item) {
        var percentValue = item.percent_raw !== undefined ? item.percent_raw : item.percent;
        return '<tr>' +
            '<td class="essb-table-position">' +
                '<span class="essb-chip essb-chip-small essb-chip-position">' + escapeHtml(item.display_name) + '</span>' +
            '</td>' +
            '<td class="essb-table-number"><strong>' + formatNumber(item.clicks) + '</strong></td>' +
            '<td class="essb-table-number">' +
                item.percent + '%' +
                '<div class="essb-progress-bar essb-progress-bar-small">' +
                    '<div class="essb-progress-fill" style="width: ' + percentValue + '%;"></div>' +
                '</div>' +
            '</td>' +
            '<td class="essb-table-number">' +
                (item.top_network !== '-' ? '<span class="essb-chip essb-chip-small essb-chip-network">' + escapeHtml(item.top_network) + '</span>' : '-') +
            '</td>' +
            '<td class="essb-table-post">' +
                (item.top_content ? '<a href="' + escapeHtml(item.top_content.url) + '" target="_blank">' + escapeHtml(item.top_content.title) + '</a>' : '-') +
            '</td>' +
            '<td>' +
                '<a href="' + escapeHtml(item.detail_url) + '" class="essb-link-btn">View Details →</a>' +
            '</td>' +
            '</tr>';
    }
    
    // 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();
    }
    
    // Function to sort data
    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 === 'clicks') {
                aVal = a.clicks || 0;
                bVal = b.clicks || 0;
            } else if (column === 'percent') {
                aVal = a.percent_raw !== undefined ? a.percent_raw : a.percent;
                bVal = b.percent_raw !== undefined ? b.percent_raw : b.percent;
            } else {
                return 0;
            }
            
            if (direction === 'asc') {
                return aVal > bVal ? 1 : -1;
            } else {
                return aVal < bVal ? 1 : -1;
            }
        });
        return sorted;
    }
    
    // Function to filter data
    function filterData(data, searchTerm) {
        if (!searchTerm) return data;
        return data.filter(function(item) {
            return item.name.indexOf(searchTerm.toLowerCase()) > -1;
        });
    }
    
    // Function to render the table
    function renderTable() {
        // Filter data
        var filteredData = filterData(tableData, currentSearch);
        
        // Sort data
        var sortedData = sortData(filteredData, currentSort.column, currentSort.direction);
        
        // Update total count
        var totalRows = sortedData.length;
        $('#position-table-total').text(totalRows);
        
        // Calculate pagination
        var totalPages = Math.ceil(totalRows / rowsPerPage);
        if (currentPage > totalPages) currentPage = totalPages || 1;
        var start = (currentPage - 1) * rowsPerPage;
        var end = Math.min(start + rowsPerPage, totalRows);
        
        // Get current page data
        var pageData = sortedData.slice(start, end);
        
        // Build table body
        var $tbody = $('#positions-table-body');
        $tbody.empty();
        
        for (var i = 0; i < pageData.length; i++) {
            $tbody.append(renderRow(pageData[i]));
        }
        
        // Update info
        $('#position-table-start').text(totalRows > 0 ? start + 1 : 0);
        $('#position-table-end').text(end);
        
        // Update pagination buttons
        var $prevBtn = $('.essb-pagination-btn[data-page="prev"]');
        var $nextBtn = $('.essb-pagination-btn[data-page="next"]');
        var $pagesContainer = $('.essb-pagination-pages');
        
        $prevBtn.prop('disabled', currentPage === 1);
        $nextBtn.prop('disabled', currentPage === totalPages || totalPages === 0);
        
        // Update page numbers
        $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);
            }
        }
    }
    
    // Search handler
    $('#position-table-search').on('keyup', function() {
        currentSearch = $(this).val();
        currentPage = 1;
        renderTable();
    });
    
    // Rows per page handler
    $('#position-table-rows').on('change', function() {
        rowsPerPage = parseInt($(this).val());
        currentPage = 1;
        renderTable();
    });
    
    // Sort handler
    $('#positions-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';
        }
        
        $('#positions-table th .sort-icon').text('↕');
        sortIcon.text(currentSort.direction === 'asc' ? '↑' : '↓');
        
        currentPage = 1;
        renderTable();
    });
    
    // Pagination handlers
    $(document).on('click', '.essb-pagination-btn[data-page="prev"]', function() {
        if (currentPage > 1) {
            currentPage--;
            renderTable();
        }
    });
    
    $(document).on('click', '.essb-pagination-btn[data-page="next"]', function() {
        var totalPages = Math.ceil(filterData(tableData, currentSearch).length / rowsPerPage);
        if (currentPage < totalPages) {
            currentPage++;
            renderTable();
        }
    });
    
    // Initial render
    renderTable();
});
</script>