<?php
/**
 * Agentic Square / Enfhess Marketplace - High Performance Analytical Matrix Dashboard Charts
 * Path: seller/report-chart.php
 */

if (!isset($timelineDataPoints)) {
    die('Chart timeline matrix context structure parameters missing.');
}

// Ensure session state fallback variables exist if missing from global scope
if (!isset($user_id)) {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    $user_id = (int)($_SESSION['user_id'] ?? 0);
}

// Sort arrays sequentially by timestamp order tracking keys
ksort($timelineDataPoints);

$jsLabels     = [];
$jsUnitsCount = [];
$jsNetProfits = [];

$aggregateTotalViews = 0;
$aggregateTotalSold  = 0;

// 1. Extract structural timeline sequences for trends graph mapping
foreach ($timelineDataPoints as $dateKey => $values) {
    $jsLabels[]     = date('M d', strtotime($dateKey));
    $jsUnitsCount[] = (int)$values['units'];
    $jsNetProfits[] = (float)$values['income'];
    
    // Increment total units sold from dynamic timeline data matrix
    $aggregateTotalSold  += (int)$values['units'];
}

// 2. STABLE FALLBACK PIPELINE: Fetch true views calculation directly from the items table matching your seller profile
if (isset($pdo) && $user_id > 0) {
    try {
        // Find the matching seller entry first to maintain data isolation integrity
        $stmtSeller = $pdo->prepare("SELECT id FROM sellers WHERE user_id = ? LIMIT 1");
        $stmtSeller->execute([$user_id]);
        $currentSeller = $stmtSeller->fetch(PDO::FETCH_ASSOC);

        if ($currentSeller) {
            $seller_id = (int)$currentSeller['id'];
            
            // Calculate total views from items matching both security validation parameters
            $fallbackViewsStmt = $pdo->prepare("SELECT SUM(views) as true_total FROM items WHERE user_id = ? AND seller_id = ?");
            $fallbackViewsStmt->execute([$user_id, $seller_id]);
            $fallbackResult = $fallbackViewsStmt->fetch(PDO::FETCH_ASSOC);
            
            $aggregateTotalViews = (int)($fallbackResult['true_total'] ?? 0);
        }
    } catch (PDOException $e) {
        // Graceful error isolation fallback logic pipeline
        $aggregateTotalViews = 0;
    }
}

// Set up fallbacks if no transactions occurred during this period
if (empty($jsLabels)) {
    $jsLabels     = ['No Transacting Logs Available'];
    $jsUnitsCount = [0];
    $jsNetProfits = [0.00];
}

// Calculate percentages dynamically preventing division by zero constraints
$overallTouchpoints = $aggregateTotalViews + $aggregateTotalSold;
$viewsPercentage    = $overallTouchpoints > 0 ? round(($aggregateTotalViews / $overallTouchpoints) * 100, 1) : 0;
$soldPercentage     = $overallTouchpoints > 0 ? round(($aggregateTotalSold / $overallTouchpoints) * 100, 1) : 0;
?>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    
    <div class="lg:col-span-2 glass-card p-6 rounded-2xl border border-slate-800/80 bg-gradient-to-b from-slate-950/40 to-slate-950/80 shadow-2xl flex flex-col justify-between">
        <div>
            <div class="flex items-center justify-between border-b border-slate-900/60 pb-4 mb-6 flex-wrap gap-4">
                <div>
                    <h3 class="text-sm font-bold uppercase text-nftAccentCyan tracking-wider">// High-Retention Performance Trends Map</h3>
                    <p class="text-[11px] text-slate-500 mt-0.5">Visual representation of daily checkouts and marketplace net yield values.</p>
                </div>
                
                <div class="flex items-center space-x-4 text-[10px] uppercase font-bold tracking-wider">
                    <div class="flex items-center space-x-1.5">
                        <span class="w-2.5 h-2.5 bg-nftAccentCyan rounded-sm block"></span>
                        <span class="text-slate-400">Net Income Proceeds ($)</span>
                    </div>
                    <div class="flex items-center space-x-1.5">
                        <span class="w-2.5 h-2.5 bg-nftAccentPurple rounded-sm block"></span>
                        <span class="text-slate-400">Volume Sales Count (Units)</span>
                    </div>
                </div>
            </div>

            <div class="relative w-full h-80">
                <canvas id="enfhessAnalyticsEngineCanvas"></canvas>
            </div>
        </div>
    </div>

    <div class="lg:col-span-1 glass-card p-6 rounded-2xl border border-slate-800/80 bg-gradient-to-b from-slate-950/40 to-slate-950/80 shadow-2xl flex flex-col justify-between">
        <div>
            <div class="border-b border-slate-900/60 pb-4 mb-6">
                <h3 class="text-sm font-bold uppercase text-nftAccentPurple tracking-wider">// Asset Conversion Share Matrix</h3>
                <p class="text-[11px] text-slate-500 mt-0.5">Proportional comparison of channel traffic views vs checkout actions.</p>
            </div>

            <div class="relative w-full h-56 flex items-center justify-center my-2">
                <canvas id="enfhessConversionRoundCanvas"></canvas>
            </div>
        </div>

        <div class="grid grid-cols-2 gap-3 pt-4 border-t border-slate-900/60">
            <div class="bg-slate-950/40 border border-slate-900 rounded-xl p-3 text-center">
                <span class="inline-flex items-center text-[10px] uppercase font-bold tracking-wider text-slate-400 mb-1">
                    <span class="w-2 h-2 bg-emerald-400 rounded-full mr-1.5"></span> Total Views
                </span>
                <div class="text-base font-black font-mono text-white"><?php echo number_format($aggregateTotalViews); ?></div>
                <div class="text-[10px] font-bold font-mono text-emerald-400 mt-0.5"><?php echo $viewsPercentage; ?>%</div>
            </div>
            
            <div class="bg-slate-950/40 border border-slate-900 rounded-xl p-3 text-center">
                <span class="inline-flex items-center text-[10px] uppercase font-bold tracking-wider text-slate-400 mb-1">
                    <span class="w-2 h-2 bg-nftAccentPurple rounded-full mr-1.5"></span> Total Sold
                </span>
                <div class="text-base font-black font-mono text-white"><?php echo number_format($aggregateTotalSold); ?></div>
                <div class="text-[10px] font-bold font-mono text-nftAccentPurple mt-0.5"><?php echo $soldPercentage; ?>%</div>
            </div>
        </div>
    </div>

</div>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        // ==========================================
        // 1. INITIALIZE LEFT TREND LINE & BAR CHART
        // ==========================================
        const contextAnchor = document.getElementById('enfhessAnalyticsEngineCanvas').getContext('2d');
        
        const incomeGradientFill = contextAnchor.createLinearGradient(0, 0, 0, 300);
        incomeGradientFill.addColorStop(0, 'rgba(6, 182, 212, 0.24)');
        incomeGradientFill.addColorStop(1, 'rgba(6, 182, 212, 0.0)');

        const metricChartInstance = new Chart(contextAnchor, {
            type: 'line',
            data: {
                labels: <?php echo json_encode($jsLabels); ?>,
                datasets: [
                    {
                        label: 'Net Income (<?php echo addslashes(get_site_currency()); ?>)',
                        type: 'line',
                        data: <?php echo json_encode($jsNetProfits); ?>,
                        borderColor: '#06b6d4',
                        borderWidth: 3,
                        pointBackgroundColor: '#06b6d4',
                        pointHoverRadius: 6,
                        tension: 0.35,
                        fill: true,
                        backgroundColor: incomeGradientFill,
                        yAxisID: 'y_income_axis'
                    },
                    {
                        label: 'Units Checked Out',
                        type: 'bar',
                        data: <?php echo json_encode($jsUnitsCount); ?>,
                        backgroundColor: 'rgba(147, 51, 234, 0.45)',
                        borderColor: '#9333ea',
                        borderWidth: 1.5,
                        borderRadius: 6,
                        barThickness: 16,
                        maxBarThickness: 24,
                        yAxisID: 'y_volume_axis'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false }
                },
                scales: {
                    x: {
                        grid: { color: 'rgba(255, 255, 255, 0.02)', borderDash: [4, 4] },
                        ticks: { color: '#94a3b8', font: { family: 'monospace', size: 10 } }
                    },
                    y_income_axis: {
                        type: 'linear',
                        position: 'left',
                        grid: { color: 'rgba(255, 255, 255, 0.04)' },
                        ticks: {
                            color: '#06b6d4',
                            font: { family: 'monospace', size: 10 },
                            callback: function(value) { return '$' + value.toLocaleString(); }
                        }
                    },
                    y_volume_axis: {
                        type: 'linear',
                        position: 'right',
                        grid: { drawOnChartArea: false },
                        ticks: {
                            color: '#9333ea',
                            font: { family: 'monospace', size: 10 },
                            stepSize: 1,
                            precision: 0
                        }
                    }
                }
            }
        });

        // ==========================================
        // 2. INITIALIZE RIGHT SIDE ROUND DOUGHNUT CHART
        // ==========================================
        const roundContextAnchor = document.getElementById('enfhessConversionRoundCanvas').getContext('2d');
        
        const roundChartInstance = new Chart(roundContextAnchor, {
            type: 'doughnut',
            data: {
                labels: ['Total Views', 'Total Sold'],
                datasets: [{
                    data: [<?php echo $aggregateTotalViews; ?>, <?php echo $aggregateTotalSold; ?>],
                    backgroundColor: [
                        '#10b981', // Emerald 500 for Views
                        '#9333ea'  // Purple 600 for Units Sold
                    ],
                    borderWidth: 4,
                    borderColor: '#0b0f19', // Cohesive border layout match
                    hoverOffset: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '72%',
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: '#0f172a',
                        titleFont: { family: 'monospace', size: 11, weight: 'bold' },
                        bodyFont: { family: 'monospace', size: 11 },
                        borderColor: 'rgba(255, 255, 255, 0.05)',
                        borderWidth: 1,
                        padding: 10,
                        displayColors: true,
                        callbacks: {
                            label: function(context) {
                                let rawValue = context.raw || 0;
                                let total = context.dataset.data.reduce((a, b) => a + b, 0);
                                let percentage = total > 0 ? ((rawValue / total) * 100).toFixed(1) : 0;
                                return ' ' + context.label + ': ' + rawValue.toLocaleString() + ' (' + percentage + '%)';
                            }
                        }
                    }
                }
            }
        });
    });
</script>
