<?php
// Define your data safely
$graph_data = [
    'Sales' => $total_sales,
    'Discounts' => $total_discount,
    'VAT' => $total_vat
];

$img = imagecreatetruecolor(400, 400);
$bg = imagecolorallocate($img, 30, 30, 30);
imagefill($img, 0, 0, $bg);

// Text color
$text_color = imagecolorallocate($img, 255, 255, 255);

$total = array_sum($graph_data);

if ($total > 0) {
    // Colors
    $colors = [
        imagecolorallocate($img, 255, 111, 0),   // Sales
        imagecolorallocate($img, 255, 215, 0),   // Discounts
        imagecolorallocate($img, 135, 206, 250)  // VAT
    ];

    $values = array_values($graph_data);
    $start = 0;

    foreach ($values as $i => $val) {
        $angle = ($val / $total) * 360;
        imagefilledarc($img, 200, 200, 300, 300, $start, $start + $angle, $colors[$i], IMG_ARC_PIE);
        $start += $angle;
    }
} else {
    // If total is zero, display message
    imagestring($img, 5, 80, 180, 'No sales data available', $text_color);
}

// Output as base64
ob_start();
imagepng($img);
$image_data = ob_get_clean();
imagedestroy($img);

echo base64_encode($image_data);
