<?php
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
require("includes/config.php");
include('includes/function.php');

ini_set("display_errors", 1);
error_reporting(E_ERROR);

$zdb     = $_SESSION["zdbyear_" . $dbname];
$compcd  = $_SESSION["comp_"    . $dbname];
$zdbroot = $_SESSION["zdbroot"] = $dbname;   // sim_root

mysqli_select_db($conn, $zdb);

$vouch = isset($_GET['vouchno']) ? (int)$_GET['vouchno'] : 0;

$maindb = 'salegst';
$trandb = 'salegsttr';

// ── Header (salegst joined with customer) ──────────────────────────────────
$getqry = mysqli_query($conn, "SELECT *, DATE_FORMAT(`vouchdt`, '%d-%m-%Y') AS vouchdtprint FROM `$maindb` WHERE `vouchno`='$vouch'") or die(mysqli_error($conn));
$getdata = mysqli_fetch_array($getqry);
if (!$getdata) {
    die("Invoice not found.");
}

// ── Company (root DB) ────────────────────────────────────────────────────
$cmpname = mysqli_query($conn, "SELECT * FROM `$zdbroot`.`company` WHERE `code`='$compcd'") or die(mysqli_error($conn));
$getcmpname = mysqli_fetch_array($cmpname);
if (!$getcmpname) $getcmpname = [];

// ── Customer (Bill To / Ship To — schema has no separate ship-to party,
//    so both blocks use the same billed customer) ──────────────────────────
$getparty = mysqli_query($conn, "SELECT * FROM `accmast` WHERE `accode`='$getdata[customer]'") or die(mysqli_error($conn));
$showparty = mysqli_fetch_array($getparty);
if (!$showparty) $showparty = [];

// ── Salesman / Godown (for the info strip under the party boxes) ───────────
$showsalesm = [];
if (!empty($getdata['salesman'])) {
    $getsalesm = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `accode`='$getdata[salesman]'") or die(mysqli_error($conn));
    $showsalesm = mysqli_fetch_array($getsalesm);
    if (!$showsalesm) $showsalesm = [];
}

$lgdw = [];
if (!empty($getdata['godown'])) {
    $findgodown = mysqli_query($conn, "SELECT `code`,`name` FROM `godown` WHERE `code`='$getdata[godown]'") or die(mysqli_error($conn));
    $lgdw = mysqli_fetch_array($findgodown);
    if (!$lgdw) $lgdw = [];
}

// ── Line items ───────────────────────────────────────────────────────────
$lines = [];
$gettran = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE `vouchno`='$vouch' ORDER BY `srl`") or die(mysqli_error($conn));
while ($r = mysqli_fetch_array($gettran)) { $lines[] = $r; }

// Display-time fallback: invoices saved before the CGST/SGST/IGST columns
// existed have them at 0 even though gstamt is populated. If a line's split
// is all-zero but it does carry GST, derive the split here on the fly (same
// rule as the live entry save path — customer statecode blank, or company
// GSTIN unknown, both default to intrastate CGST+SGST, never IGST).
$companyStateCodePdf = trim($getcmpname['statecode'] ?? '');
if ($companyStateCodePdf === '') {
    $companyStateCodePdf = substr(trim($getcmpname['gstno'] ?? ''), 0, 2);
}
$customerStateCodePdf = trim($showparty['statecode'] ?? '');
$isInterstatePdf = ($companyStateCodePdf !== '' && $customerStateCodePdf !== '' && $companyStateCodePdf !== $customerStateCodePdf);
foreach ($lines as $k => $ln) {
    $gstamt = (float)($ln['gstamt'] ?? 0);
    $hasSplit = ((float)($ln['cgstamt'] ?? 0)) > 0 || ((float)($ln['sgstamt'] ?? 0)) > 0 || ((float)($ln['igstamt'] ?? 0)) > 0;
    if ($gstamt > 0 && !$hasSplit) {
        if ($isInterstatePdf) {
            $lines[$k]['cgstamt'] = 0; $lines[$k]['sgstamt'] = 0; $lines[$k]['igstamt'] = $gstamt;
        } else {
            $c = round($gstamt / 2, 2);
            $lines[$k]['cgstamt'] = $c; $lines[$k]['sgstamt'] = round($gstamt - $c, 2); $lines[$k]['igstamt'] = 0;
        }
    }
}

// GST rate-wise breakup (grouped by gstpercent), same logic as salegst_print.php.
$gstBreakup = [];
foreach ($lines as $ln) {
    $rate = (float)($ln['gstpercent'] ?? 0);
    $key  = number_format($rate, 2, '.', '');
    if (!isset($gstBreakup[$key])) $gstBreakup[$key] = ['rate' => $rate, 'taxable' => 0, 'gst' => 0, 'cgst' => 0, 'sgst' => 0, 'igst' => 0];
    $gstBreakup[$key]['taxable'] += (float)($ln['amt'] ?? 0) - (float)($ln['discamt'] ?? 0);
    $gstBreakup[$key]['gst']     += (float)($ln['gstamt'] ?? 0);
    $gstBreakup[$key]['cgst']    += (float)($ln['cgstamt'] ?? 0);
    $gstBreakup[$key]['sgst']    += (float)($ln['sgstamt'] ?? 0);
    $gstBreakup[$key]['igst']    += (float)($ln['igstamt'] ?? 0);
}
ksort($gstBreakup, SORT_NUMERIC);

// Header totals used in the Payment Details totals row may also be stale 0s
// on old invoices — prefer the freshly-summed breakup totals whenever the
// stored header total disagrees with them (i.e. wasn't backfilled yet).
$sumCgstPdf = array_sum(array_column($gstBreakup, 'cgst'));
$sumSgstPdf = array_sum(array_column($gstBreakup, 'sgst'));
$sumIgstPdf = array_sum(array_column($gstBreakup, 'igst'));
if (((float)($getdata['totcgst'] ?? 0)) == 0 && ((float)($getdata['totsgst'] ?? 0)) == 0 && ((float)($getdata['totigst'] ?? 0)) == 0 && ($sumCgstPdf > 0 || $sumSgstPdf > 0 || $sumIgstPdf > 0)) {
    $getdata['totcgst'] = $sumCgstPdf;
    $getdata['totsgst'] = $sumSgstPdf;
    $getdata['totigst'] = $sumIgstPdf;
}

// ── Company display name (Trade Name if set, else legal Company Name) ──────
$compDisplayName = trim($getcmpname['tradename'] ?? '') !== '' ? $getcmpname['tradename'] : ($getcmpname['name'] ?? '');

// ── GST-specific Bank Details / Address (Company Setup → GST Details tab) —
//    each field falls back to the General tab's value when left blank. ─────
function gstf($get, $gstKey, $genKey) {
    $v = trim($get[$gstKey] ?? '');
    return $v !== '' ? $v : ($get[$genKey] ?? '');
}
$pdfAddress  = gstf($getcmpname, 'gst_address',  'address');
$pdfCity     = gstf($getcmpname, 'gst_city',     'city');
$pdfPincode  = gstf($getcmpname, 'gst_pincode',  'pincode');
$pdfCountry  = gstf($getcmpname, 'gst_country',  'country');
$pdfBankname   = gstf($getcmpname, 'gst_bankname',   'bankname');
$pdfBranchname = gstf($getcmpname, 'gst_branchname', 'branchname');
$pdfAccountno  = gstf($getcmpname, 'gst_accountno',  'accountno');
$pdfIfsccode   = gstf($getcmpname, 'gst_ifsccode',   'ifsccode');
$pdfTelephone  = gstf($getcmpname, 'gst_telephone',  'telephone');

function pf2($v) {
    if ($v === null || $v === '') return '';
    $v = (float)$v;
    if ($v == 0) return '';
    return ($v == (int)$v) ? number_format($v, 0) : number_format($v, 2);
}

require_once("library/TCPDF/tcpdf.php");

$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);

$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(10, 10, 10);
$pdf->SetAutoPageBreak(true, 10);

$pdf->AddPage();

$pdf->SetDrawColor(0, 0, 0);
$pdf->SetFillColor(255, 255, 255);

$pdf->Rect(10, 15, 190, 27, 'DF');

$pdf->SetFont('freeserif', 'B', 12);
$pdf->Cell(190, -12, "Tax Invoice", 0, 0, 'C');
$pdf->Ln();

$pdf->SetFont('freeserif', 'B', 20);
$pdf->Cell(190, 2, $compDisplayName, 'B', 0, 'C');
$pdf->Ln();

$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(190, 2, $pdfAddress, 0, 0, 'C');
$pdf->Ln();

$pdf->SetFont('freeserif', '', 10);
$cityline = trim($pdfCity . ' ' . $pdfPincode . ' ' . $pdfCountry);
$pdf->Cell(190, 2, $cityline, 0, 0, 'C');
$pdf->Ln();

$pdf->SetFont('freeserif', '', 10);
$mobileLine = "Mobile No.:- " . $pdfTelephone;
if (!empty($getcmpname['email'])) {
    $mobileLine .= "   |   Email: " . $getcmpname['email'];
}
$pdf->Cell(190, 2, $mobileLine, 0, 0, 'C');
$pdf->Ln();

$pdf->SetFont('freeserif', '', 10);
$stateLine = "State : " . ($getcmpname['state'] ?? '') . "   Code : " . $companyStateCodePdf;
if (!empty($getcmpname['cin'])) {
    $stateLine .= "   |   CIN : " . $getcmpname['cin'];
}
$pdf->Cell(190, 2, $stateLine, 0, 0, 'C');
$pdf->Ln();

$pdf->SetFont('freeserif', 'B', 10);
$pdf->Cell(95, 6, "GST NO. : " . ($getcmpname['gstno'] ?? ''), 'LB', 0, 'C');
$pdf->Cell(95, 6, "PAN NO. : " . ($getcmpname['panno'] ?? ''), 'RB', 0, 'C');
$pdf->Ln();

$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(8, 5, "", 'L', 0, 'C');
$pdf->Cell(4, 5, "Invoice No. :", 0, 0, 'C');
$pdf->SetFont('freeserif', 'B', 10);
$pdf->Cell(26, 5, "GST#" . $getdata["vouchno"], 0, 0, 'C');
$pdf->Cell(52, 5, " ", 0, 0, 'C');
$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(20, 5, "Invoice Date :", 0, 0, 'C');
$pdf->SetFont('freeserif', 'B', 10);
$pdf->Cell(20, 5, $getdata['vouchdtprint'], 0, 0, 'C');
$pdf->Cell(60, 5, "", 'R', 0, 'C');
$pdf->Ln();

$pdf->SetFont('freeserif', 'B', 10);
$pdf->Cell(90, 5, "Bill To Party", 1, 0, 'C');
$pdf->Cell(1, 6, "", 0, 0, 'L');
$pdf->Cell(99, 5, "Ship To Party", 1, 0, 'C');
$pdf->Ln(6);

// Schema has no separate ship-to fields on `salegst`, so both blocks show
// the same billed customer from `accmast`.
$printname   = $showparty['name']   ?? '';
$printmobile = $showparty['mobile'] ?? '';

$pdf->SetFont('freeserif', 'B', 10);
$pdf->Cell(14, 4, "M/s. ", 'LT', 0, 'L');
$pdf->Cell(2, 4, ":", 'T', 0, 'L');
$pdf->Cell(74, 4, $printname, 'TR', 0, 'L');
$pdf->Cell(1, 4, "", 'R', 0, 'L');
$pdf->Cell(14, 4, "M/s.", 'TL', 0, 'L');
$pdf->Cell(2, 4, ":", 'T', 0, 'L');
$pdf->Cell(83, 4, $printname, 'TR', 0, 'L');
$pdf->Ln(4);

$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(14, 4, "Address", 'L', 0, 'L');
$pdf->Cell(2, 4, ":", '0', 0, 'L');
$pdf->SetFont('freeserif', '', 9);
$pdf->Cell(74, 4, $showparty['add1'] ?? '', 'R', 0, 'L');
$pdf->Cell(1, 4, "", 'R', 0, 'L');
$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(14, 4, "Address", 0, 0, 'L');
$pdf->Cell(2, 4, ":", 0, 0, 'L');
$pdf->SetFont('freeserif', '', 9);
$pdf->Cell(83, 4, $showparty['add1'] ?? '', 'R', 0, 'L');
$pdf->Ln(4);

$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(16, 4, "", 'L', 0, 'L');
$pdf->SetFont('freeserif', '', 9);
$pdf->Cell(74, 4, $showparty['add2'] ?? '', 'R', 0, 'L');
$pdf->Cell(1, 4, "", 'R', 0, 'L');
$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(16, 4, "", 0, 0, 'L');
$pdf->SetFont('freeserif', '', 9);
$pdf->Cell(83, 4, $showparty['add2'] ?? '', 'R', 0, 'L');
$pdf->Ln(4);

$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(16, 4, "", 'L', 0, 'L');
$pdf->SetFont('freeserif', '', 9);
$addr3line = trim(($showparty['add3'] ?? '') . ' ' . ($showparty['city'] ?? '') . ' ' . ($showparty['pin'] ?? ''));
$pdf->Cell(74, 4, $addr3line, 'R', 0, 'L');
$pdf->Cell(1, 4, "", 'R', 0, 'L');
$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(16, 4, "", 0, 0, 'L');
$pdf->SetFont('freeserif', '', 9);
$pdf->Cell(83, 4, $addr3line, 'R', 0, 'L');
$pdf->Ln(4);

$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(14, 4, "Mobile", 'L', 0, 'L');
$pdf->Cell(2, 4, ":", '0', 0, 'L');
$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(74, 4, $printmobile, 'R', 0, 'L');
$pdf->Cell(1, 4, "", 'R', 0, 'L');
$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(14, 4, "Mobile", 'L', 0, 'L');
$pdf->Cell(2, 4, ":", '0', 0, 'L');
$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(83, 4, $printmobile, 'R', 0, 'L');
$pdf->Ln(4);

$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(14, 4, "GST No.", 'L', 0, 'L');
$pdf->Cell(2, 4, ":", '0', 0, 'L');
$pdf->SetFont('freeserif', 'B', 9);
$pdf->Cell(74, 4, $showparty['gstno'] ?? '', 'R', 0, 'L');
$pdf->Cell(1, 4, "", 'R', 0, 'L');
$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(14, 4, "GST No.", 'L', 0, 'L');
$pdf->Cell(2, 4, ":", '0', 0, 'L');
$pdf->SetFont('freeserif', 'B', 9);
$pdf->Cell(83, 4, $showparty['gstno'] ?? '', 'R', 0, 'L');
$pdf->Ln(4);

$pdf->SetFont('freeserif', 'B', 10);
$pdf->Cell(14, 4, "State", 'LB', 0, 'L');
$pdf->Cell(2, 4, ":", 'B', 0, 'L');
$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(34, 4, $showparty['state'] ?? '', 'B', 0, 'L');
$pdf->Cell(40, 4, "Code : " . ($showparty['statecode'] ?? ''), 'RB', 0, 'L');
$pdf->Cell(1, 4, "", 'R', 0, 'L');
$pdf->SetFont('freeserif', 'B', 10);
$pdf->Cell(14, 4, "State", 'LB', 0, 'L');
$pdf->Cell(2, 4, ":", 'B', 0, 'L');
$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(34, 4, $showparty['state'] ?? '', 'B', 0, 'L');
$pdf->Cell(49, 4, "Code : " . ($showparty['statecode'] ?? ''), 'RB', 0, 'L');
$pdf->Ln(4);

// Godown / Salesman / Remarks strip (replaces the old LR/Transport row —
// `salegst` doesn't track LR/transporter/payment-mode fields).
$pdf->SetFont('freeserif', 'B', 10);
$pdf->Cell(19, 5, "Godown:", 'L', 0, 'L');
$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(71, 5, $lgdw['name'] ?? '', '', 0, 'L');
$pdf->Cell(1, 5, "", 0, 0, 'L');
$pdf->SetFont('freeserif', 'B', 10);
$pdf->Cell(19, 5, "Salesman:", '', 0, 'L');
$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(80, 5, $showsalesm['name'] ?? '', 'R', 0, 'L');
$pdf->Ln(5);

$pdf->SetFont('freeserif', 'B', 10);
$pdf->Cell(19, 5, "Remarks:", 'LB', 0, 'L');
$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(171, 5, $getdata['remarks'] ?? '', 'RB', 0, 'L');
$pdf->Ln(5);

// ── Item table ───────────────────────────────────────────────────────────
$pdf->SetFont('freeserif', 'B', 10);
$pdf->Cell(8, 5, "Sr.", 'BLT', 0, 'C');
$pdf->Cell(74, 5, "Product", 'LBT', 0, 'C');
$pdf->Cell(20, 5, "HSN Code", 'BLRT', 0, 'C');
$pdf->Cell(15, 5, "GST%", 'BRT', 0, 'R');
$pdf->Cell(18, 5, "Qty.", 'BRT', 0, 'R');
$pdf->Cell(25, 5, "Rate", 'BRT', 0, 'R');
$pdf->Cell(30, 5, "Amount", 'BRT', 0, 'R');
$pdf->Ln(5);

$ctr = 0;
$totqty = 0;
foreach ($lines as $showtran) {
    $ctr++;
    $totqty = $totqty + (float)$showtran['tqty'];

    $pdf->SetFont('freeserif', '', 10);
    $pdf->Cell(8, 6, (string)$ctr, 'BLT', 0, 'C');
    $pdf->Cell(74, 6, $showtran['description'], 'LBT', 0, 'L');
    $pdf->Cell(20, 6, $showtran['hsncode'] ?? '', 'BLRT', 0, 'C');
    $pdf->Cell(15, 6, pf2($showtran['gstpercent']), 'BRT', 0, 'R');
    $pdf->Cell(18, 6, pf2($showtran['tqty']), 'BRT', 0, 'R');
    $pdf->Cell(25, 6, pf2($showtran['cost']), 'BRT', 0, 'R');
    $pdf->Cell(30, 6, pf2($showtran['amt']), 'BRT', 0, 'R');
    $pdf->Ln();
}

// Pad the table out to a minimum of 10 rows so short invoices don't look bare.
$newctr = 10 - $ctr;
for ($i = 1; $i <= $newctr; $i++) {
    $pdf->Cell(8, 6, "", 'BLT', 0, 'C');
    $pdf->Cell(74, 6, "", 'LBT', 0, 'C');
    $pdf->Cell(20, 6, "", 'BLRT', 0, 'C');
    $pdf->Cell(15, 6, "", 'BRT', 0, 'R');
    $pdf->Cell(18, 6, "", 'BRT', 0, 'R');
    $pdf->Cell(25, 6, "", 'BRT', 0, 'R');
    $pdf->Cell(30, 6, "", 'BRT', 0, 'R');
    $pdf->Ln();
}

$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(117, 5, "Total", 'BL', 0, 'R');
$pdf->Cell(18, 5, pf2($totqty), 'B', 0, 'R');
$pdf->Cell(55, 5, pf2($getdata['subtotal']), 'BR', 0, 'R');
$pdf->Ln();

if ((float)$getdata['totdiscamt'] > 0) {
    $pdf->SetFont('freeserif', '', 10);
    $pdf->Cell(135, 5, " Less Item Discount", 'BLR', 0, 'R');
    $pdf->Cell(55, 5, pf2($getdata['totdiscamt']), 'BR', 0, 'R');
    $pdf->Ln();
}

if ((float)$getdata['packingcharges'] > 0) {
    $pdf->SetFont('freeserif', '', 10);
    $pdf->Cell(135, 5, " Packing Charges", 'BLR', 0, 'R');
    $pdf->Cell(55, 5, pf2($getdata['packingcharges']), 'BR', 0, 'R');
    $pdf->Ln();
}

if ((float)$getdata['transport_charges'] > 0) {
    $pdf->SetFont('freeserif', '', 10);
    $pdf->Cell(135, 5, " Transport Charges", 'BLR', 0, 'R');
    $pdf->Cell(55, 5, pf2($getdata['transport_charges']), 'BR', 0, 'R');
    $pdf->Ln();
}

if ((float)$getdata['other_charges'] > 0) {
    $pdf->SetFont('freeserif', '', 10);
    $pdf->Cell(135, 5, " Other Charges", 'BLR', 0, 'R');
    $pdf->Cell(55, 5, pf2($getdata['other_charges']), 'BR', 0, 'R');
    $pdf->Ln();
}

// ── GST rate-wise breakup + bank details block ──────────────────────────
// Right side laid out like the Tax Invoice PDF's Payment Details block —
// a fully bordered grid with Taxable Amt./CGST/SGST/IGST columns per rate
// slab. CGST+SGST apply on intrastate sales, IGST on interstate — only one
// side is ever non-zero per invoice (see $isInterstatePdf, derived from the
// values saved at entry time in salegst.php).
// Payment Details (left) shrunk to make room for a wider breakup grid on the
// right — Taxable Amt. and Total GST carry the longest numbers, so they get
// the most space; % stays compact since it's only ever 1-2 digits.
$h = 4;
$wL = 21;        // left label
$wV = 80;        // left value
$wGap = 1;       // separator gap
$wTaxable = 24;
$wRate = 10;
$wCgst = 15;
$wSgst = 15;
$wIgst = 13;
$wGst = 18;      // Total GST (CGST+SGST or IGST, whichever applies)

$bankLabels = [
    ['Bank Name', $pdfBankname],
    ['Branch',    $pdfBranchname],
    ['A/c No.',   $pdfAccountno],
    ['IFSC Code', $pdfIfsccode],
];
$breakupRows = array_values($gstBreakup);

$pdf->SetFont('freeserif', 'B', 9);
$pdf->Cell($wL + ($wV - 7) + $wGap, $h, "Payment Details", 1, 0, 'C');
$pdf->Cell($wTaxable, $h, "Taxable Amt.", 1, 0, 'R');
$pdf->Cell($wRate, $h, "%", 1, 0, 'R');
$pdf->Cell($wCgst, $h, "CGST", 1, 0, 'R');
$pdf->Cell($wSgst, $h, "SGST", 1, 0, 'R');
$pdf->Cell($wIgst, $h, "IGST", 1, 0, 'R');
$pdf->Cell($wGst, $h, "Total GST", 1, 0, 'R');
$pdf->Ln();

for ($bi = 0; $bi < 4; $bi++) {
    $pdf->SetFont('freeserif', 'B', 9);
    $pdf->Cell($wL, $h, $bankLabels[$bi][0], 1, 0, 'L');
    $pdf->SetFont('freeserif', '', 9);
    $pdf->Cell($wV - 7 + $wGap, $h, $bankLabels[$bi][1], 1, 0, 'L');
    // $pdf->Cell($wGap, $h, '', "", 0);

    if (isset($breakupRows[$bi])) {
        $bk = $breakupRows[$bi];
        $pdf->Cell($wTaxable, $h, pf2($bk['taxable']), 1, 0, 'R');
        $pdf->Cell($wRate, $h, rtrim(rtrim(number_format($bk['rate'], 2), '0'), '.') . '%', 1, 0, 'R');
        $pdf->Cell($wCgst, $h, pf2($bk['cgst']), 1, 0, 'R');
        $pdf->Cell($wSgst, $h, pf2($bk['sgst']), 1, 0, 'R');
        $pdf->Cell($wIgst, $h, pf2($bk['igst']), 1, 0, 'R');
        $pdf->Cell($wGst, $h, pf2($bk['gst']), 1, 0, 'R');
    } else {
        $pdf->Cell($wTaxable, $h, '', 1, 0, 'R');
        $pdf->Cell($wRate, $h, '', 1, 0, 'R');
        $pdf->Cell($wCgst, $h, '', 1, 0, 'R');
        $pdf->Cell($wSgst, $h, '', 1, 0, 'R');
        $pdf->Cell($wIgst, $h, '', 1, 0, 'R');
        $pdf->Cell($wGst, $h, '', 1, 0, 'R');
    }
    $pdf->Ln();
}

$pdf->SetFont('freeserif', 'B', 9);
$pdf->Cell($wL  + ($wV - 7) + $wGap, $h, "", 1, 0);
$pdf->Cell($wTaxable, $h, pf2($getdata['taxableamt']), 1, 0, 'R');
$pdf->Cell($wRate, $h, "Total", 1, 0, 'R');
$pdf->Cell($wCgst, $h, pf2($getdata['totcgst']), 1, 0, 'R');
$pdf->Cell($wSgst, $h, pf2($getdata['totsgst']), 1, 0, 'R');
$pdf->Cell($wIgst, $h, pf2($getdata['totigst']), 1, 0, 'R');
$pdf->Cell($wGst, $h, pf2($getdata['totgstamt']), 1, 0, 'R');
$pdf->Ln();

// Any remaining GST slabs (more than 4 distinct rates on one invoice) get
// their own extra rows so nothing is silently dropped.
if (count($breakupRows) > 4) {
    for ($bi = 4; $bi < count($breakupRows); $bi++) {
        $bk = $breakupRows[$bi];
        $pdf->Cell($wL + ($wV - 7) + $wGap, $h, "", 1, 0);
        $pdf->Cell($wTaxable, $h, pf2($bk['taxable']), 1, 0, 'R');
        $pdf->Cell($wRate, $h, rtrim(rtrim(number_format($bk['rate'], 2), '0'), '.') . '%', 1, 0, 'R');
        $pdf->Cell($wCgst, $h, pf2($bk['cgst']), 1, 0, 'R');
        $pdf->Cell($wSgst, $h, pf2($bk['sgst']), 1, 0, 'R');
        $pdf->Cell($wIgst, $h, pf2($bk['igst']), 1, 0, 'R');
        $pdf->Cell($wGst, $h, pf2($bk['gst']), 1, 0, 'R');
        $pdf->Ln();
    }
}

$pdf->Ln(1);

$wTotal = 190;
$h = 5;

$pdf->SetFont('freeserif', 'B', 10);
$pdf->Cell(150, $h, "Bill Amount", 'TBL', 0, 'R');
$pdf->Cell(40, $h, number_format((float)$getdata['totamt'], 2), 'TBR', 0, 'R');
$pdf->Ln();

$amountinwords = rsword(round((float)$getdata['totamt']));

$pdf->SetFont('freeserif', '', 10);
$pdf->Cell(190, $h, "Amount In Words: " . $amountinwords, 'BLR', 0, 'L');
$pdf->Ln();

$wDecl = 110;   // Declaration
$wRecv = 30;    // Receiver
$wAuth = 50;    // Authorised
$h = 4;         // row height

$pdf->SetFont('freeserif', 'B', 10);

$pdf->Cell($wDecl, $h, "DECLARATION:", 'LRT', 0, 'L');
$pdf->Cell($wRecv, $h, "", 'RT', 0);
$pdf->Cell($wAuth, $h, "For " . $compDisplayName, 'RT', 0, 'C');
$pdf->Ln();

$pdf->SetFont('freeserif', '', 9);
$pdf->Cell($wDecl, $h, "1) We declare that this invoice shows the actual price of the goods", 'LR', 0);
$pdf->Cell($wRecv, $h, "", 'R', 0);
$pdf->Cell($wAuth, $h, "", 'R', 0);
$pdf->Ln();

$pdf->Cell($wDecl, $h, "described and that all particulars are true and correct.", 'LR', 0);
$pdf->Cell($wRecv, $h, "", 'R', 0);
$pdf->Cell($wAuth, $h, "", 'R', 0);
$pdf->Ln();

$pdf->Cell($wDecl, $h, "2) Goods once sold will not be taken back or replaced.", 'LR', 0);
$pdf->Cell($wRecv, $h, "", 'R', 0);
$pdf->Cell($wAuth, $h, "", 'R', 0);
$pdf->Ln();

$pdf->Cell($wDecl, $h, "3) We are not responsible for damage or loss in transport.", 'LR', 0);
$pdf->Cell($wRecv, $h, "", 'R', 0);
$pdf->Cell($wAuth, $h, "", 'R', 0);
$pdf->Ln();

$h = 6;
$pdf->Cell($wDecl, $h, "4) Over Due Balance Will Be Charged 24% Interest P.A.", 'LRB', 0);
$pdf->Cell($wRecv, $h, "Receiver's Signature", 'RB', 0, 'C');
$pdf->Cell($wAuth, $h, "Authorised Signatory", 'RB', 0, 'C');
$pdf->Ln();

$pdf->SetFont('freeserif', '', 11);
$pdf->Cell(190, 7, "Subject to Jurisdiction", 'LRB', 0, 'L');
$pdf->Ln(5);

if (ob_get_level() > 0) { ob_end_clean(); }
$pdf->Output("Sale GST Invoice-" . $getdata['vouchno'] . ".pdf", "I");
