<?php
// Networks View
$total_clicks = $stats->total_clicks;
$networks_data = array();

foreach($stats->networks as $network => $clicks) {
    $percentage = ($total_clicks > 0) ? ($clicks / $total_clicks) * 100 : 0;
    $networks_data[] = (object)array(
        'name' => ($network),
        'clicks' => $clicks,
        'percentage' => $percentage,
        'desktop_clicks' => round($clicks * ($stats->desktop_clicks / max(1, $total_clicks))),
        'mobile_clicks' => round($clicks * ($stats->mobile_clicks / max(1, $total_clicks)))
    );
}

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

// Get top networks by device
$desktop_networks = array_filter($networks_data, function($n) {
    return $n->desktop_clicks > 0;
});
usort($desktop_networks, function($a, $b) {
    return $b->desktop_clicks - $a->desktop_clicks;
});

$mobile_networks = array_filter($networks_data, function($n) {
    return $n->mobile_clicks > 0;
});
usort($mobile_networks, function($a, $b) {
    return $b->mobile_clicks - $a->mobile_clicks;
});

$top_all = !empty($networks_data) ? $networks_data[0] : null;
$top_desktop = !empty($desktop_networks) ? $desktop_networks[0] : null;
$top_mobile = !empty($mobile_networks) ? $mobile_networks[0] : null;

// Prepare table data as JavaScript array
$table_data = array();
foreach($networks_data as $network) {
    $best_position = essb_get_best_position_for_network($network->name, $date_from, $date_to);
    $best_content = essb_get_best_content_for_network($network->name, $date_from, $date_to);
    
    $table_data[] = array(
        'name' => strtolower($network->name),
        'display_name' => essb_stats_get_network_name($network->name),
        'clicks' => $network->clicks,
        'desktop_clicks' => $network->desktop_clicks,
        'mobile_clicks' => $network->mobile_clicks,
        'percent' => round($network->percentage, 1),
        'percent_raw' => $network->percentage,
        'best_position' => $best_position ? ESSBSocialShareAnalyticsBackEnd::position_name($best_position) : '-',
        'best_content' => ($best_content && isset($best_content->essb_post_id)) ? array(
            'id' => $best_content->essb_post_id,
            'title' => substr(get_the_title($best_content->essb_post_id), 0, 40),
            'url' => get_permalink($best_content->essb_post_id)
        ) : null,
        'detail_url' => essb_get_tab_url('detail', $period, $date_from, $date_to) . '&detail_type=network&detail_item=' . urlencode($network->name)
    );
}
?>

<!-- Top Networks Panel -->
<div class="essb-kpi-grid">
    <!-- All Networks -->
    <div class="essb-kpi-card">
        <div class="essb-kpi-title">Top Network (All)</div>
        <div class="essb-chip-wrapper">
            <div class="essb-chip essb-chip-network"><?php echo $top_all ? essb_stats_get_network_name($top_all->name) : '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 Networks -->
    <div class="essb-kpi-card">
        <div class="essb-kpi-title">Top Network (Desktop)</div>
        <div class="essb-chip-wrapper">
            <div class="essb-chip essb-chip-network"><?php echo $top_desktop ? essb_stats_get_network_name($top_desktop->name) : 'No Data'; ?></div>
            <div class="essb-value-wrapper">
                <div class="essb-kpi-value-small"><?php echo $top_desktop ? ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($top_desktop->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->desktop_clicks / $stats->desktop_clicks) * 100; ?>%"></div>
        </div>
        <div class="essb-kpi-percent"><?php echo round(($top_desktop->desktop_clicks / $stats->desktop_clicks) * 100, 1); ?>% of desktop clicks</div>
        <?php endif; ?>
    </div>
    
    <!-- Mobile Networks -->
    <div class="essb-kpi-card">
        <div class="essb-kpi-title">Top Network (Mobile)</div>
        <div class="essb-chip-wrapper">
            <div class="essb-chip essb-chip-network"><?php echo $top_mobile ? essb_stats_get_network_name($top_mobile->name) : 'No Data'; ?></div>
            <div class="essb-value-wrapper">
                <div class="essb-kpi-value-small"><?php echo $top_mobile ? ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($top_mobile->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->mobile_clicks / $stats->mobile_clicks) * 100; ?>%"></div>
        </div>
        <div class="essb-kpi-percent"><?php echo round(($top_mobile->mobile_clicks / $stats->mobile_clicks) * 100, 1); ?>% of mobile clicks</div>
        <?php endif; ?>
    </div>
</div>

<!-- Networks Table -->
<div class="essb-chart-container">
    <div class="essb-chart-title">
        Detailed Network Report
        <div class="essb-table-controls">
            <input type="text" id="network-table-search" class="essb-table-search" placeholder="Search networks...">
            <select id="network-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="networks-table">
            <thead>
                <tr>
                    <th data-sort="name" class="sortable">Network <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 Clicks <span class="sort-icon">↕</span></th>
                    <th data-sort="mobile" class="sortable">Mobile Clicks <span class="sort-icon">↕</span></th>
                    <th data-sort="percent" class="sortable">% of Total <span class="sort-icon">↕</span></th>
                    <th>Best Position</th>
                    <th>Best Content</th>
                    <th>Actions</th>
                </thead>
            <tbody id="networks-table-body">
                <!-- Table body will be populated by JavaScript -->
            </tbody>
        </table>
        <div class="essb-table-footer">
            <div class="essb-table-info">Showing <span id="network-table-start">0</span> to <span id="network-table-end">0</span> of <span id="network-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-network">' +
                '<span class="essb-chip essb-chip-small essb-chip-network">' + escapeHtml(item.display_name) + '</span>' +
            '</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: ' + percentValue + '%;"></div>' +
                '</div>' +
            '</td>' +
            '<td>' + escapeHtml(item.best_position) + '</td>' +
            '<td class="essb-table-post">' +
                (item.best_content ? '<a href="' + escapeHtml(item.best_content.url) + '" target="_blank">' + escapeHtml(item.best_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 === '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 !== 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;
        $('#network-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 = $('#networks-table-body');
        $tbody.empty();
        
        for (var i = 0; i < pageData.length; i++) {
            $tbody.append(renderRow(pageData[i]));
        }
        
        // Update info
        $('#network-table-start').text(totalRows > 0 ? start + 1 : 0);
        $('#network-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
    $('#network-table-search').on('keyup', function() {
        currentSearch = $(this).val();
        currentPage = 1;
        renderTable();
    });
    
    // Rows per page handler
    $('#network-table-rows').on('change', function() {
        rowsPerPage = parseInt($(this).val());
        currentPage = 1;
        renderTable();
    });
    
    // Sort handler
    $('#networks-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';
        }
        
        $('#networks-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>