<?php
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Chart\Chart;
use PhpOffice\PhpSpreadsheet\Chart\DataSeries;
use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues;
use PhpOffice\PhpSpreadsheet\Chart\Legend;
use PhpOffice\PhpSpreadsheet\Chart\PlotArea;
use PhpOffice\PhpSpreadsheet\Chart\Title;
use PhpOffice\PhpSpreadsheet\Style\Fill;

$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();

// Sample data
$worksheet->fromArray([
    ['', 'Category 1', 'Category 2', 'Category 3'],
    ['Values', 10, 20, 15],
]);

// Define data series
$labels = [
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$B$1:$D$1', null, 3),
];
$categories = [
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, 'Worksheet!$A$2', null, 1),
];
$values = [
    new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$D$2', null, 3),
];

// Create the data series
$series = new DataSeries(
    DataSeries::TYPE_BARCHART, // Chart type
    DataSeries::GROUPING_CLUSTERED, // Grouping
    range(0, count($values) - 1), // Index for series
    $labels, // Data labels
    $categories, // Category labels
    $values // Data values
);

// Create the plot area
$plotArea = new PlotArea(null, [$series]);

// Create the chart
$chart = new Chart(
    'chart1', // Chart name
    new Title('Sample Bar Chart'), // Chart title
    new Legend(Legend::POSITION_RIGHT, null, false), // Legend
    $plotArea
);

// Set chart position
$chart->setTopLeftPosition('A4');
$chart->setBottomRightPosition('K20');

// Add chart to worksheet
$worksheet->addChart($chart);

// Set fill color for the bars
$worksheet->getStyle('B2')->getFILL()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('FFFF00'); // Yellow for first bar
$worksheet->getStyle('C2')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('008000'); // Green for second bar
$worksheet->getStyle('D2')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('0000FF'); // Blue for third bar

// Save the spreadsheet
$writer = new Xlsx($spreadsheet);
$writer->setIncludeCharts(true);
$writer->save('bar_chart_with_colors.xlsx');
?>