<?php
// Content View
$total_clicks = $stats->total_clicks;
$top_posts = essb_get_top_posts($date_from, $date_to, 100); // Get up to 100 posts for pagination

// Prepare table data
$content_table_data = array();
foreach($top_posts as $post) {
    $percentage = $total_clicks > 0 ? ($post->total_clicks / $total_clicks) * 100 : 0;
    $top_network = isset($post->top_network) ? $post->top_network : null;
    $top_position = essb_get_top_position_for_content($post->essb_post_id, $date_from, $date_to);
    
    $content_table_data[] = array(
        'id' => $post->essb_post_id,
        'title' => $post->title ?: 'Untitled',
        'permalink' => $post->permalink,
        'clicks' => $post->total_clicks,
        'desktop_clicks' => $post->desktop_clicks,
        'mobile_clicks' => $post->mobile_clicks,
        'percent' => round($percentage, 1),
        'percent_raw' => $percentage,
        'top_network' => $top_network ? essb_stats_get_network_name($top_network) : '-',
        'top_position' => $top_position ? ESSBSocialShareAnalyticsBackEnd::position_name($top_position) : '-'
    );
}
?>

<div class="essb-chart-container">
    <div class="essb-chart-title">
        Content Performance Report
        <div class="essb-table-controls">
            <input type="text" id="content-table-search" class="essb-table-search" placeholder="Search content...">
            <select id="content-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="content-table">
            <thead>
                <tr>
                    <th data-sort="title" class="sortable">Post / Page <span class="sort-icon">↕</span></th>
                    <th data-sort="clicks" class="sortable">Total Clicks <span class="sort-icon">↕</span></th>
                    <th data-sort="desktop" 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="percent" class="sortable">% of Total <span class="sort-icon">↕</span></th>
                    <th data-sort="network" class="sortable">Top Network <span class="sort-icon">↕</span></th>
                    <th data-sort="position" class="sortable">Top Position <span class="sort-icon">↕</span></th>
                    <th>Actions</th>
                </thead>
            <tbody id="content-table-body">
                <!-- Table body will be populated by JavaScript -->
            </tbody>
        </table>
        <div class="essb-table-footer">
            <div class="essb-table-info">Showing <span id="content-table-start">0</span> to <span id="content-table-end">0</span> of <span id="content-table-total">0</span> entries</div>
            <div class="essb-table-pagination">
                <button class="essb-pagination-btn" data-page="prev" data-table="content" disabled>Previous</button>
                <span class="essb-pagination-pages" data-table="content"></span>
                <button class="essb-pagination-btn" data-page="next" data-table="content" 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($content_table_data); ?>;
    
    // Helper function to escape HTML
    function escapeHtml(str) {
        if (!str) return '';
        return String(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 render a single row
    function renderRow(item) {
        var detailUrl = '<?php echo essb_get_tab_url('detail', $period, $date_from, $date_to); ?>&detail_type=content&detail_item=' + item.id;
        
        return '<tr data-title="' + escapeHtml(item.title.toLowerCase()) + '" ' +
                    'data-clicks="' + item.clicks + '" ' +
                    'data-desktop="' + item.desktop_clicks + '" ' +
                    'data-mobile="' + item.mobile_clicks + '" ' +
                    'data-percent="' + item.percent_raw + '" ' +
                    'data-network="' + escapeHtml(item.top_network.toLowerCase()) + '" ' +
                    'data-position="' + escapeHtml(item.top_position.toLowerCase()) + '">' +
                    '<td class="essb-table-post"><a href="' + escapeHtml(item.permalink) + '" target="_blank">' + escapeHtml(item.title.substring(0, 80)) + '</a></td>' +
                    '<td class="essb-table-number"><strong>' + formatNumber(item.clicks) + '</strong></td>' +
                    '<td class="essb-table-number">' + formatNumber(item.desktop_clicks) + '</td>' +
                    '<td class="essb-table-number">' + formatNumber(item.mobile_clicks) + '</td>' +
                    '<td class="essb-table-number">' +
                        item.percent + '%' +
                        '<div class="essb-progress-bar essb-progress-bar-small">' +
                            '<div class="essb-progress-fill" style="width: ' + item.percent_raw + '%;"></div>' +
                        '</div>' +
                    '</td>' +
                    '<td>' +
                        (item.top_network !== '-' ? '<span class="essb-chip essb-chip-small essb-chip-network">' + escapeHtml(item.top_network) + '</span>' : '-') +
                    '</td>' +
                    '<td>' +
                        (item.top_position !== '-' ? '<span class="essb-chip essb-chip-small essb-chip-position">' + escapeHtml(item.top_position) + '</span>' : '-') +
                    '</td>' +
                    '<td><a href="' + detailUrl + '" class="essb-link-btn">View Details →</a></td>' +
                '</tr>';
    }
    
    // Table state
    var currentPage = 1;
    var rowsPerPage = 25;
    var currentSort = { column: 'clicks', direction: 'desc' };
    var currentSearch = '';
    
    // Function to sort data
    function sortData(data, column, direction) {
        var sorted = [...data];
        sorted.sort(function(a, b) {
            var aVal, bVal;
            
            if (column === 'title') {
                aVal = a.title.toLowerCase();
                bVal = b.title.toLowerCase();
            } else if (column === 'clicks') {
                aVal = a.clicks || 0;
                bVal = b.clicks || 0;
            } else if (column === 'desktop') {
                aVal = a.desktop_clicks || 0;
                bVal = b.desktop_clicks || 0;
            } else if (column === 'mobile') {
                aVal = a.mobile_clicks || 0;
                bVal = b.mobile_clicks || 0;
            } else if (column === 'percent') {
                aVal = a.percent_raw || 0;
                bVal = b.percent_raw || 0;
            } else if (column === 'network') {
                aVal = a.top_network.toLowerCase();
                bVal = b.top_network.toLowerCase();
            } else if (column === 'position') {
                aVal = a.top_position.toLowerCase();
                bVal = b.top_position.toLowerCase();
            } 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.title.toLowerCase().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;
        $('#content-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 = $('#content-table-body');
        $tbody.empty();
        
        for (var i = 0; i < pageData.length; i++) {
            $tbody.append(renderRow(pageData[i]));
        }
        
        // Update info
        $('#content-table-start').text(totalRows > 0 ? start + 1 : 0);
        $('#content-table-end').text(end);
        
        // Update pagination buttons
        var $prevBtn = $('.essb-pagination-btn[data-table="content"][data-page="prev"]');
        var $nextBtn = $('.essb-pagination-btn[data-table="content"][data-page="next"]');
        var $pagesContainer = $('.essb-pagination-pages[data-table="content"]');
        
        $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
    $('#content-table-search').on('keyup', function() {
        currentSearch = $(this).val();
        currentPage = 1;
        renderTable();
    });
    
    // Rows per page handler
    $('#content-table-rows').on('change', function() {
        rowsPerPage = parseInt($(this).val());
        currentPage = 1;
        renderTable();
    });
    
    // Sort handler
    $('#content-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';
        }
        
        $('#content-table th .sort-icon').text('↕');
        sortIcon.text(currentSort.direction === 'asc' ? '↑' : '↓');
        
        currentPage = 1;
        renderTable();
    });
    
    // Pagination handlers
    $(document).on('click', '.essb-pagination-btn[data-table="content"][data-page="prev"]', function() {
        if (currentPage > 1) {
            currentPage--;
            renderTable();
        }
    });
    
    $(document).on('click', '.essb-pagination-btn[data-table="content"][data-page="next"]', function() {
        var totalPages = Math.ceil(filterData(tableData, currentSearch).length / rowsPerPage);
        if (currentPage < totalPages) {
            currentPage++;
            renderTable();
        }
    });
    
    // Initial render
    renderTable();
});
</script>