<?php
/**
 * ESSB Analytics Post Metabox
 * Displays share button analytics for individual posts
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Get the current post ID and date range
$post_id = isset($post_id) ? intval($post_id) : get_the_ID();
$essb_date_from = isset($essb_date_from) ? sanitize_text_field($essb_date_from) : date('Y-m-d', strtotime('-30 days'));
$essb_date_to = isset($essb_date_to) ? sanitize_text_field($essb_date_to) : date('Y-m-d');

// If no post ID, show error
if (!$post_id) {
    echo '<div class="essb-metabox-error">No post selected.</div>';
    return;
}

if (!function_exists('essb_stats_get_network_name')) {
    function essb_stats_get_network_name($network_key = '') {
        $essb_networks = essb_available_social_networks();
        $r = $network_key;

        foreach ($essb_networks as $key => $data) {
            if ($key == 'twitter') {
                $data['name'] = 'X';
            }

            if ($key == $network_key) {
                $r = $data['name'];
            }
        }

        if ($r == 'pinpro') {
            $r = 'Pinterest Pro';
        }

        return $r;
    }
}

// Include necessary functions if not already loaded
if (!function_exists('essb_get_single_post_stats')) {
    function essb_get_single_post_stats($post_id, $date_from, $date_to) {
        global $wpdb;
        $table_name = $wpdb->prefix . ESSB3_TRACKER_TABLE;
        
        if (empty($post_id) || empty($date_from) || empty($date_to)) {
            return array(
                'total_clicks' => 0,
                'desktop_clicks' => 0,
                'mobile_clicks' => 0,
                'networks' => array(),
                'positions' => array(),
                'trend' => array()
            );
        }
        
        $stats = array(
            'total_clicks' => 0,
            'desktop_clicks' => 0,
            'mobile_clicks' => 0,
            'networks' => array(),
            'positions' => array(),
            'trend' => array()
        );
        
        // Get total, desktop, mobile clicks
        $query = $wpdb->prepare(
            "SELECT 
                COUNT(*) as total_clicks,
                SUM(CASE WHEN essb_mobile = 'false' THEN 1 ELSE 0 END) as desktop_clicks,
                SUM(CASE WHEN essb_mobile = 'true' THEN 1 ELSE 0 END) as mobile_clicks
            FROM {$table_name}
            WHERE essb_post_id = %d
            AND DATE(essb_date) BETWEEN %s AND %s
            AND essb_service != 'sidebar-close'",
            $post_id, $date_from, $date_to
        );
        
        $totals = $wpdb->get_row($query);
        if ($totals) {
            $stats['total_clicks'] = intval($totals->total_clicks);
            $stats['desktop_clicks'] = intval($totals->desktop_clicks);
            $stats['mobile_clicks'] = intval($totals->mobile_clicks);
        }
        
        // Get network breakdown
        $network_query = $wpdb->prepare(
            "SELECT 
                essb_service as network,
                COUNT(*) as clicks,
                SUM(CASE WHEN essb_mobile = 'false' THEN 1 ELSE 0 END) as desktop_clicks,
                SUM(CASE WHEN essb_mobile = 'true' THEN 1 ELSE 0 END) as mobile_clicks
            FROM {$table_name}
            WHERE essb_post_id = %d
            AND DATE(essb_date) BETWEEN %s AND %s
            AND essb_service != 'sidebar-close'
            GROUP BY essb_service
            ORDER BY clicks DESC",
            $post_id, $date_from, $date_to
        );
        
        $network_results = $wpdb->get_results($network_query);
        if (!empty($network_results) && is_array($network_results)) {
            foreach ($network_results as $row) {
                $stats['networks'][$row->network] = array(
                    'clicks' => intval($row->clicks),
                    'desktop' => intval($row->desktop_clicks),
                    'mobile' => intval($row->mobile_clicks)
                );
            }
        }
        
        // Get position breakdown
        $position_query = $wpdb->prepare(
            "SELECT 
                essb_position as position,
                COUNT(*) as clicks,
                SUM(CASE WHEN essb_mobile = 'false' THEN 1 ELSE 0 END) as desktop_clicks,
                SUM(CASE WHEN essb_mobile = 'true' THEN 1 ELSE 0 END) as mobile_clicks
            FROM {$table_name}
            WHERE essb_post_id = %d
            AND DATE(essb_date) BETWEEN %s AND %s
            AND essb_service != 'sidebar-close'
            GROUP BY essb_position
            ORDER BY clicks DESC",
            $post_id, $date_from, $date_to
        );
        
        $position_results = $wpdb->get_results($position_query);
        if (!empty($position_results) && is_array($position_results)) {
            foreach ($position_results as $row) {
                $stats['positions'][$row->position] = array(
                    'clicks' => intval($row->clicks),
                    'desktop' => intval($row->desktop_clicks),
                    'mobile' => intval($row->mobile_clicks)
                );
            }
        }
        
        return $stats;
    }
}

if (!function_exists('essb_format_number')) {
    function essb_format_number($number) {
        if (!is_numeric($number)) {
            return $number;
        }
        if ($number >= 1000000) {
            return round(($number / 1000) / 1000, 1) . "M";
        } elseif ($number >= 100000) {
            return round($number / 1000, 0) . "k";
        } else {
            return number_format($number);
        }
    }
}

if (!function_exists('essb_get_position_name')) {
    function essb_get_position_name($position) {
        $r = $position;
        
        $all_positions = essb5_available_content_positions();
        foreach ($all_positions as $key => $data) {
            $key = str_replace("content_", "", $key);
            if ($key == 'manual') {
                $key = 'shortcode';
            }
            if ($key == $position) {
                $r = $data['label'];
            }
        }
        
        $all_positions = essb5_available_button_positions();
        foreach ($all_positions as $key => $data) {
            if ($key == $position) {
                $r = $data['label'];
            }
        }
        
        if ($position == 'pinit') {
            $r = esc_html__('Pinable Image', 'essb');
        }
        
        return $r;
    }
}

// Get the stats
$stats = essb_get_single_post_stats($post_id, $essb_date_from, $essb_date_to);
$total_clicks = $stats['total_clicks'];
$desktop_clicks = $stats['desktop_clicks'];
$mobile_clicks = $stats['mobile_clicks'];

// Calculate best network
$best_network = 'None';
$best_network_clicks = 0;
if (!empty($stats['networks']) && is_array($stats['networks'])) {
    foreach ($stats['networks'] as $network => $data) {
        if ($data['clicks'] > $best_network_clicks) {
            $best_network_clicks = $data['clicks'];
            $best_network = $network;
        }
    }
}

// Calculate best position
$best_position = 'None';
$best_position_clicks = 0;
if (!empty($stats['positions']) && is_array($stats['positions'])) {
    foreach ($stats['positions'] as $position => $data) {
        if ($data['clicks'] > $best_position_clicks) {
            $best_position_clicks = $data['clicks'];
            $best_position = $position;
        }
    }
}

// Calculate best device
$best_device = $desktop_clicks > $mobile_clicks ? 'Desktop' : 'Mobile';
$best_device_clicks = max($desktop_clicks, $mobile_clicks);

// Prepare network table data
$network_data = array();
foreach ($stats['networks'] as $network => $data) {
    $percentage = $total_clicks > 0 ? ($data['clicks'] / $total_clicks) * 100 : 0;
    $network_data[] = array(
        'name' => $network,
        'display_name' => essb_stats_get_network_name($network),
        'clicks' => $data['clicks'],
        'desktop_clicks' => $data['desktop'],
        'mobile_clicks' => $data['mobile'],
        'percentage' => $percentage
    );
}
usort($network_data, function($a, $b) {
    return $b['clicks'] - $a['clicks'];
});

// Prepare position table data
$position_data = array();
foreach ($stats['positions'] as $position => $data) {
    $percentage = $total_clicks > 0 ? ($data['clicks'] / $total_clicks) * 100 : 0;
    $position_data[] = array(
        'name' => $position,
        'display_name' => essb_get_position_name($position),
        'clicks' => $data['clicks'],
        'desktop_clicks' => $data['desktop'],
        'mobile_clicks' => $data['mobile'],
        'percentage' => $percentage
    );
}
usort($position_data, function($a, $b) {
    return $b['clicks'] - $a['clicks'];
});

// Build the detail report URL
$detail_report_url = admin_url('admin.php?page=essb_redirect_analytics&tab=analytics&view=detail&period=30days&detail_type=content&detail_item=' . $post_id);
?>

<style>
    /* ESSB Analytics Post Metabox Styles */
    .essb-metabox-wrap {
        padding: 0;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        color: #1e293b;
    }
    
    /* Header with button */
    .essb-metabox-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        flex-wrap: wrap;
        gap: 12px;
    }
    
    .essb-metabox-header-title {
        font-size: 14px;
        font-weight: 600;
        color: #1e293b;
    }
    
    .essb-metabox-link-btn {
        color: #3b82f6;
        text-decoration: none;
        font-size: 12px;
        font-weight: 500;
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 6px 12px;
        background: #eff6ff;
        border-radius: 6px;
        transition: all 0.2s ease;
    }
    
    .essb-metabox-link-btn:hover {
        background: #dbeafe;
        color: #2563eb;
        text-decoration: none;
    }
    
    /* KPI Grid */
    .essb-metabox-kpi-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 16px;
        margin-bottom: 24px;
    }
    
    .essb-metabox-kpi-card {
        background: #ffffff;
        border-radius: 8px;
        padding: 16px;
        border: 1px solid #e2e8f0;
        box-shadow: 0 1px 2px rgba(0,0,0,0.05);
    }
    
    .essb-metabox-kpi-title {
        font-size: 11px;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #64748b;
        margin-bottom: 8px;
    }
    
    .essb-metabox-kpi-value {
        font-size: 28px;
        font-weight: 600;
        color: #1e293b;
        margin-bottom: 4px;
    }
    
    .essb-metabox-kpi-sub {
        font-size: 11px;
        color: #64748b;
        margin-top: 8px;
        padding-top: 8px;
        border-top: 1px solid #e2e8f0;
    }
    
    /* Chips */
    .essb-metabox-chip-wrapper {
        margin: 12px 0 8px 0;
    }
    
    .essb-metabox-chip {
        display: inline-block;
        padding: 4px 10px;
        background: #f1f5f9;
        border: 1px solid #e2e8f0;
        border-radius: 20px;
        font-size: 13px;
        font-weight: 500;
        color: #1e293b;
    }
    
    .essb-metabox-chip-network {
        background: #eef2ff;
        border-color: #c7d2fe;
        color: #1e40af;
    }
    
    .essb-metabox-chip-position {
        background: #fef3c7;
        border-color: #fde68a;
        color: #92400e;
    }
    
    .essb-metabox-chip-device {
        background: #d1fae5;
        border-color: #a7f3d0;
        color: #065f46;
    }
    
    .essb-metabox-chip-small {
        padding: 2px 8px;
        font-size: 11px;
    }
    
    .essb-metabox-value-wrapper {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 8px;
    }
    
    .essb-metabox-kpi-value-small {
        font-size: 20px;
        font-weight: 600;
        color: #1e293b;
    }
    
    .essb-metabox-kpi-label-small {
        font-size: 10px;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #64748b;
    }
    
    .essb-metabox-progress-bar {
        background: #e2e8f0;
        border-radius: 4px;
        overflow: hidden;
        height: 4px;
        margin-top: 8px;
    }
    
    .essb-metabox-progress-fill {
        background: #3b82f6;
        height: 100%;
        transition: width 0.3s ease;
    }
    
    .essb-metabox-percent {
        font-size: 11px;
        color: #64748b;
        text-align: right;
        margin-top: 4px;
    }
    
    /* Tables */
    .essb-metabox-table-wrapper {
        overflow-x: auto;
        margin-top: 16px;
    }
    
    .essb-metabox-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 12px;
    }
    
    .essb-metabox-table thead th {
        background: #f8fafc;
        padding: 10px 12px;
        text-align: left;
        font-weight: 600;
        font-size: 11px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #64748b;
        border-bottom: 1px solid #e2e8f0;
    }
    
    .essb-metabox-table tbody td {
        padding: 10px 12px;
        border-bottom: 1px solid #e2e8f0;
        vertical-align: middle;
    }
    
    .essb-metabox-table tbody tr:hover {
        background: #f8fafc;
    }
    
    .essb-metabox-table-number {
        text-align: right;
        font-family: monospace;
        font-size: 12px;
    }
    
    /* Section Headers */
    .essb-metabox-section {
        margin-top: 24px;
    }
    
    .essb-metabox-section-title {
        font-size: 14px;
        font-weight: 600;
        color: #1e293b;
        margin-bottom: 12px;
        padding-bottom: 8px;
        border-bottom: 1px solid #e2e8f0;
    }
    
    /* Empty State */
    .essb-metabox-empty {
        text-align: center;
        padding: 40px 20px;
        color: #64748b;
        background: #f8fafc;
        border-radius: 8px;
        border: 1px solid #e2e8f0;
    }
    
    /* Date Range Info */
    .essb-metabox-date-range {
        font-size: 12px;
        color: #64748b;
        margin-bottom: 16px;
        padding: 8px 12px;
        background: #f8fafc;
        border-radius: 6px;
        border: 1px solid #e2e8f0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 12px;
    }
    
    /* Responsive */
    @media (max-width: 782px) {
        .essb-metabox-kpi-grid {
            grid-template-columns: repeat(2, 1fr);
        }
        
        .essb-metabox-date-range {
            flex-direction: column;
            align-items: flex-start;
        }
    }
</style>

<div class="essb-metabox-wrap">
    <!-- Date Range Info with View Full Report Button -->
    <div class="essb-metabox-date-range">
        <span>📊 Data from <strong><?php echo date('M j, Y', strtotime($essb_date_from)); ?></strong> to <strong><?php echo date('M j, Y', strtotime($essb_date_to)); ?></strong></span>
        <a href="<?php echo esc_url($detail_report_url); ?>" target="_blank" class="essb-metabox-link-btn">
            View Full Report →
        </a>
    </div>
    
    <!-- KPI Grid -->
    <div class="essb-metabox-kpi-grid">
        <!-- Total Clicks Card -->
        <div class="essb-metabox-kpi-card">
            <div class="essb-metabox-kpi-title">Total Clicks</div>
            <div class="essb-metabox-kpi-value"><?php echo essb_format_number($total_clicks); ?></div>
            <div class="essb-metabox-kpi-sub">
                Desktop: <?php echo essb_format_number($desktop_clicks); ?> | Mobile: <?php echo essb_format_number($mobile_clicks); ?>
            </div>
        </div>
        
        <!-- Best Network Card -->
        <div class="essb-metabox-kpi-card">
            <div class="essb-metabox-kpi-title">Best Network</div>
            <div class="essb-metabox-chip-wrapper">
                <div class="essb-metabox-chip essb-metabox-chip-network"><?php echo essb_stats_get_network_name($best_network); ?></div>
            </div>
            <div class="essb-metabox-value-wrapper">
                <div class="essb-metabox-kpi-value-small"><?php echo essb_format_number($best_network_clicks); ?></div>
                <div class="essb-metabox-kpi-label-small">clicks</div>
            </div>
            <?php if ($total_clicks > 0 && $best_network_clicks > 0): ?>
            <div class="essb-metabox-progress-bar">
                <div class="essb-metabox-progress-fill" style="width: <?php echo ($best_network_clicks / $total_clicks) * 100; ?>%"></div>
            </div>
            <div class="essb-metabox-percent"><?php echo round(($best_network_clicks / $total_clicks) * 100, 1); ?>% of total</div>
            <?php endif; ?>
        </div>
        
        <!-- Best Position Card -->
        <div class="essb-metabox-kpi-card">
            <div class="essb-metabox-kpi-title">Best Position</div>
            <div class="essb-metabox-chip-wrapper">
                <div class="essb-metabox-chip essb-metabox-chip-position"><?php echo essb_get_position_name($best_position); ?></div>
            </div>
            <div class="essb-metabox-value-wrapper">
                <div class="essb-metabox-kpi-value-small"><?php echo essb_format_number($best_position_clicks); ?></div>
                <div class="essb-metabox-kpi-label-small">clicks</div>
            </div>
        </div>
        
        <!-- Best Device Card -->
        <div class="essb-metabox-kpi-card">
            <div class="essb-metabox-kpi-title">Best Device</div>
            <div class="essb-metabox-chip-wrapper">
                <div class="essb-metabox-chip essb-metabox-chip-device"><?php echo $best_device; ?></div>
            </div>
            <div class="essb-metabox-value-wrapper">
                <div class="essb-metabox-kpi-value-small"><?php echo essb_format_number($best_device_clicks); ?></div>
                <div class="essb-metabox-kpi-label-small">clicks</div>
            </div>
            <div class="essb-metabox-kpi-sub" style="margin-top: 8px;">
                Desktop: <?php echo $total_clicks > 0 ? round(($desktop_clicks / $total_clicks) * 100, 1) : 0; ?>% | 
                Mobile: <?php echo $total_clicks > 0 ? round(($mobile_clicks / $total_clicks) * 100, 1) : 0; ?>%
            </div>
        </div>
    </div>
    
    <!-- Networks Table -->
    <div class="essb-metabox-section">
        <div class="essb-metabox-section-title">Performance by Network</div>
        
        <?php if (empty($network_data)): ?>
            <div class="essb-metabox-empty">No network data available for this period</div>
        <?php else: ?>
            <div class="essb-metabox-table-wrapper">
                <table class="essb-metabox-table">
                    <thead>
                        <tr>
                            <th>Network</th>
                            <th class="essb-metabox-table-number">Clicks</th>
                            <th class="essb-metabox-table-number">Desktop</th>
                            <th class="essb-metabox-table-number">Mobile</th>
                            <th class="essb-metabox-table-number">% of Total</th>
                        </thead>
                    <tbody>
                        <?php foreach($network_data as $network): ?>
                        <tr>
                            <td><span class="essb-metabox-chip essb-metabox-chip-small essb-metabox-chip-network"><?php echo esc_html($network['display_name']); ?></span></td>
                            <td class="essb-metabox-table-number"><strong><?php echo essb_format_number($network['clicks']); ?></strong></td>
                            <td class="essb-metabox-table-number"><?php echo essb_format_number($network['desktop_clicks']); ?></td>
                            <td class="essb-metabox-table-number"><?php echo essb_format_number($network['mobile_clicks']); ?></td>
                            <td class="essb-metabox-table-number">
                                <?php echo round($network['percentage'], 1); ?>%
                                <div class="essb-metabox-progress-bar">
                                    <div class="essb-metabox-progress-fill" style="width: <?php echo $network['percentage']; ?>%"></div>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- Positions Table -->
    <div class="essb-metabox-section">
        <div class="essb-metabox-section-title">Performance by Position</div>
        
        <?php if (empty($position_data)): ?>
            <div class="essb-metabox-empty">No position data available for this period</div>
        <?php else: ?>
            <div class="essb-metabox-table-wrapper">
                <table class="essb-metabox-table">
                    <thead>
                        <tr>
                            <th>Position</th>
                            <th class="essb-metabox-table-number">Clicks</th>
                            <th class="essb-metabox-table-number">Desktop</th>
                            <th class="essb-metabox-table-number">Mobile</th>
                            <th class="essb-metabox-table-number">% of Total</th>
                        </thead>
                    <tbody>
                        <?php foreach($position_data as $position): ?>
                        <tr>
                            <td><span class="essb-metabox-chip essb-metabox-chip-small essb-metabox-chip-position"><?php echo esc_html($position['display_name']); ?></span></td>
                            <td class="essb-metabox-table-number"><strong><?php echo essb_format_number($position['clicks']); ?></strong></td>
                            <td class="essb-metabox-table-number"><?php echo essb_format_number($position['desktop_clicks']); ?></td>
                            <td class="essb-metabox-table-number"><?php echo essb_format_number($position['mobile_clicks']); ?></td>
                            <td class="essb-metabox-table-number">
                                <?php echo round($position['percentage'], 1); ?>%
                                <div class="essb-metabox-progress-bar">
                                    <div class="essb-metabox-progress-fill" style="width: <?php echo $position['percentage']; ?>%"></div>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>