<?php

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

mysqli_query($conn, "SET NAMES 'utf8'");
mysqli_query($conn, 'SET CHARACTER SET utf8');

$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];
$zroot = $_SESSION["zdir"];
$zcomp = $_SESSION["comp_" . $dbname];
$myyear = $_SESSION[$myyear];
$instid = $_SESSION["instid"];
$accstkn = $_SESSION["accstkn"];

mysqli_select_db($conn, $zdb);

$vouch = $_REQUEST['vouchno'];
$proforma = $_REQUEST['proforma'];

// =========================
// DATA FETCH (same as salegst_fin_print.php)
// =========================
$getqry = mysqli_query($conn, "SELECT *,
        DATE_FORMAT(`vouchdt`, '%d/%m/%Y') as mydt,
        DATE_FORMAT(`chaldt`,  '%d/%m/%Y') as mychaldt,
        DATE_FORMAT(`orddt`,   '%d/%m/%Y') as myorddt
     FROM `salemain`
     WHERE vouchno='$vouch'
     LIMIT 1") or die(mysqli_error($conn));
$getdata = mysqli_fetch_array($getqry);

$cmpqry = mysqli_query($conn, "SELECT * FROM $zroot.`company` WHERE `code`='$zcomp' LIMIT 1") or die(mysqli_error($conn));
$getcmpname = mysqli_fetch_array($cmpqry);

$partyqry = mysqli_query($conn, "SELECT * FROM accmast WHERE `accode`='$getdata[party]' LIMIT 1") or die(mysqli_error($conn));
$showparty = mysqli_fetch_array($partyqry);

$isIGST = ($getdata['totigst'] > 0);
$mobile = trim($showparty['mobile']);

$billNo = 'BEW ' . str_pad($getdata['invno'], 6, '0', STR_PAD_LEFT) . '/' . date('y') . '-' . (date('y') + 1);

// =========================
// GST SLAB DATA (same logic as print file)
// =========================
$slabs = [
    '5' => ['cgst' => $getdata['cgst5'], 'sgst' => $getdata['sgst5'], 'igst' => $getdata['igst5'], 'tot' => $getdata['totgst5']],
    '12' => ['cgst' => $getdata['cgst12'], 'sgst' => $getdata['sgst12'], 'igst' => $getdata['igst12'], 'tot' => $getdata['totgst12']],
    '18' => ['cgst' => $getdata['cgst18'], 'sgst' => $getdata['sgst18'], 'igst' => $getdata['igst18'], 'tot' => $getdata['totgst18']],
    '28' => ['cgst' => $getdata['cgst28'], 'sgst' => $getdata['sgst28'], 'igst' => $getdata['igst28'], 'tot' => $getdata['totgst28']],
];
$anySlabData = array_sum(array_column($slabs, 'tot')) > 0;

$gstLines = [];
if ($anySlabData) {
    foreach ($slabs as $pct => $g) {
        if ($g['tot'] <= 0)
            continue;
        $half = $pct / 2;
        if ($isIGST) {
            $gstLines[] = ['Add IGST ' . $pct . '.00 %', number_format($g['igst'], 2)];
        } else {
            $gstLines[] = ['Add CGST ' . $half . ' %', number_format($g['cgst'], 2)];
            $gstLines[] = ['Add SGST ' . $half . ' %', number_format($g['sgst'], 2)];
        }
    }
} elseif ($getdata['totcgst'] > 0 || $getdata['totsgst'] > 0 || $getdata['totigst'] > 0) {
    if ($isIGST) {
        $gstLines[] = ['Add IGST ' . $getdata['igstperc'] . ' %', number_format($getdata['totigst'], 2)];
    } else {
        $gstLines[] = ['Add CGST ' . $getdata['cgstperc'] . ' %', number_format($getdata['totcgst'], 2)];
        $gstLines[] = ['Add SGST ' . $getdata['sgstperc'] . ' %', number_format($getdata['totsgst'], 2)];
    }
}

require('library/fpdf/fpdf.php');

class PDF extends FPDF {

    function Header() {
        
    }

    function Footer() {
        
    }
}

$pdf = new PDF('P', 'mm', 'A4');
$pdf->AddPage();
$pdf->SetAutoPageBreak(true, 10);
$pdf->SetMargins(7, 7, 7);

$L = 8;
$R = 207;
$W = $R - $L; // 194

$pdf->SetDrawColor(0, 0, 0);
$pdf->SetLineWidth(0.4);

// =========================
// ROW 1: HEADER (logo / company name)
// =========================
$y = 10;
if ($proforma) {
    $logoPath = $_SERVER['DOCUMENT_ROOT'] . '/bewprof.png';
} else {
    $logoPath = $_SERVER['DOCUMENT_ROOT'] . '/bewinv.png';
}

//browse($logoPath);
//die();
if (file_exists($logoPath)) {
    $imgW = 200;
    $imgH = 45;
    $pdf->Image($logoPath, 6 + ($W - $imgW) / 2, $y, $imgW, $imgH);
    $y += $imgH + 3;
} else {
    $pdf->SetXY($L, $y);
    $pdf->SetFont('Arial', 'B', 20);
    $pdf->Cell($W, 12, $getcmpname['compname'], 0, 1, 'C');
    $y += 14;
}
$pdf->SetLineWidth(0.5);
$pdf->Line($L, $y, $R, $y);
$y += 2;

// =========================
// ROW 2: BILL REFERENCE INFO (2 columns)
// =========================
$colW = $W / 2;
$rowH = 5.5;

$leftLabels = ['Bill No.', 'Work Order No.', 'Your Challan No.', 'Our Challan No.'];
$leftValues = [$billNo, $getdata['ordno'], $getdata['gatepass'], $getdata['chalno']];
$rightLabels = ['Bill Date', 'Order Date', 'Challan Date', 'Date'];
$rightValues = [$getdata['mydt'], $getdata['myorddt'], $getdata['mychaldt'], $getdata['mydt']];

$startY2 = $y + 2;
for ($i = 0; $i < 4; $i++) {
    $yy = $startY2 + ($i * $rowH);
    $pdf->SetXY($L + 2, $yy);
    $pdf->SetFont('Arial', 'B', 9.5);
    $pdf->Cell(35, $rowH, $leftLabels[$i], 0, 0);
    $pdf->SetFont('Arial', '', 9.5);
    $pdf->Cell(60, $rowH, ': ' . $leftValues[$i], 0, 0);

    $pdf->SetXY($L + $colW + 2, $yy);
    $pdf->SetFont('Arial', 'B', 9.5);
    $pdf->Cell(35, $rowH, $rightLabels[$i], 0, 0);
    $pdf->SetFont('Arial', '', 9.5);
    $pdf->Cell(60, $rowH, ': ' . $rightValues[$i], 0, 0);
}
$y = $startY2 + (4 * $rowH) + 1;
$pdf->Line($L, $y, $R, $y);
$pdf->Line($L + $colW, $startY2 - 2, $L + $colW, $y);
$y += 2;

// =========================
// ROW 3: PARTY DETAILS
// =========================
$startY3 = $y;
$pdf->SetXY($L + 2, $startY3);
$pdf->SetFont('Arial', 'B', 11);
$pdf->Cell(0, 5, 'M/s. ' . $showparty['name'], 0, 1);

$pdf->SetFont('Arial', '', 9.5);
$addrLines = [$showparty['add1']];
if (!empty($showparty['add2']))
    $addrLines[] = $showparty['add2'];
$cityLine = $showparty['city'];
if (!empty($showparty['pin']))
    $cityLine .= ' - ' . $showparty['pin'];
if (!empty($cityLine))
    $addrLines[] = $cityLine;

$pdf->SetX($L + 2);
$pdf->MultiCell(110, 5, implode("\n", $addrLines), 0, 'L');
$afterAddrY = $pdf->GetY();

$pdf->SetXY($L + 125, $startY3 + 5);
$pdf->SetFont('Arial', '', 9.5);
$pdf->Cell(0, 5, 'GST NO. : ' . $showparty['gstno'], 0, 1);
$pdf->SetX($L + 125);
$pdf->Cell(0, 5, 'PAN NO. : ' . ($showparty['pan'] ?? ''), 0, 1);

$y = max($afterAddrY, $startY3 + 15) + 2;
$pdf->Line($L, $y, $R, $y);
$y += 2;

// =========================
// ROW 4: ITEMS TABLE
// =========================
$tblStartY = $y;
$pdf->SetXY($L, $tblStartY);

$wSr = 8;
$wDesc = 108;
$wHsn = 20;
$wQty = 15;
$wRate = 20;
$wAmt = $W - ($wSr + $wDesc + $wHsn + $wQty + $wRate);

$pdf->SetFont('Arial', 'B', 9.5);
$pdf->SetFillColor(240, 240, 240);
$pdf->Cell($wSr, 7, 'Sr.', 1, 0, 'C', true);
$pdf->Cell($wDesc, 7, 'Description', 1, 0, 'C', true);
$pdf->Cell($wHsn, 7, 'HSN/SAC', 1, 0, 'C', true);
$pdf->Cell($wQty, 7, 'Qty.', 1, 0, 'C', true);
$pdf->Cell($wRate, 7, 'Rate', 1, 0, 'C', true);
$pdf->Cell($wAmt, 7, 'Amount', 1, 1, 'C', true);

$pdf->SetX($L);
$pdf->SetFont('Arial', '', 9);

$ctr = 0;
$totqty = 0;
$rowH2 = 6;

$gettran = mysqli_query($conn, "SELECT * FROM `saletran` WHERE `vouchno`='$vouch' ORDER BY srno") or die(mysqli_error($conn));
while ($showtran = mysqli_fetch_array($gettran)) {
    $sr = '';
    if ($showtran['amount'] > 0) {
        $ctr++;
        $totqty += $showtran['qty'];
        $sr = $ctr;
    }
    $qtyDisp = ($showtran['qty'] > 0) ? number_format($showtran['qty']) : '';
    $rateDisp = ($showtran['rate'] > 0) ? number_format($showtran['rate'], 2) : '';
    $amtDisp = ($showtran['amount'] > 0) ? number_format($showtran['amount'], 2) : '';

    $pdf->SetX($L);
    $pdf->Cell($wSr, $rowH2, $sr, "R", 0, 'C');
    $pdf->Cell($wDesc, $rowH2, $showtran['descrip'], "R", 0, 'L');
    $pdf->Cell($wHsn, $rowH2, $showtran['hsncode'], "R", 0, 'C');
    $pdf->Cell($wQty, $rowH2, $qtyDisp, "R", 0, 'R');
    $pdf->Cell($wRate, $rowH2, $rateDisp, "R", 0, 'R');
    $pdf->Cell($wAmt, $rowH2, $amtDisp, "R", 1, 'R');
}
for ($i = $ctr; $i < 12; $i++) {
    $isLastRow = ($i == 11);
    $brd = $isLastRow ? 'RB' : 'R';

    $pdf->SetX($L);
    $pdf->Cell($wSr, $rowH2, '', $brd, 0, 'C');
    $pdf->Cell($wDesc, $rowH2, '', $brd, 0, 'L');
    $pdf->Cell($wHsn, $rowH2, '', $brd, 0, 'C');
    $pdf->Cell($wQty, $rowH2, '', $brd, 0, 'R');
    $pdf->Cell($wRate, $rowH2, '', $brd, 0, 'R');
    $pdf->Cell($wAmt, $rowH2, '', $brd, 1, 'R');
}

$y = $pdf->GetY() + 2;

// =========================
// ROW 5: BANK DETAILS (left) | TOTALS (right)
// =========================
$startY5 = $y;
$bankColW = $W / 2;

$bankLabels = ['Bank Name', 'Branch', 'Account No.', 'IFSC Code'];
$bankValues = [$getcmpname['bankname'], $getcmpname['branchname'], $getcmpname['acno'], $getcmpname['bankcode']];
for ($i = 0; $i < 4; $i++) {
    $pdf->SetXY($L + 2, $startY5 + ($i * 5));
    $pdf->SetFont('Arial', 'B', 9);
    $pdf->Cell(30, 5, $bankLabels[$i], 0, 0);
    $pdf->SetFont('Arial', '', 9);
    $pdf->Cell(60, 5, $bankValues[$i], 0, 0);
}
$gstInfoY = $startY5 + (4 * 5) + 2;
$pdf->SetXY($L + 2, $gstInfoY);
$pdf->Cell(0, 5, 'GST NO. : ' . $getcmpname['gst'], 0, 1);
$pdf->SetX($L + 2);
$pdf->Cell(0, 5, 'PAN NO. : ' . $getcmpname['panno'], 0, 1);
$leftEndY = $pdf->GetY();

$totX = $L + $bankColW;
$totLabelW = 38;
$totValW = $bankColW - $totLabelW - 4;
$ty = $startY5;
$rowHT = 5.5;

$pdf->SetFont('Arial', '', 9.5);
$pdf->SetXY($totX, $ty);
$pdf->Cell($totLabelW, $rowHT, 'Sub Total', 0, 0, 'L');
$pdf->Cell($totValW, $rowHT, number_format($getdata['subtotal'], 2), 0, 0, 'R');
$ty += $rowHT;

if ($getdata['lesother'] > 0) {
    
    $adv = $getdata['cdiscperc'] . " %     " . $getdata['lesother'];
    $pdf->SetXY($totX, $ty);
    $pdf->Cell($totLabelW, $rowHT, 'Advance', 0, 0, 'L');
    $pdf->Cell($totValW, $rowHT, $adv, 0, 0, 'R');
    $ty += $rowHT;
}

$pdf->SetXY($totX, $ty);
$pdf->Cell($totLabelW, $rowHT, 'Taxable Value', 0, 0, 'L');
$pdf->Cell($totValW, $rowHT, number_format($getdata['tottaxamt'] > 0 ? $getdata['tottaxamt'] : $getdata['subtotal'], 2), 0, 0, 'R');
$ty += $rowHT;

foreach ($gstLines as $line) {
    $pdf->SetXY($totX, $ty);
    $pdf->Cell($totLabelW, $rowHT, $line[0], 0, 0, 'L');
    $pdf->Cell($totValW, $rowHT, $line[1], 0, 0, 'R');
    $ty += $rowHT;
}

if ($getdata['taxdisc'] > 0) {
    $pdf->SetXY($totX, $ty);
    $pdf->Cell($totLabelW, $rowHT, 'Less Discount', 0, 0, 'L');
    $pdf->Cell($totValW, $rowHT, number_format($getdata['taxdisc'], 2), 0, 0, 'R');
    $ty += $rowHT;
}

$pdf->Line($totX, $ty + 0.5, $totX + $bankColW - 0, $ty + 0.5);
$ty += 1.5;
$pdf->SetFont('Arial', 'B', 11);
$pdf->SetXY($totX, $ty);
$pdf->Cell($totLabelW, 6, 'Bill Amount', 0, 0, 'L');
$pdf->Cell($totValW, 6, number_format($getdata['netamt'], 2), 0, 0, 'R');
$ty += 6;

$rightEndY = $ty;
$y = max($leftEndY, $rightEndY) + 2;
$pdf->Line($totX, $startY5 - 2, $totX, $y);
$pdf->Line($L, $y, $R, $y);
$y += 2;

// =========================
// ROW 6: AMOUNT IN WORDS
// =========================
$pdf->SetXY($L + 2, $y);
$pdf->SetFont('Arial', '', 9.5);
$pdf->MultiCell($W - 4, 5, 'Rupees ' . rsword(round($getdata['netamt'])) . ' Only', 0, 'L');
$y = $pdf->GetY() + 1;
$pdf->Line($L, $y, $R, $y);
$y += 2;

// =========================
// ROW 7: FOOTER
// =========================
$startY7 = $y;
$footLeftW = $W * 0.65;
$footRightW = $W - $footLeftW;

$pdf->SetXY($L + 2, $startY7);
$pdf->SetFont('Arial', 'B', 8.5);
$pdf->Cell(0, 4, 'E. & O.E.', 0, 1);
$pdf->SetX($L + 2);
$pdf->Cell(0, 4, 'Subject to Mumbai Jurisdiction', 0, 1);
$pdf->Ln(1);
$pdf->SetX($L + 2);
$pdf->SetFont('Arial', '', 7.5);
$declaration = "I/We hereby certify that my/our registration certificate under Rule 1 of GST invoice rules 2017 is in force on the date on which the sale of the goods specified in this tax invoice is made by me/us and that the transaction of sale covered by this tax invoice has been affected by me/us and it shall be accounted for in the turnover of sales while filing of return and the due tax, if any, payable on the sales has been paid or shall be paid.";
$pdf->MultiCell($footLeftW - 4, 3.6, $declaration, 0, 'L');
$leftFootEndY = $pdf->GetY();

$rightX = $L + $footLeftW;
$pdf->SetXY($rightX, $startY7);
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell($footRightW, 5, 'FOR ' . strtoupper($getcmpname['pname']), 0, 1, 'C');

$signPath = $_SERVER['DOCUMENT_ROOT'] . '/bewsign.png';
$signY = $pdf->GetY() + 1;
if (file_exists($signPath)) {
    $sw = 35;
    $sh = 16;
    $pdf->Image($signPath, $rightX + ($footRightW - $sw) / 2, $signY, $sw, $sh);
    $signY += $sh + 1;
} else {
    $signY += 18;
}
$pdf->SetXY($rightX, $signY);
$pdf->SetFont('Arial', '', 9.5);
$pdf->Cell($footRightW, 5, 'Authorised Signatory', 0, 1, 'C');
$rightFootEndY = $pdf->GetY();

$footEndY = max($leftFootEndY, $rightFootEndY) + 2;
$pdf->Line($rightX, $startY7 - 2, $rightX, $footEndY);
$pdf->Line($L, $footEndY, $R, $footEndY);

$pdf->Rect($L, 10, $W, $footEndY - 10);

ob_end_clean();

// =========================
// OUTPUT (same flow as sale_pdf.php)
// =========================
$para = $_REQUEST["para"];

$pdf->Output("GSTBILL-" . $getdata['vouchno'] . ".pdf", "I");
