<?php
// Heatmap View - Network vs Position Matrix
$device_filter = isset($_GET['device_filter']) ? sanitize_text_field($_GET['device_filter']) : 'all';

// Get heatmap data
$heatmap_data = essb_get_heatmap_matrix_data($date_from, $date_to, $device_filter);
$networks = $heatmap_data['networks'];
$positions = $heatmap_data['positions'];
$matrix = $heatmap_data['matrix'];
$max_clicks = $heatmap_data['max_clicks'];

// Calculate totals for each network and position
$network_totals = array();
foreach($networks as $network) {
    $network_totals[$network] = array_sum(array_column($matrix[$network] ?? array(), 'clicks'));
}

$position_totals = array();
foreach($positions as $position) {
    $total = 0;
    foreach($networks as $network) {
        $total += $matrix[$network][$position]['clicks'] ?? 0;
    }
    $position_totals[$position] = $total;
}

// Sort networks by total clicks (descending)
usort($networks, function($a, $b) use ($network_totals) {
    return $network_totals[$b] - $network_totals[$a];
});

// Sort positions by total clicks (descending)
usort($positions, function($a, $b) use ($position_totals) {
    return $position_totals[$b] - $position_totals[$a];
});
?>

<!-- Heatmap Filter -->
<div class="essb-filter-bar">
    <span>Device Filter:</span>
    <form method="GET" action="" style="display: inline-flex; gap: 10px;">
        <input type="hidden" name="page" value="essb_redirect_analytics">
        <input type="hidden" name="tab" value="analytics">
        <input type="hidden" name="view" value="heatmap">
        <input type="hidden" name="period" value="<?php echo esc_attr($period); ?>">
        <?php if($period == 'custom'): ?>
            <input type="hidden" name="date_from" value="<?php echo esc_attr($date_from); ?>">
            <input type="hidden" name="date_to" value="<?php echo esc_attr($date_to); ?>">
        <?php endif; ?>
        
        <select name="device_filter" class="essb-filter-select" onchange="this.form.submit()">
            <option value="all" <?php echo $device_filter == 'all' ? 'selected' : ''; ?>>All Devices</option>
            <option value="desktop" <?php echo $device_filter == 'desktop' ? 'selected' : ''; ?>>Desktop Only</option>
            <option value="mobile" <?php echo $device_filter == 'mobile' ? 'selected' : ''; ?>>Mobile Only</option>
        </select>
    </form>
</div>

<!-- Heatmap Title -->
<div class="essb-chart-container">
    <div class="essb-chart-title">
        Network vs Position Heatmap
<div class="essb-heatmap-legend">
    <span class="essb-legend-label">Click Intensity:</span>
    <div class="essb-legend-colors">
        <div class="essb-legend-color" style="background: #eff6ff;"></div>
        <div class="essb-legend-color" style="background: #bfdbfe;"></div>
        <div class="essb-legend-color" style="background: #93c5fd;"></div>
        <div class="essb-legend-color" style="background: #60a5fa;"></div>
        <div class="essb-legend-color" style="background: #3b82f6;"></div>
        <div class="essb-legend-color" style="background: #2563eb;"></div>
        <div class="essb-legend-color" style="background: #1e3a8a;"></div>
    </div>
    <span class="essb-legend-text">Low → High</span>
</div>
    </div>
    
    <?php if (empty($networks) || empty($positions)): ?>
        <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="M4 4h16v16H4z"/>
                <line x1="8" y1="8" x2="16" y2="16"/>
                <line x1="16" y1="8" x2="8" y2="16"/>
            </svg>
            <p>No heatmap data available for this period</p>
            <p class="essb-empty-state-sub">Try selecting a different date range or device filter.</p>
        </div>
    <?php else: ?>
        <div class="essb-heatmap-table-wrapper">
            <table class="essb-heatmap-table">
                <thead>
                    <tr>
                        <th class="essb-heatmap-corner">Network \ Position</th>
                        <?php foreach($positions as $position): ?>
                        <th class="essb-heatmap-header">
                            <div class="essb-heatmap-header-content">
                                <?php echo esc_html(ESSBSocialShareAnalyticsBackEnd::position_name($position)); ?>
                                <div class="essb-heatmap-total"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($position_totals[$position]); ?></div>
                            </div>
                        </th>
                        <?php endforeach; ?>
                        <th class="essb-heatmap-total-col">Total</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($networks as $network): 
                        $network_total = $network_totals[$network];
                    ?>
                    <tr>
                        <th class="essb-heatmap-row-header">
                            <div class="essb-heatmap-header-content">
                                <span class="essb-chip essb-chip-small essb-chip-network"><?php echo essb_stats_get_network_name($network); ?></span>
                                <div class="essb-heatmap-total"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($network_total); ?></div>
                            </div>
                        </th>
                        <?php foreach($positions as $position): 
                            $cell = $matrix[$network][$position] ?? array('clicks' => 0, 'percentage' => 0);
                            $clicks = $cell['clicks'];
                            $percentage = $cell['percentage'];
                            $intensity = $max_clicks > 0 ? ($clicks / $max_clicks) * 100 : 0;
                            $bg_color = essb_get_heatmap_color($intensity);
                        ?>
<td class="essb-heatmap-cell" style="background-color: <?php echo $bg_color; ?>;" 
    data-clicks="<?php echo $clicks; ?>" 
    data-percent="<?php echo round($percentage, 1); ?>"
    data-bg-color="<?php echo $bg_color; ?>">
    <div class="essb-heatmap-cell-content">
        <div class="essb-heatmap-clicks"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($clicks); ?></div>
        <?php if ($network_total > 0): ?>
        <div class="essb-heatmap-percent"><?php echo round($percentage, 1); ?>%</div>
        <?php endif; ?>
    </div>
</td>
                        <?php endforeach; ?>
                        <td class="essb-heatmap-row-total">
                            <div class="essb-heatmap-cell-content">
                                <div class="essb-heatmap-clicks"><?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($network_total); ?></div>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <th class="essb-heatmap-footer-corner">Total</th>
                        <?php foreach($positions as $position): ?>
                        <th class="essb-heatmap-footer">
                            <?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($position_totals[$position]); ?>
                        </th>
                        <?php endforeach; ?>
                        <th class="essb-heatmap-footer-total">
                            <?php 
                            $grand_total = array_sum($network_totals);
                            echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($grand_total);
                            ?>
                        </th>
                    </tr>
                </tfoot>
            </table>
        </div>
        
        <div class="essb-heatmap-stats">
            <div class="essb-heatmap-stat">
                <span class="essb-heatmap-stat-label">Hottest Cell:</span>
                <?php 
                $hottest = array('clicks' => 0, 'network' => '', 'position' => '');
                foreach($networks as $network) {
                    foreach($positions as $position) {
                        $clicks = $matrix[$network][$position]['clicks'] ?? 0;
                        if ($clicks > $hottest['clicks']) {
                            $hottest = array(
                                'clicks' => $clicks,
                                'network' => $network,
                                'position' => $position,
                                'percentage' => $matrix[$network][$position]['percentage'] ?? 0
                            );
                        }
                    }
                }
                ?>
                <?php if ($hottest['clicks'] > 0): ?>
                <span class="essb-heatmap-stat-value">
                    <?php echo essb_stats_get_network_name($hottest['network']); ?> @ <?php echo ESSBSocialShareAnalyticsBackEnd::position_name($hottest['position']); ?>
                    (<?php echo ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($hottest['clicks']); ?> clicks, <?php echo round($hottest['percentage'], 1); ?>% of network)
                </span>
                <?php else: ?>
                <span class="essb-heatmap-stat-value">No data available</span>
                <?php endif; ?>
            </div>
            <div class="essb-heatmap-stat">
                <span class="essb-heatmap-stat-label">Most Active Network:</span>
                <span class="essb-heatmap-stat-value">
                    <?php 
                    if (!empty($networks)) {
                        $top_network = $networks[0];
                        echo essb_stats_get_network_name($top_network) . ' (' . ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($network_totals[$top_network]) . ' clicks)';
                    } else {
                        echo 'No data';
                    }
                    ?>
                </span>
            </div>
            <div class="essb-heatmap-stat">
                <span class="essb-heatmap-stat-label">Most Active Position:</span>
                <span class="essb-heatmap-stat-value">
                    <?php 
                    if (!empty($positions)) {
                        $top_position = $positions[0];
                        echo ESSBSocialShareAnalyticsBackEnd::position_name($top_position) . ' (' . ESSBSocialShareAnalyticsBackEnd::prettyPrintNumber($position_totals[$top_position]) . ' clicks)';
                    } else {
                        echo 'No data';
                    }
                    ?>
                </span>
            </div>
        </div>
    <?php endif; ?>
</div>

<script type="text/javascript">
jQuery(document).ready(function($) {
    // Add tooltip functionality for heatmap cells
    $('.essb-heatmap-cell').hover(
        function() {
            var clicks = $(this).data('clicks');
            var percent = $(this).data('percent');
            if (clicks > 0) {
                $(this).attr('title', clicks + ' clicks (' + percent + '% of network)');
            }
        }
    );
    
    // Function to determine if text should be white or dark based on background color
    function setTextColor(cell) {
        var bgColor = cell.data('bg-color');
        if (!bgColor) return;
        
        // Parse the background color
        var rgb;
        if (bgColor.startsWith('#')) {
            var hex = bgColor.substring(1);
            var r = parseInt(hex.substring(0, 2), 16);
            var g = parseInt(hex.substring(2, 4), 16);
            var b = parseInt(hex.substring(4, 6), 16);
            rgb = {r: r, g: g, b: b};
        } else if (bgColor.startsWith('rgb')) {
            var matches = bgColor.match(/\d+/g);
            if (matches && matches.length >= 3) {
                rgb = {r: parseInt(matches[0]), g: parseInt(matches[1]), b: parseInt(matches[2])};
            }
        }
        
        if (rgb) {
            // Calculate luminance (perceived brightness)
            var luminance = (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255;
            
            // If background is dark, use white text; if light, use dark text
            var textColor = luminance < 0.5 ? '#ffffff' : '#1e293b';
            var percentColor = luminance < 0.5 ? '#e2e8f0' : '#64748b';
            
            cell.find('.essb-heatmap-clicks').css('color', textColor);
            cell.find('.essb-heatmap-percent').css('color', percentColor);
        }
    }
    
    // Apply text color to all heatmap cells
    $('.essb-heatmap-cell').each(function() {
        setTextColor($(this));
    });
});
</script>