<?php
// generate_excel.php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
session_start();
$filesData = isset($_SESSION['filesData']) ? $_SESSION['filesData'] : [];
if (empty($filesData)) {
die("No files to process.");
}
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Set worksheet title and document properties
$sheet->setTitle('GST-3B Report');
$spreadsheet->getProperties()
->setCreator('GST Report Generator')
->setTitle('GST-3B Full Report')
->setSubject('GST-3B Data Export')
->setDescription('Generated GST-3B Excel report with complete formatting');
// Headers array (same as your original)
$headers = [
'GSTIN', 'Return Period',
// Outward Supplies (Sales) Details
'Outward supplies taxable value (excluding zero rated/exempt sales)', 'Integrated Tax on outward supplies', 'Central GST on outward supplies', 'State GST on outward supplies', 'Cess on outward supplies',
'Zero rated supplies taxable value', 'IGST on zero rated supplies', 'CGST on zero rated supplies', 'SGST on zero rated supplies', 'Cess on zero rated supplies',
'Nil rated or exempt supplies taxable value', 'IGST on nil/exempt supplies', 'CGST on nil/exempt supplies', 'SGST on nil/exempt supplies', 'Cess on nil/exempt supplies',
// Reversed Outward Supplies
'Reversed outward supplies taxable value', 'IGST reversed externally', 'CGST reversed externally', 'SGST reversed externally', 'Cess reversed externally',
// Non-GST Outward Supplies
'Outward supply of goods/services not liable to GST', 'IGST on non-GST outward supplies (usually zero/null)', 'CGST on non-GST outward supplies', 'SGST on non-GST outward supplies', 'Cess on non-GST outward supplies',
// Input Tax Credit (ITC) Available (By Source)
'ITC available on imported goods (IGST portion)', 'ITC available on imported goods (CGST portion)', 'ITC available on imported goods (SGST portion)', 'ITC available on imported goods (Cess portion)',
'ITC available on inward supplies from registered taxpayers (IGST)', 'ITC available on inward supplies from registered taxpayers (CGST)', 'ITC available on inward supplies from registered taxpayers (SGST)', 'ITC available on inward supplies from registered taxpayers (Cess)',
'ITC available on other inputs (IGST)', 'ITC available on other inputs (CGST)', 'ITC available on other inputs (SGST)', 'ITC available on other inputs (Cess)',
'ITC available from Input Service Distributor (IGST)', 'ITC available from ISD (CGST)', 'ITC available from ISD (SGST)', 'ITC available from ISD (Cess)',
'ITC available on inward supplies from IS (IGST)', 'ITC available on inward supplies from IS (CGST)', 'ITC available on inward supplies from IS (SGST)', 'ITC available on inward supplies from IS (Cess)',
// Reversed ITC (ITC Reversed)
'ITC reversed as per rules (IGST portion)', 'ITC reversed as per rules (CGST)', 'ITC reversed as per rules (SGST)', 'ITC reversed as per rules (Cess)',
'ITC reversed other than rules (IGST)', 'ITC reversed other than rules (CGST)', 'ITC reversed other than rules (SGST)', 'ITC reversed other than rules (Cess)',
// Net ITC Available (After Reversal)
'Net ITC available (IGST) after reversal', 'Net ITC available (CGST) after reversal', 'Net ITC available (SGST) after reversal', 'Net ITC available (Cess) after reversal',
// Ineligible ITC
'ITC ineligible as per rules (IGST)', 'ITC ineligible as per rules (CGST)', 'ITC ineligible as per rules (SGST)', 'ITC ineligible as per rules (Cess)',
'ITC ineligible other reasons (IGST)', 'ITC ineligible other reasons (CGST)', 'ITC ineligible other reasons (SGST)', 'ITC ineligible other reasons (Cess)',
// Interest
'Interest amount (IGST)', 'Interest amount (CGST)', 'Interest amount (SGST)', 'Interest amount (Cess)',
// Late Fees
'Late fee (IGST)', 'Late fee (CGST)', 'Late fee (SGST)', 'Late fee (Cess)',
// Total Tax Liability and Payments
'Total tax payable', 'Total cash paid', 'Total ITC utilized',
// Unknown q1 to q7 (possibly system fields or internal codes)
'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields',
// Cash Balance of Tax Components
'Cash balance IGST tax', 'Cash balance IGST interest', 'Cash balance IGST penalty', 'Cash balance IGST fee', 'Cash balance IGST others',
'Cash balance CGST tax', 'Cash balance CGST interest', 'Cash balance CGST penalty', 'Cash balance CGST fee', 'Cash balance CGST others',
'Cash balance SGST tax', 'Cash balance SGST interest', 'Cash balance SGST penalty', 'Cash balance SGST fee', 'Cash balance SGST others',
'Cash balance cess tax', 'Cash balance cess interest', 'Cash balance cess penalty', 'Cash balance cess fee', 'Cash balance cess others',
// Total Balance of Tax Components
'Total balance IGST', 'Total balance CGST', 'Total balance SGST', 'Total balance cess',
// ITC Balances
'ITC balance IGST', 'ITC balance CGST', 'ITC balance SGST', 'ITC balance Cess',
// Status
'Filing status (e.g., filed, pending, rejected)',
// Tax Payment Details by Tax Type & Components
'Tax paid IGST (tax)', 'Tax paid IGST (interest)', 'Tax paid IGST (penalty)', 'Tax paid IGST (fee)', 'Tax paid IGST (others)', 'Total tax paid IGST',
'Tax paid SGST (tax)', 'Tax paid SGST (interest)', 'Tax paid SGST (penalty)', 'Tax paid SGST (fee)', 'Tax paid SGST (others)', 'Total tax paid SGST',
'Tax paid CGST (tax)', 'Tax paid CGST (interest)', 'Tax paid CGST (penalty)', 'Tax paid CGST (fee)', 'Tax paid CGST (others)', 'Total tax paid CGST',
'Tax paid Cess (tax)', 'Tax paid Cess (interest)', 'Tax paid Cess (penalty)', 'Tax paid Cess (fee)', 'Tax paid Cess (others)', 'Total tax paid Cess',
// Tax Payment Transaction Details
'Tax payment liability ID', 'Tax payment transaction code', 'Tax payment transaction date',
// Tax Paid by ITC Details
'Debit ledger ID from which ITC utilized to pay tax', 'Liability ledger ID for ITC utilization',
'IGST paid by utilizing IGST ITC', 'IGST paid by utilizing CGST ITC', 'IGST paid by utilizing SGST ITC',
'SGST paid by utilizing SGST ITC', 'SGST paid by utilizing IGST ITC',
'CGST paid by utilizing CGST ITC', 'CGST paid by utilizing IGST ITC',
'Cess paid by utilizing Cess ITC',
'ITC utilization transaction code', 'ITC utilization transaction date',
];
// Write headers to row 1
$colIndex = 1; // PhpSpreadsheet columns are 1-indexed
foreach ($headers as $header) {
$colLetter = Coordinate::stringFromColumnIndex($colIndex);
$sheet->setCellValue($colLetter . '1', $header);
$colIndex++;
}
// Write data rows starting from row 2
$rowIndex = 2;
foreach ($filesData as $item) {
$colIndex = 1;
// Helper to write and increment column index
$setCell = function($value) use ($sheet, &$colIndex, $rowIndex) {
$colLetter = Coordinate::stringFromColumnIndex($colIndex);
$sheet->setCellValue($colLetter . $rowIndex, $value);
$colIndex++;
};
// Write fields in the same order as headers
$setCell($item['gstin'] ?? '');
$setCell($item['ret_period'] ?? '');
$sup = $item['sup_details'] ?? [];
// osup_det
$osup_det = $sup['osup_det'] ?? [];
$setCell($osup_det['txval'] ?? '');
$setCell($osup_det['iamt'] ?? '');
$setCell($osup_det['camt'] ?? '');
$setCell($osup_det['samt'] ?? '');
$setCell($osup_det['csamt'] ?? '');
// osup_zero
$osup_zero = $sup['osup_zero'] ?? [];
$setCell($osup_zero['txval'] ?? '');
$setCell($osup_zero['iamt'] ?? '');
$setCell($osup_zero['camt'] ?? '');
$setCell($osup_zero['samt'] ?? '');
$setCell($osup_zero['csamt'] ?? '');
// osup_nil_exmp
$osup_nil_exmp = $sup['osup_nil_exmp'] ?? [];
$setCell($osup_nil_exmp['txval'] ?? '');
$setCell($osup_nil_exmp['iamt'] ?? '');
$setCell($osup_nil_exmp['camt'] ?? '');
$setCell($osup_nil_exmp['samt'] ?? '');
$setCell($osup_nil_exmp['csamt'] ?? '');
// isup_rev
$isup_rev = $sup['isup_rev'] ?? [];
$setCell($isup_rev['txval'] ?? '');
$setCell($isup_rev['iamt'] ?? '');
$setCell($isup_rev['camt'] ?? '');
$setCell($isup_rev['samt'] ?? '');
$setCell($isup_rev['csamt'] ?? '');
// osup_nongst
$osup_nongst = $sup['osup_nongst'] ?? [];
$setCell($osup_nongst['txval'] ?? '');
$setCell($osup_nongst['iamt'] ?? '');
$setCell($osup_nongst['camt'] ?? '');
$setCell($osup_nongst['samt'] ?? '');
$setCell($osup_nongst['csamt'] ?? '');
// itc_elg - itc_avl (map by 'ty')
$itc_avl = $item['itc_elg']['itc_avl'] ?? [];
$itc_avl_map = [];
foreach ($itc_avl as $itc) {
$itc_avl_map[$itc['ty']] = $itc;
}
$types_avl = ['IMPG', 'ISRC', 'OTH', 'ISD', 'IMPS'];
foreach ($types_avl as $type) {
$itc = $itc_avl_map[$type] ?? [];
$setCell($itc['iamt'] ?? '');
$setCell($itc['camt'] ?? '');
$setCell($itc['samt'] ?? '');
$setCell($itc['csamt'] ?? '');
}
// itc_elg - itc_rev
$itc_rev = $item['itc_elg']['itc_rev'] ?? [];
$itc_rev_map = [];
foreach ($itc_rev as $itc) {
$itc_rev_map[$itc['ty']] = $itc;
}
$types_rev = ['RUL', 'OTH'];
foreach ($types_rev as $type) {
$itc = $itc_rev_map[$type] ?? [];
$setCell($itc['iamt'] ?? '');
$setCell($itc['camt'] ?? '');
$setCell($itc['samt'] ?? '');
$setCell($itc['csamt'] ?? '');
}
// itc_elg - itc_net
$itc_net = $item['itc_elg']['itc_net'] ?? [];
$setCell($itc_net['iamt'] ?? '');
$setCell($itc_net['camt'] ?? '');
$setCell($itc_net['samt'] ?? '');
$setCell($itc_net['csamt'] ?? '');
// itc_elg - itc_inelg
$itc_inelg = $item['itc_elg']['itc_inelg'] ?? [];
$itc_inelg_map = [];
foreach ($itc_inelg as $itc) {
$itc_inelg_map[$itc['ty']] = $itc;
}
$types_inelg = ['RUL', 'OTH'];
foreach ($types_inelg as $type) {
$itc = $itc_inelg_map[$type] ?? [];
$setCell($itc['iamt'] ?? '');
$setCell($itc['camt'] ?? '');
$setCell($itc['samt'] ?? '');
$setCell($itc['csamt'] ?? '');
}
// intr_ltfee
$intr_ltfee = $item['intr_ltfee'] ?? [];
$intr_details = $intr_ltfee['intr_details'] ?? [];
$setCell($intr_details['iamt'] ?? '');
$setCell($intr_details['camt'] ?? '');
$setCell($intr_details['samt'] ?? '');
$setCell($intr_details['csamt'] ?? '');
$ltfee_details = $intr_ltfee['ltfee_details'] ?? [];
$setCell($ltfee_details['iamt'] ?? '');
$setCell($ltfee_details['camt'] ?? '');
$setCell($ltfee_details['samt'] ?? '');
$setCell($ltfee_details['csamt'] ?? '');
// tt_val
$tt_val = $item['tt_val'] ?? [];
$setCell($tt_val['tt_pay'] ?? '');
$setCell($tt_val['tt_csh_pd'] ?? '');
$setCell($tt_val['tt_itc_pd'] ?? '');
// qn
$qn = $item['qn'] ?? [];
$setCell($qn['q1'] ?? '');
$setCell($qn['q2'] ?? '');
$setCell($qn['q3'] ?? '');
$setCell($qn['q4'] ?? '');
$setCell($qn['q5'] ?? '');
$setCell($qn['q6'] ?? '');
$setCell($qn['q7'] ?? '');
// taxpayble - bal - cash_bal
$bal = $item['taxpayble']['bal'] ?? [];
$cash_bal = $bal['cash_bal'] ?? [];
$igst = $cash_bal['igst'] ?? [];
$setCell($igst['tx'] ?? '');
$setCell($igst['intr'] ?? '');
$setCell($igst['pen'] ?? '');
$setCell($igst['fee'] ?? '');
$setCell($igst['oth'] ?? '');
$cgst = $cash_bal['cgst'] ?? [];
$setCell($cgst['tx'] ?? '');
$setCell($cgst['intr'] ?? '');
$setCell($cgst['pen'] ?? '');
$setCell($cgst['fee'] ?? '');
$setCell($cgst['oth'] ?? '');
$sgst = $cash_bal['sgst'] ?? [];
$setCell($sgst['tx'] ?? '');
$setCell($sgst['intr'] ?? '');
$setCell($sgst['pen'] ?? '');
$setCell($sgst['fee'] ?? '');
$setCell($sgst['oth'] ?? '');
$cess = $cash_bal['cess'] ?? [];
$setCell($cess['tx'] ?? '');
$setCell($cess['intr'] ?? '');
$setCell($cess['pen'] ?? '');
$setCell($cess['fee'] ?? '');
$setCell($cess['oth'] ?? '');
$setCell($bal['igst_tot_bal'] ?? '');
$setCell($bal['cgst_tot_bal'] ?? '');
$setCell($bal['sgst_tot_bal'] ?? '');
$setCell($bal['cess_tot_bal'] ?? '');
// taxpayble - bal - itc_bal
$itc_bal = $bal['itc_bal'] ?? [];
$setCell($itc_bal['igst_bal'] ?? '');
$setCell($itc_bal['cgst_bal'] ?? '');
$setCell($itc_bal['sgst_bal'] ?? '');
$setCell($itc_bal['cess_bal'] ?? '');
// taxpayble - status
$setCell($item['taxpayble']['status'] ?? '');
// taxpayble - returnsDbCdredList - tax_pay (first entry)
$tax_pay = $item['taxpayble']['returnsDbCdredList']['tax_pay'][0] ?? [];
$tax_pay_igst = $tax_pay['igst'] ?? [];
$setCell($tax_pay_igst['tx'] ?? '');
$setCell($tax_pay_igst['intr'] ?? '');
$setCell($tax_pay_igst['pen'] ?? '');
$setCell($tax_pay_igst['fee'] ?? '');
$setCell($tax_pay_igst['oth'] ?? '');
$setCell($tax_pay_igst['tot'] ?? '');
$tax_pay_sgst = $tax_pay['sgst'] ?? [];
$setCell($tax_pay_sgst['tx'] ?? '');
$setCell($tax_pay_sgst['intr'] ?? '');
$setCell($tax_pay_sgst['pen'] ?? '');
$setCell($tax_pay_sgst['fee'] ?? '');
$setCell($tax_pay_sgst['oth'] ?? '');
$setCell($tax_pay_sgst['tot'] ?? '');
$tax_pay_cgst = $tax_pay['cgst'] ?? [];
$setCell($tax_pay_cgst['tx'] ?? '');
$setCell($tax_pay_cgst['intr'] ?? '');
$setCell($tax_pay_cgst['pen'] ?? '');
$setCell($tax_pay_cgst['fee'] ?? '');
$setCell($tax_pay_cgst['oth'] ?? '');
$setCell($tax_pay_cgst['tot'] ?? '');
$tax_pay_cess = $tax_pay['cess'] ?? [];
$setCell($tax_pay_cess['tx'] ?? '');
$setCell($tax_pay_cess['intr'] ?? '');
$setCell($tax_pay_cess['pen'] ?? '');
$setCell($tax_pay_cess['fee'] ?? '');
$setCell($tax_pay_cess['oth'] ?? '');
$setCell($tax_pay_cess['tot'] ?? '');
$setCell($tax_pay['liab_id'] ?? '');
$setCell($tax_pay['trancd'] ?? '');
$setCell($tax_pay['trandate'] ?? '');
// taxpayble - returnsDbCdredList - tax_paid - pd_by_itc (first entry)
$tax_paid_itc = $item['taxpayble']['returnsDbCdredList']['tax_paid']['pd_by_itc'][0] ?? [];
$setCell($tax_paid_itc['debit_id'] ?? '');
$setCell($tax_paid_itc['liab_id'] ?? '');
$setCell($tax_paid_itc['igst_igst_amt'] ?? '');
$setCell($tax_paid_itc['igst_cgst_amt'] ?? '');
$setCell($tax_paid_itc['igst_sgst_amt'] ?? '');
$setCell($tax_paid_itc['sgst_sgst_amt'] ?? '');
$setCell($tax_paid_itc['sgst_igst_amt'] ?? '');
$setCell($tax_paid_itc['cgst_cgst_amt'] ?? '');
$setCell($tax_paid_itc['cgst_igst_amt'] ?? '');
$setCell($tax_paid_itc['cess_cess_amt'] ?? '');
$setCell($tax_paid_itc['trancd'] ?? '');
$setCell($tax_paid_itc['trandate'] ?? '');
$rowIndex++;
}
// --- Apply Styling ---
// Freeze the header row
$sheet->freezePane('A2');
// Calculate last column letter
$lastColLetter = Coordinate::stringFromColumnIndex(count($headers));
// Style header row
$headerStyleArray = [
'font' => [
'bold' => true,
'color' => ['rgb' => 'FFFFFF'],
'size' => 12,
],
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER,
'wrapText' => true,
],
'fill' => [
'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => '4A6FA5'], // GST blue
],
'borders' => [
'bottom' => [
'borderStyle' => Border::BORDER_THICK,
'color' => ['rgb' => 'CCCCCC'],
],
'allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['rgb' => 'CCCCCC'],
],
],
];
$sheet->getStyle("A1:{$lastColLetter}1")->applyFromArray($headerStyleArray);
$sheet->getRowDimension(1)->setRowHeight(30);
// Set column widths and alignment
for ($col = 1; $col <= count($headers); $col++) {
$colLetter = Coordinate::stringFromColumnIndex($col);
// Wider column for GSTIN and Return Period
if ($col === 1 || $col === 2) {
$sheet->getColumnDimension($colLetter)->setWidth(20);
$sheet->getStyle("{$colLetter}2:{$colLetter}{$rowIndex}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
} else {
$sheet->getColumnDimension($colLetter)->setWidth(15);
$sheet->getStyle("{$colLetter}2:{$colLetter}{$rowIndex}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
}
$sheet->getStyle("{$colLetter}2:{$colLetter}{$rowIndex}")->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
}
// Apply borders and alternating row background color
$borderStyleArray = [
'borders' => [
'allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['rgb' => 'DDDDDD'],
],
],
];
for ($r = 2; $r < $rowIndex; $r++) {
$sheet->getStyle("A{$r}:{$lastColLetter}{$r}")->applyFromArray($borderStyleArray);
// Alternate row fill
if ($r % 2 === 0) {
$sheet->getStyle("A{$r}:{$lastColLetter}{$r}")
->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()
->setRGB('F9FAFC');
}
}
// Number formatting: all except GSTIN and Return Period columns are numbers with 2 decimals
for ($col = 3; $col <= count($headers); $col++) {
$colLetter = Coordinate::stringFromColumnIndex($col);
$sheet->getStyle("{$colLetter}2:{$colLetter}{$rowIndex}")
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_NUMBER_00);
}
// Date formatting - Find column index of "Tax payment transaction date"
$dateColIndex = array_search('Tax payment transaction date', $headers);
if ($dateColIndex !== false) {
// PhpSpreadsheet columns are 1-based, array_search returns 0-based, so +1
$dateCol = Coordinate::stringFromColumnIndex($dateColIndex + 1);
$sheet->getStyle("{$dateCol}2:{$dateCol}{$rowIndex}")
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_DATE_DDMMYYYY);
}
// Output Excel file headers and save
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="GST_Report_Full.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit;
?>
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
session_start();
$filesData = isset($_SESSION['filesData']) ? $_SESSION['filesData'] : [];
if (empty($filesData)) {
die("No files to process.");
}
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('GST-3B Horizontal Report');
$spreadsheet->getProperties()
->setCreator('GST Report Generator')
->setTitle('GST-3B Horizontal Full Report')
->setSubject('GST-3B Data Export')
->setDescription('Generated horizontal GST-3B Excel report');
// Your headers (field names):
$headers = [
'GSTIN', 'Return Period',
'Outward supplies taxable value (excluding zero rated/exempt sales)', 'Integrated Tax on outward supplies', 'Central GST on outward supplies', 'State GST on outward supplies', 'Cess on outward supplies',
'Zero rated supplies taxable value', 'IGST on zero rated supplies', 'CGST on zero rated supplies', 'SGST on zero rated supplies', 'Cess on zero rated supplies',
'Nil rated or exempt supplies taxable value', 'IGST on nil/exempt supplies', 'CGST on nil/exempt supplies', 'SGST on nil/exempt supplies', 'Cess on nil/exempt supplies',
'Reversed outward supplies taxable value', 'IGST reversed externally', 'CGST reversed externally', 'SGST reversed externally', 'Cess reversed externally',
'Outward supply of goods/services not liable to GST', 'IGST on non-GST outward supplies (usually zero/null)', 'CGST on non-GST outward supplies', 'SGST on non-GST outward supplies', 'Cess on non-GST outward supplies',
'ITC available on imported goods (IGST portion)', 'ITC available on imported goods (CGST portion)', 'ITC available on imported goods (SGST portion)', 'ITC available on imported goods (Cess portion)',
'ITC available on inward supplies from registered taxpayers (IGST)', 'ITC available on inward supplies from registered taxpayers (CGST)', 'ITC available on inward supplies from registered taxpayers (SGST)', 'ITC available on inward supplies from registered taxpayers (Cess)',
'ITC available on other inputs (IGST)', 'ITC available on other inputs (CGST)', 'ITC available on other inputs (SGST)', 'ITC available on other inputs (Cess)',
'ITC available from Input Service Distributor (IGST)', 'ITC available from ISD (CGST)', 'ITC available from ISD (SGST)', 'ITC available from ISD (Cess)',
'ITC available on inward supplies from IS (IGST)', 'ITC available on inward supplies from IS (CGST)', 'ITC available on inward supplies from IS (SGST)', 'ITC available on inward supplies from IS (Cess)',
'ITC reversed as per rules (IGST portion)', 'ITC reversed as per rules (CGST)', 'ITC reversed as per rules (SGST)', 'ITC reversed as per rules (Cess)',
'ITC reversed other than rules (IGST)', 'ITC reversed other than rules (CGST)', 'ITC reversed other than rules (SGST)', 'ITC reversed other than rules (Cess)',
'Net ITC available (IGST) after reversal', 'Net ITC available (CGST) after reversal', 'Net ITC available (SGST) after reversal', 'Net ITC available (Cess) after reversal',
'ITC ineligible as per rules (IGST)', 'ITC ineligible as per rules (CGST)', 'ITC ineligible as per rules (SGST)', 'ITC ineligible as per rules (Cess)',
'ITC ineligible other reasons (IGST)', 'ITC ineligible other reasons (CGST)', 'ITC ineligible other reasons (SGST)', 'ITC ineligible other reasons (Cess)',
'Interest amount (IGST)', 'Interest amount (CGST)', 'Interest amount (SGST)', 'Interest amount (Cess)',
'Late fee (IGST)', 'Late fee (CGST)', 'Late fee (SGST)', 'Late fee (Cess)',
'Total tax payable', 'Total cash paid', 'Total ITC utilized',
'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields',
'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields',
'Various internal indicators or calculated fields',
'Cash balance IGST tax', 'Cash balance IGST interest', 'Cash balance IGST penalty', 'Cash balance IGST fee', 'Cash balance IGST others',
'Cash balance CGST tax', 'Cash balance CGST interest', 'Cash balance CGST penalty', 'Cash balance CGST fee', 'Cash balance CGST others',
'Cash balance SGST tax', 'Cash balance SGST interest', 'Cash balance SGST penalty', 'Cash balance SGST fee', 'Cash balance SGST others',
'Cash balance cess tax', 'Cash balance cess interest', 'Cash balance cess penalty', 'Cash balance cess fee', 'Cash balance cess others',
'Total balance IGST', 'Total balance CGST', 'Total balance SGST', 'Total balance cess',
'ITC balance IGST', 'ITC balance CGST', 'ITC balance SGST', 'ITC balance Cess',
'Filing status (e.g., filed, pending, rejected)',
'Tax paid IGST (tax)', 'Tax paid IGST (interest)', 'Tax paid IGST (penalty)', 'Tax paid IGST (fee)', 'Tax paid IGST (others)', 'Total tax paid IGST',
'Tax paid SGST (tax)', 'Tax paid SGST (interest)', 'Tax paid SGST (penalty)', 'Tax paid SGST (fee)', 'Tax paid SGST (others)', 'Total tax paid SGST',
'Tax paid CGST (tax)', 'Tax paid CGST (interest)', 'Tax paid CGST (penalty)', 'Tax paid CGST (fee)', 'Tax paid CGST (others)', 'Total tax paid CGST',
'Tax paid Cess (tax)', 'Tax paid Cess (interest)', 'Tax paid Cess (penalty)', 'Tax paid Cess (fee)', 'Tax paid Cess (others)', 'Total tax paid Cess',
'Tax payment liability ID', 'Tax payment transaction code', 'Tax payment transaction date',
'Debit ledger ID from which ITC utilized to pay tax', 'Liability ledger ID for ITC utilization',
'IGST paid by utilizing IGST ITC', 'IGST paid by utilizing CGST ITC', 'IGST paid by utilizing SGST ITC',
'SGST paid by utilizing SGST ITC', 'SGST paid by utilizing IGST ITC',
'CGST paid by utilizing CGST ITC', 'CGST paid by utilizing IGST ITC',
'Cess paid by utilizing Cess ITC',
'ITC utilization transaction code', 'ITC utilization transaction date',
];
// Write GSTINs horizontally starting from B1
$gstinList = [];
foreach ($filesData as $item) {
$gstinList[] = $item['gstin'] ?? 'Unknown GSTIN';
}
$gstinCount = count($gstinList);
for ($i = 0; $i < $gstinCount; $i++) {
$colLetter = Coordinate::stringFromColumnIndex($i + 2); // B=2, etc
$sheet->setCellValue($colLetter . '1', $gstinList[$i]);
}
// Write headers vertically starting from A2
$fieldCount = count($headers);
for ($r = 0; $r < $fieldCount; $r++) {
$sheet->setCellValue('A' . ($r + 2), $headers[$r]);
}
// Helper fn to safely read nested keys (handles missing)
function getNestedValue($array, $keys) {
foreach ($keys as $key) {
if (!isset($array[$key])) return '';
$array = $array[$key];
}
return $array;
}
// Write data by field (rows), GSTIN (cols)
for ($c = 0; $c < $gstinCount; $c++) {
$item = $filesData[$c];
for ($r = 0; $r < $fieldCount; $r++) {
$colLetter = Coordinate::stringFromColumnIndex($c + 2);
$rowNum = $r + 2;
$field = $headers[$r];
$value = '';
// Map field to data: Simplified; expand as per your full map below
switch ($field) {
case 'GSTIN':
$value = $item['gstin'] ?? '';
break;
case 'Return Period':
$value = $item['ret_period'] ?? '';
break;
case 'Outward supplies taxable value (excluding zero rated/exempt sales)':
$value = getNestedValue($item, ['sup_details', 'osup_det', 'txval']);
break;
case 'Integrated Tax on outward supplies':
$value = getNestedValue($item, ['sup_details', 'osup_det', 'iamt']);
break;
case 'Central GST on outward supplies':
$value = getNestedValue($item, ['sup_details', 'osup_det', 'camt']);
break;
case 'State GST on outward supplies':
$value = getNestedValue($item, ['sup_details', 'osup_det', 'samt']);
break;
case 'Cess on outward supplies':
$value = getNestedValue($item, ['sup_details', 'osup_det', 'csamt']);
break;
// Continue mapping rest of headers similarly...
// Example: you should implement the full mapping logic here for all headers based on your original data structure
default:
$value = ''; // Or leave blank (implement all fields as needed)
break;
}
$sheet->setCellValue($colLetter . $rowNum, $value);
}
}
// --- Styling ---
$lastColIndex = $gstinCount + 1; // +1 for Column A (fields)
$lastColLetter = Coordinate::stringFromColumnIndex($lastColIndex);
$lastRowNum = $fieldCount + 1;
// Freeze title row and field name column
$sheet->freezePane('B2');
// Style header row (GSTINs - Row 1)
$sheet->getStyle("B1:{$lastColLetter}1")->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '4A6FA5']],
'borders' => ['bottom' => ['borderStyle' => Border::BORDER_MEDIUM, 'color' => ['rgb' => '333333']]],
]);
// Style field names column (A)
$sheet->getStyle("A2:A{$lastRowNum}")->applyFromArray([
'font' => ['bold' => true],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_LEFT, 'vertical' => Alignment::VERTICAL_CENTER],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => 'D9E1F2']],
'borders' => ['right' => ['borderStyle' => Border::BORDER_MEDIUM, 'color' => ['rgb' => '333333']]],
]);
$sheet->getColumnDimension('A')->setWidth(50);
// Set GSTIN columns width
for ($c = 2; $c <= $lastColIndex; $c++) {
$colL = Coordinate::stringFromColumnIndex($c);
$sheet->getColumnDimension($colL)->setWidth(20);
$sheet->getStyle("{$colL}2:{$colL}{$lastRowNum}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
$sheet->getStyle("{$colL}2:{$colL}{$lastRowNum}")->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
}
// Apply border to entire data range
$sheet->getStyle("A1:{$lastColLetter}{$lastRowNum}")->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
// Apply alternating row fill on field names rows for readability (even row)
for ($r = 2; $r <= $lastRowNum; $r++) {
if (($r % 2) == 0) {
$sheet->getStyle("A{$r}:{$lastColLetter}{$r}")->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFF4F6FA');
}
}
// Number format GSTIN columns, except GSTIN and Return Period rows (rows 1 and 2 correspond to GSTIN header and fields)
for ($c = 2; $c <= $lastColIndex; $c++) {
$colL = Coordinate::stringFromColumnIndex($c);
$sheet->getStyle("{$colL}2:{$colL}{$lastRowNum}")
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_NUMBER_00);
}
// Date formatting for "Tax payment transaction date" row - find row number
$dateFieldRowIndex = array_search('Tax payment transaction date', $headers);
if ($dateFieldRowIndex !== false) {
$dateRowNum = $dateFieldRowIndex + 2;
$sheet->getStyle("B{$dateRowNum}:{$lastColLetter}{$dateRowNum}")
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_DATE_DDMMYYYY);
}
// --- Conditional Formatting for Zero and Negative Values ---
$conditionalRange = "B2:{$lastColLetter}{$lastRowNum}";
// Negative values red font
$negCond = new Conditional();
$negCond->setConditionType(Conditional::CONDITION_CELLIS)
->setOperatorType(Conditional::OPERATOR_LESSTHAN)
->addCondition('0');
$negCond->getStyle()->getFont()->getColor()->setARGB('FFFF0000');
// Zero values light gray fill
$zeroCond = new Conditional();
$zeroCond->setConditionType(Conditional::CONDITION_CELLIS)
->setOperatorType(Conditional::OPERATOR_EQUAL)
->addCondition('0');
$zeroCond->getStyle()->getFill()->setFillType(Fill::FILL_SOLID);
$zeroCond->getStyle()->getFill()->getStartColor()->setARGB('FFEEEEEE');
$sheet->getStyle($conditionalRange)->setConditionalStyles([$negCond, $zeroCond]);
// --- Output the file ---
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="GST_Report_Horizontal.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit;
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
session_start();
$filesData = isset($_SESSION['filesData']) ? $_SESSION['filesData'] : [];
if (empty($filesData)) {
die("No files to process.");
}
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('GST-3B Horizontal Report');
$spreadsheet->getProperties()
->setCreator('GST Report Generator')
->setTitle('GST-3B Horizontal Full Report')
->setSubject('GST-3B Data Export')
->setDescription('Generated horizontal GST-3B Excel report');
// Define headers (field names)
$headers = [
'GSTIN', 'Return Period',
'Outward supplies taxable value (excluding zero rated/exempt sales)', 'Integrated Tax on outward supplies', 'Central GST on outward supplies', 'State GST on outward supplies', 'Cess on outward supplies',
'Zero rated supplies taxable value', 'IGST on zero rated supplies', 'CGST on zero rated supplies', 'SGST on zero rated supplies', 'Cess on zero rated supplies',
'Nil rated or exempt supplies taxable value', 'IGST on nil/exempt supplies', 'CGST on nil/exempt supplies', 'SGST on nil/exempt supplies', 'Cess on nil/exempt supplies',
'Reversed outward supplies taxable value', 'IGST reversed externally', 'CGST reversed externally', 'SGST reversed externally', 'Cess reversed externally',
'Outward supply of goods/services not liable to GST', 'IGST on non-GST outward supplies (usually zero/null)', 'CGST on non-GST outward supplies', 'SGST on non-GST outward supplies', 'Cess on non-GST outward supplies',
'ITC available on imported goods (IGST portion)', 'ITC available on imported goods (CGST portion)', 'ITC available on imported goods (SGST portion)', 'ITC available on imported goods (Cess portion)',
'ITC available on inward supplies from registered taxpayers (IGST)', 'ITC available on inward supplies from registered taxpayers (CGST)', 'ITC available on inward supplies from registered taxpayers (SGST)', 'ITC available on inward supplies from registered taxpayers (Cess)',
'ITC available on other inputs (IGST)', 'ITC available on other inputs (CGST)', 'ITC available on other inputs (SGST)', 'ITC available on other inputs (Cess)',
'ITC available from Input Service Distributor (IGST)', 'ITC available from ISD (CGST)', 'ITC available from ISD (SGST)', 'ITC available from ISD (Cess)',
'ITC available on inward supplies from IS (IGST)', 'ITC available on inward supplies from IS (CGST)', 'ITC available on inward supplies from IS (SGST)', 'ITC available on inward supplies from IS (Cess)',
'ITC reversed as per rules (IGST portion)', 'ITC reversed as per rules (CGST)', 'ITC reversed as per rules (SGST)', 'ITC reversed as per rules (Cess)',
'ITC reversed other than rules (IGST)', 'ITC reversed other than rules (CGST)', 'ITC reversed other than rules (SGST)', 'ITC reversed other than rules (Cess)',
'Net ITC available (IGST) after reversal', 'Net ITC available (CGST) after reversal', 'Net ITC available (SGST) after reversal', 'Net ITC available (Cess) after reversal',
'ITC ineligible as per rules (IGST)', 'ITC ineligible as per rules (CGST)', 'ITC ineligible as per rules (SGST)', 'ITC ineligible as per rules (Cess)',
'ITC ineligible other reasons (IGST)', 'ITC ineligible other reasons (CGST)', 'ITC ineligible other reasons (SGST)', 'ITC ineligible other reasons (Cess)',
'Interest amount (IGST)', 'Interest amount (CGST)', 'Interest amount (SGST)', 'Interest amount (Cess)',
'Late fee (IGST)', 'Late fee (CGST)', 'Late fee (SGST)', 'Late fee (Cess)',
'Total tax payable', 'Total cash paid', 'Total ITC utilized',
'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields',
'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields', 'Various internal indicators or calculated fields',
'Various internal indicators or calculated fields',
'Cash balance IGST tax', 'Cash balance IGST interest', 'Cash balance IGST penalty', 'Cash balance IGST fee', 'Cash balance IGST others',
'Cash balance CGST tax', 'Cash balance CGST interest', 'Cash balance CGST penalty', 'Cash balance CGST fee', 'Cash balance CGST others',
'Cash balance SGST tax', 'Cash balance SGST interest', 'Cash balance SGST penalty', 'Cash balance SGST fee', 'Cash balance SGST others',
'Cash balance cess tax', 'Cash balance cess interest', 'Cash balance cess penalty', 'Cash balance cess fee', 'Cash balance cess others',
'Total balance IGST', 'Total balance CGST', 'Total balance SGST', 'Total balance cess',
'ITC balance IGST', 'ITC balance CGST', 'ITC balance SGST', 'ITC balance Cess',
'Filing status (e.g., filed, pending, rejected)',
'Tax paid IGST (tax)', 'Tax paid IGST (interest)', 'Tax paid IGST (penalty)', 'Tax paid IGST (fee)', 'Tax paid IGST (others)', 'Total tax paid IGST',
'Tax paid SGST (tax)', 'Tax paid SGST (interest)', 'Tax paid SGST (penalty)', 'Tax paid SGST (fee)', 'Tax paid SGST (others)', 'Total tax paid SGST',
'Tax paid CGST (tax)', 'Tax paid CGST (interest)', 'Tax paid CGST (penalty)', 'Tax paid CGST (fee)', 'Tax paid CGST (others)', 'Total tax paid CGST',
'Tax paid Cess (tax)', 'Tax paid Cess (interest)', 'Tax paid Cess (penalty)', 'Tax paid Cess (fee)', 'Tax paid Cess (others)', 'Total tax paid Cess',
'Tax payment liability ID', 'Tax payment transaction code', 'Tax payment transaction date',
'Debit ledger ID from which ITC utilized to pay tax', 'Liability ledger ID for ITC utilization',
'IGST paid by utilizing IGST ITC', 'IGST paid by utilizing CGST ITC', 'IGST paid by utilizing SGST ITC',
'SGST paid by utilizing SGST ITC', 'SGST paid by utilizing IGST ITC',
'CGST paid by utilizing CGST ITC', 'CGST paid by utilizing IGST ITC',
'Cess paid by utilizing Cess ITC',
'ITC utilization transaction code', 'ITC utilization transaction date',
];
// Map each header to JSON keypaths or special handlers (to iterate arrays etc)
// Paths are arrays of keys for nested lookup or special case strings
$mapping = [
'GSTIN' => ['gstin'],
'Return Period' => ['ret_period'],
// Outward Supplies (osup_det)
'Outward supplies taxable value (excluding zero rated/exempt sales)' => ['sup_details', 'osup_det', 'txval'],
'Integrated Tax on outward supplies' => ['sup_details', 'osup_det', 'iamt'],
'Central GST on outward supplies' => ['sup_details', 'osup_det', 'camt'],
'State GST on outward supplies' => ['sup_details', 'osup_det', 'samt'],
'Cess on outward supplies' => ['sup_details', 'osup_det', 'csamt'],
// osup_zero
'Zero rated supplies taxable value' => ['sup_details', 'osup_zero', 'txval'],
'IGST on zero rated supplies' => ['sup_details', 'osup_zero', 'iamt'],
'CGST on zero rated supplies' => ['sup_details', 'osup_zero', 'camt'],
'SGST on zero rated supplies' => ['sup_details', 'osup_zero', 'samt'],
'Cess on zero rated supplies' => ['sup_details', 'osup_zero', 'csamt'],
// osup_nil_exmp
'Nil rated or exempt supplies taxable value' => ['sup_details', 'osup_nil_exmp', 'txval'],
'IGST on nil/exempt supplies' => ['sup_details', 'osup_nil_exmp', 'iamt'],
'CGST on nil/exempt supplies' => ['sup_details', 'osup_nil_exmp', 'camt'],
'SGST on nil/exempt supplies' => ['sup_details', 'osup_nil_exmp', 'samt'],
'Cess on nil/exempt supplies' => ['sup_details', 'osup_nil_exmp', 'csamt'],
// isup_rev
'Reversed outward supplies taxable value' => ['sup_details', 'isup_rev', 'txval'],
'IGST reversed externally' => ['sup_details', 'isup_rev', 'iamt'],
'CGST reversed externally' => ['sup_details', 'isup_rev', 'camt'],
'SGST reversed externally' => ['sup_details', 'isup_rev', 'samt'],
'Cess reversed externally' => ['sup_details', 'isup_rev', 'csamt'],
// osup_nongst
'Outward supply of goods/services not liable to GST' => ['sup_details', 'osup_nongst', 'txval'],
'IGST on non-GST outward supplies (usually zero/null)' => ['sup_details', 'osup_nongst', 'iamt'],
'CGST on non-GST outward supplies' => ['sup_details', 'osup_nongst', 'camt'],
'SGST on non-GST outward supplies' => ['sup_details', 'osup_nongst', 'samt'],
'Cess on non-GST outward supplies' => ['sup_details', 'osup_nongst', 'csamt'],
// itc_elg - itc_avl is array with 'ty' keys (IMPG, ISRC, OTH, ISD, IMPS)
// We'll flatten columns for these with pattern: "ITC available on imported goods (IGST portion)" => ty IMPS? careful: by type
// So we map headers to type and subfield patterns:
'ITC available on imported goods (IGST portion)' => ['itc_elg', 'itc_avl', 'IMPG', 'iamt'],
'ITC available on imported goods (CGST portion)' => ['itc_elg', 'itc_avl', 'IMPG', 'camt'],
'ITC available on imported goods (SGST portion)' => ['itc_elg', 'itc_avl', 'IMPG', 'samt'],
'ITC available on imported goods (Cess portion)' => ['itc_elg', 'itc_avl', 'IMPG', 'csamt'],
'ITC available on inward supplies from registered taxpayers (IGST)' => ['itc_elg', 'itc_avl', 'ISRC', 'iamt'],
'ITC available on inward supplies from registered taxpayers (CGST)' => ['itc_elg', 'itc_avl', 'ISRC', 'camt'],
'ITC available on inward supplies from registered taxpayers (SGST)' => ['itc_elg', 'itc_avl', 'ISRC', 'samt'],
'ITC available on inward supplies from registered taxpayers (Cess)' => ['itc_elg', 'itc_avl', 'ISRC', 'csamt'],
'ITC available on other inputs (IGST)' => ['itc_elg', 'itc_avl', 'OTH', 'iamt'],
'ITC available on other inputs (CGST)' => ['itc_elg', 'itc_avl', 'OTH', 'camt'],
'ITC available on other inputs (SGST)' => ['itc_elg', 'itc_avl', 'OTH', 'samt'],
'ITC available on other inputs (Cess)' => ['itc_elg', 'itc_avl', 'OTH', 'csamt'],
'ITC available from Input Service Distributor (IGST)' => ['itc_elg', 'itc_avl', 'ISD', 'iamt'],
'ITC available from ISD (CGST)' => ['itc_elg', 'itc_avl', 'ISD', 'camt'],
'ITC available from ISD (SGST)' => ['itc_elg', 'itc_avl', 'ISD', 'samt'],
'ITC available from ISD (Cess)' => ['itc_elg', 'itc_avl', 'ISD', 'csamt'],
'ITC available on inward supplies from IS (IGST)' => ['itc_elg', 'itc_avl', 'IMPS', 'iamt'],
'ITC available on inward supplies from IS (CGST)' => ['itc_elg', 'itc_avl', 'IMPS', 'camt'],
'ITC available on inward supplies from IS (SGST)' => ['itc_elg', 'itc_avl', 'IMPS', 'samt'],
'ITC available on inward supplies from IS (Cess)' => ['itc_elg', 'itc_avl', 'IMPS', 'csamt'],
// Similar pattern for itc_rev ['itc_elg']['itc_rev'] types RUL, OTH etc
'ITC reversed as per rules (IGST portion)' => ['itc_elg', 'itc_rev', 'RUL', 'iamt'],
'ITC reversed as per rules (CGST)' => ['itc_elg', 'itc_rev', 'RUL', 'camt'],
'ITC reversed as per rules (SGST)' => ['itc_elg', 'itc_rev', 'RUL', 'samt'],
'ITC reversed as per rules (Cess)' => ['itc_elg', 'itc_rev', 'RUL', 'csamt'],
'ITC reversed other than rules (IGST)' => ['itc_elg', 'itc_rev', 'OTH', 'iamt'],
'ITC reversed other than rules (CGST)' => ['itc_elg', 'itc_rev', 'OTH', 'camt'],
'ITC reversed other than rules (SGST)' => ['itc_elg', 'itc_rev', 'OTH', 'samt'],
'ITC reversed other than rules (Cess)' => ['itc_elg', 'itc_rev', 'OTH', 'csamt'],
// itc_net (not an array)
'Net ITC available (IGST) after reversal' => ['itc_elg','itc_net','iamt'],
'Net ITC available (CGST) after reversal' => ['itc_elg','itc_net','camt'],
'Net ITC available (SGST) after reversal' => ['itc_elg','itc_net','samt'],
'Net ITC available (Cess) after reversal' => ['itc_elg','itc_net','csamt'],
// itc_inelg (again array with types)
'ITC ineligible as per rules (IGST)' => ['itc_elg','itc_inelg','RUL','iamt'],
'ITC ineligible as per rules (CGST)' => ['itc_elg','itc_inelg','RUL','camt'],
'ITC ineligible as per rules (SGST)' => ['itc_elg','itc_inelg','RUL','samt'],
'ITC ineligible as per rules (Cess)' => ['itc_elg','itc_inelg','RUL','csamt'],
'ITC ineligible other reasons (IGST)' => ['itc_elg','itc_inelg','OTH','iamt'],
'ITC ineligible other reasons (CGST)' => ['itc_elg','itc_inelg','OTH','camt'],
'ITC ineligible other reasons (SGST)' => ['itc_elg','itc_inelg','OTH','samt'],
'ITC ineligible other reasons (Cess)' => ['itc_elg','itc_inelg','OTH','csamt'],
// Interest and Late fee - flat nested keys
'Interest amount (IGST)' => ['intr_ltfee','intr_details','iamt'],
'Interest amount (CGST)' => ['intr_ltfee','intr_details','camt'],
'Interest amount (SGST)' => ['intr_ltfee','intr_details','samt'],
'Interest amount (Cess)' => ['intr_ltfee','intr_details','csamt'],
'Late fee (IGST)' => ['intr_ltfee','ltfee_details','iamt'],
'Late fee (CGST)' => ['intr_ltfee','ltfee_details','camt'],
'Late fee (SGST)' => ['intr_ltfee','ltfee_details','samt'],
'Late fee (Cess)' => ['intr_ltfee','ltfee_details','csamt'],
// Total tax payable etc 3 fields in tt_val
'Total tax payable' => ['tt_val','tt_pay'],
'Total cash paid' => ['tt_val','tt_csh_pd'],
'Total ITC utilized' => ['tt_val','tt_itc_pd'],
// Various qn fields
'Various internal indicators or calculated fields' => ['qn', 'q1'], // q1-q7 same header - for simplicity just show q1 here
// Not ideal to have multiple same headers — you may want to disambiguate in real sheet
// Cash balance fields grouped by tax types
// Each of igst, cgst, sgst, cess has tx, intr, pen, fee, oth
'Cash balance IGST tax' => ['taxpayble','bal','cash_bal','igst','tx'],
'Cash balance IGST interest' => ['taxpayble','bal','cash_bal','igst','intr'],
'Cash balance IGST penalty' => ['taxpayble','bal','cash_bal','igst','pen'],
'Cash balance IGST fee' => ['taxpayble','bal','cash_bal','igst','fee'],
'Cash balance IGST others' => ['taxpayble','bal','cash_bal','igst','oth'],
'Cash balance CGST tax' => ['taxpayble','bal','cash_bal','cgst','tx'],
'Cash balance CGST interest' => ['taxpayble','bal','cash_bal','cgst','intr'],
'Cash balance CGST penalty' => ['taxpayble','bal','cash_bal','cgst','pen'],
'Cash balance CGST fee' => ['taxpayble','bal','cash_bal','cgst','fee'],
'Cash balance CGST others' => ['taxpayble','bal','cash_bal','cgst','oth'],
'Cash balance SGST tax' => ['taxpayble','bal','cash_bal','sgst','tx'],
'Cash balance SGST interest' => ['taxpayble','bal','cash_bal','sgst','intr'],
'Cash balance SGST penalty' => ['taxpayble','bal','cash_bal','sgst','pen'],
'Cash balance SGST fee' => ['taxpayble','bal','cash_bal','sgst','fee'],
'Cash balance SGST others' => ['taxpayble','bal','cash_bal','sgst','oth'],
'Cash balance cess tax' => ['taxpayble','bal','cash_bal','cess','tx'],
'Cash balance cess interest' => ['taxpayble','bal','cash_bal','cess','intr'],
'Cash balance cess penalty' => ['taxpayble','bal','cash_bal','cess','pen'],
'Cash balance cess fee' => ['taxpayble','bal','cash_bal','cess','fee'],
'Cash balance cess others' => ['taxpayble','bal','cash_bal','cess','oth'],
'Total balance IGST' => ['taxpayble','bal','igst_tot_bal'],
'Total balance CGST' => ['taxpayble','bal','cgst_tot_bal'],
'Total balance SGST' => ['taxpayble','bal','sgst_tot_bal'],
'Total balance cess' => ['taxpayble','bal','cess_tot_bal'],
// ITC balances
'ITC balance IGST' => ['taxpayble','bal','itc_bal','igst_bal'],
'ITC balance CGST' => ['taxpayble','bal','itc_bal','cgst_bal'],
'ITC balance SGST' => ['taxpayble','bal','itc_bal','sgst_bal'],
'ITC balance Cess' => ['taxpayble','bal','itc_bal','cess_bal'],
'Filing status (e.g., filed, pending, rejected)' => ['taxpayble','status'],
// Tax paid fields grouped by igst, sgst, cgst, cess (only first element in tax_pay list)
'Tax paid IGST (tax)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'igst','tx'],
'Tax paid IGST (interest)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'igst','intr'],
'Tax paid IGST (penalty)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'igst','pen'],
'Tax paid IGST (fee)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'igst','fee'],
'Tax paid IGST (others)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'igst','oth'],
'Total tax paid IGST' => ['taxpayble','returnsDbCdredList','tax_pay',0,'igst','tot'],
'Tax paid SGST (tax)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'sgst','tx'],
'Tax paid SGST (interest)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'sgst','intr'],
'Tax paid SGST (penalty)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'sgst','pen'],
'Tax paid SGST (fee)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'sgst','fee'],
'Tax paid SGST (others)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'sgst','oth'],
'Total tax paid SGST' => ['taxpayble','returnsDbCdredList','tax_pay',0,'sgst','tot'],
'Tax paid CGST (tax)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'cgst','tx'],
'Tax paid CGST (interest)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'cgst','intr'],
'Tax paid CGST (penalty)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'cgst','pen'],
'Tax paid CGST (fee)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'cgst','fee'],
'Tax paid CGST (others)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'cgst','oth'],
'Total tax paid CGST' => ['taxpayble','returnsDbCdredList','tax_pay',0,'cgst','tot'],
'Tax paid Cess (tax)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'cess','tx'],
'Tax paid Cess (interest)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'cess','intr'],
'Tax paid Cess (penalty)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'cess','pen'],
'Tax paid Cess (fee)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'cess','fee'],
'Tax paid Cess (others)' => ['taxpayble','returnsDbCdredList','tax_pay',0,'cess','oth'],
'Total tax paid Cess' => ['taxpayble','returnsDbCdredList','tax_pay',0,'cess','tot'],
'Tax payment liability ID' => ['taxpayble','returnsDbCdredList','tax_pay',0,'liab_id'],
'Tax payment transaction code' => ['taxpayble','returnsDbCdredList','tax_pay',0,'trancd'],
'Tax payment transaction date' => ['taxpayble','returnsDbCdredList','tax_pay',0,'trandate'],
'Debit ledger ID from which ITC utilized to pay tax' => ['taxpayble','returnsDbCdredList','tax_paid','pd_by_itc',0,'debit_id'],
'Liability ledger ID for ITC utilization' => ['taxpayble','returnsDbCdredList','tax_paid','pd_by_itc',0,'liab_id'],
'IGST paid by utilizing IGST ITC' => ['taxpayble','returnsDbCdredList','tax_paid','pd_by_itc',0,'igst_igst_amt'],
'IGST paid by utilizing CGST ITC' => ['taxpayble','returnsDbCdredList','tax_paid','pd_by_itc',0,'igst_cgst_amt'],
'IGST paid by utilizing SGST ITC' => ['taxpayble','returnsDbCdredList','tax_paid','pd_by_itc',0,'igst_sgst_amt'],
'SGST paid by utilizing SGST ITC' => ['taxpayble','returnsDbCdredList','tax_paid','pd_by_itc',0,'sgst_sgst_amt'],
'SGST paid by utilizing IGST ITC' => ['taxpayble','returnsDbCdredList','tax_paid','pd_by_itc',0,'sgst_igst_amt'],
'CGST paid by utilizing CGST ITC' => ['taxpayble','returnsDbCdredList','tax_paid','pd_by_itc',0,'cgst_cgst_amt'],
'CGST paid by utilizing IGST ITC' => ['taxpayble','returnsDbCdredList','tax_paid','pd_by_itc',0,'cgst_igst_amt'],
'Cess paid by utilizing Cess ITC' => ['taxpayble','returnsDbCdredList','tax_paid','pd_by_itc',0,'cess_cess_amt'],
'ITC utilization transaction code' => ['taxpayble','returnsDbCdredList','tax_paid','pd_by_itc',0,'trancd'],
'ITC utilization transaction date' => ['taxpayble','returnsDbCdredList','tax_paid','pd_by_itc',0,'trandate'],
];
// Helper function to get nested array value safely
function getNestedValue($array, $path) {
foreach ($path as $key) {
if (is_array($array) && array_key_exists($key, $array)) {
$array = $array[$key];
} else {
return ''; // Default fallback if path does not exist
}
}
return $array;
}
// Write GSTINs horizontally starting from B1
$gstinList = [];
foreach ($filesData as $item) {
$gstinList[] = $item['gstin'] ?? 'Unknown GSTIN';
}
$gstinCount = count($gstinList);
for ($i = 0; $i < $gstinCount; $i++) {
$colLetter = Coordinate::stringFromColumnIndex($i + 2); // B=2, etc
$sheet->setCellValue($colLetter . '1', $gstinList[$i]);
}
// Write headers vertically in A2 downwards
$fieldCount = count($headers);
for ($r = 0; $r < $fieldCount; $r++) {
$sheet->setCellValue('A' . ($r + 2), $headers[$r]);
}
// Iterate all GSTINs and all fields to fill values
for ($c = 0; $c < $gstinCount; $c++) {
$item = $filesData[$c];
for ($r = 0; $r < $fieldCount; $r++) {
$colLetter = Coordinate::stringFromColumnIndex($c + 2);
$rowNum = $r + 2;
$header = $headers[$r];
$value = '';
if (isset($mapping[$header])) {
$path = $mapping[$header];
if (in_array('itc_avl', $path) || in_array('itc_rev', $path) || in_array('itc_inelg', $path)) {
// Special handling for array lookups by 'ty'
// path example: ['itc_elg','itc_avl','IMPG','iamt']
$base = $item;
foreach($path as $key) {
if (is_array($base) && array_key_exists($key, $base)) {
$base = $base[$key];
} else if (in_array($key, ['IMPG','ISRC','OTH','ISD','IMPS','RUL','OTH'])) {
// For ty keys (special)
if (isset($base) && is_array($base)) {
// search for array element having 'ty' == $key
$found = '';
foreach ($base as $element) {
if (isset($element['ty']) && $element['ty'] === $key) {
$found = $element;
break;
}
}
$base = $found !== '' ? $found : [];
} else {
$base = [];
}
} else {
$base = [];
break;
}
}
if (is_array($base)) {
if (in_array(end($path), ['iamt','camt','samt','csamt'])) {
$value = $base[end($path)] ?? '';
}
else $value = '';
} else {
$value = $base;
}
} else {
// Normal nested path fetch
$value = getNestedValue($item, $path);
}
}
$sheet->setCellValue($colLetter . $rowNum, $value);
}
}
// --- Styling ---
$lastColIndex = $gstinCount + 1;
$lastColLetter = Coordinate::stringFromColumnIndex($lastColIndex);
$lastRowNum = $fieldCount + 1;
$sheet->freezePane('B2'); // Freeze header row and first column
// Style header row (GSTINs)
$sheet->getStyle("B1:{$lastColLetter}1")->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '4A6FA5']],
'borders' => ['bottom' => ['borderStyle' => Border::BORDER_MEDIUM, 'color' => ['rgb' => '333333']]],
]);
// Style field names column (A)
$sheet->getStyle("A2:A{$lastRowNum}")->applyFromArray([
'font' => ['bold' => true],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_LEFT, 'vertical' => Alignment::VERTICAL_CENTER],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => 'D9E1F2']],
'borders' => ['right' => ['borderStyle' => Border::BORDER_MEDIUM, 'color' => ['rgb' => '333333']]],
]);
$sheet->getColumnDimension('A')->setWidth(50);
// GSTIN columns width and alignment
for ($c = 2; $c <= $lastColIndex; $c++) {
$colL = Coordinate::stringFromColumnIndex($c);
$sheet->getColumnDimension($colL)->setWidth(20);
$sheet->getStyle("{$colL}2:{$colL}{$lastRowNum}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
$sheet->getStyle("{$colL}2:{$colL}{$lastRowNum}")->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
}
// Borders around all cells
$sheet->getStyle("A1:{$lastColLetter}{$lastRowNum}")->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
// Alternating row fill in data rows
for ($r = 2; $r <= $lastRowNum; $r++) {
if (($r % 2) === 0) {
$sheet->getStyle("A{$r}:{$lastColLetter}{$r}")->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFF4F6FA');
}
}
// Number formatting for GSTIN data columns (everything except first column)
for ($c = 2; $c <= $lastColIndex; $c++) {
$colL = Coordinate::stringFromColumnIndex($c);
$sheet->getStyle("{$colL}2:{$colL}{$lastRowNum}")
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_NUMBER_00);
}
// Date formatting on "Tax payment transaction date" row
$dateFieldRowIndex = array_search('Tax payment transaction date', $headers);
if ($dateFieldRowIndex !== false) {
$dateRowNum = $dateFieldRowIndex + 2;
$sheet->getStyle("B{$dateRowNum}:{$lastColLetter}{$dateRowNum}")
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_DATE_DDMMYYYY);
}
// Conditional formatting - negative values red font, zero values gray fill
$conditionalRange = "B2:{$lastColLetter}{$lastRowNum}";
// Negative values red font
$negCond = new Conditional();
$negCond->setConditionType(Conditional::CONDITION_CELLIS)
->setOperatorType(Conditional::OPERATOR_LESSTHAN)
->addCondition('0');
$negCond->getStyle()->getFont()->getColor()->setARGB('FFFF0000');
// Zero values light gray fill
$zeroCond = new Conditional();
$zeroCond->setConditionType(Conditional::CONDITION_CELLIS)
->setOperatorType(Conditional::OPERATOR_EQUAL)
->addCondition('0');
$zeroCond->getStyle()->getFill()->setFillType(Fill::FILL_SOLID);
$zeroCond->getStyle()->getFill()->getStartColor()->setARGB('FFEEEEEE');
$sheet->getStyle($conditionalRange)->setConditionalStyles([$negCond, $zeroCond]);
// ----------------------------
// Add Summary Worksheet
// ----------------------------
$summarySheet = $spreadsheet->createSheet();
$summarySheet->setTitle('Summary');
// Summary headers — just some key totals for example:
$summaryHeaders = [
'GSTIN',
'Total Outward Supplies Taxable Value',
'Total Integrated Tax',
'Total Central GST',
'Total State GST',
'Total Cess',
'Total Tax Payable',
];
// Write summary headers horizontally row 1, starting A1
foreach ($summaryHeaders as $i => $sh) {
$summarySheet->setCellValue(Coordinate::stringFromColumnIndex($i+1) . '1', $sh);
}
// Write GSTIN list vertically starting A2
for ($i=0; $i < $gstinCount; $i++) {
$summarySheet->setCellValue('A' . ($i+2), $gstinList[$i]);
}
// For simplification sum from original data fields or fallback if missing
for ($i=0; $i < $gstinCount; $i++) {
$item = $filesData[$i];
// Outward supplies taxable value
$osup_txval = getNestedValue($item, ['sup_details', 'osup_det', 'txval']) + 0;
$osup_iamt = getNestedValue($item, ['sup_details', 'osup_det', 'iamt']) + 0;
$osup_camt = getNestedValue($item, ['sup_details', 'osup_det', 'camt']) + 0;
$osup_samt = getNestedValue($item, ['sup_details', 'osup_det', 'samt']) + 0;
$osup_csamt = getNestedValue($item, ['sup_details', 'osup_det', 'csamt']) + 0;
$tt_pay = getNestedValue($item, ['tt_val', 'tt_pay']) + 0;
$summarySheet->setCellValue('B' . ($i + 2), $osup_txval);
$summarySheet->setCellValue('C' . ($i + 2), $osup_iamt);
$summarySheet->setCellValue('D' . ($i + 2), $osup_camt);
$summarySheet->setCellValue('E' . ($i + 2), $osup_samt);
$summarySheet->setCellValue('F' . ($i + 2), $osup_csamt);
$summarySheet->setCellValue('G' . ($i + 2), $tt_pay);
}
// Styling summary header
$summarySheet->getStyle('A1:G1')->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '4A6FA5']],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
'borders' => ['bottom' => ['borderStyle' => Border::BORDER_THICK, 'color' => ['rgb' => '333333']]],
]);
// Column widths summary
foreach(range('A', 'G') as $columnID) {
$summarySheet->getColumnDimension($columnID)->setWidth($columnID == 'A' ? 20 : 18);
}
// Borders for summary data
$summarySheet->getStyle("A1:G" . ($gstinCount + 1))
->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
// Number format for numbers in summary
$summarySheet->getStyle("B2:G" . ($gstinCount + 1))
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_NUMBER_00);
// Freeze header row on summary sheet
$summarySheet->freezePane('A2');
// --- Output Excel ---
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="GST_Report_Horizontal_Full.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit;