<?php
// Sale Invoice PDF — modeled on saleprint_pdf.php's layout/style (aefurat
// font, company box, M/s+Voucher/Date/Godown header rows, item table,
// footer totals + signature), but rebuilt against this app's ACTUAL current
// Sale Invoice tables (`sale`/`saletr`), which don't carry the legacy
// salemain/saletran schema's item/color/transporter/marka fields. Fields
// that don't exist here (Transporter, Marka) are replaced with ones that do
// (Salesman).
//
// Previous/Current Balance: this schema doesn't have the legacy gstmain
// running-balance concept saleprint_pdf.php used, but the customer's ledger
// balance (accmast.openbal/dc + actran) is the same one every other report
// in this app (ledger, trial balance, statements) already reads from, so
// that's what drives it here — see the computation below.
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 = 'sale';
$trandb = 'saletr';

// ── Header ───────────────────────────────────────────────────────────────
$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 ─────────────────────────────────────────────────────────────
$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 (replaces saleprint_pdf.php's "Transporter" row — this schema
//    tracks Salesman on the invoice, not a transporter) ─────────────────────
$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 = [];
}

// ── Godown ───────────────────────────────────────────────────────────────
$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; }

// `sale` header stores totamt (already inclusive of packing/transport/other
// charges) but not a separate subtotal column, so it's summed here from the
// line items — same convention as $getdata['tottqty'] which IS stored.
$subtotal = 0;
foreach ($lines as $ln) { $subtotal += (float)($ln['amt'] ?? 0); }

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);
}

// ── Previous / Current Balance (customer ledger: accmast.openbal/dc + actran) ──
// "Current" is the customer's running balance as of this invoice's date —
// opening balance (sign-adjusted the same way ledger.php/trbal_fr.php do:
// dc='D' flips it negative) plus every actran posting through that date,
// which already includes this invoice's own debit. "Previous" backs that
// debit back out to get the balance immediately before this invoice. Doing
// it this way (rather than excluding this invoice's actran rows by
// source/vouchno) works the same whether the invoice posted under
// source='SL' keyed to its own vouchno (created directly here) or
// source='DSP' keyed to a sale order's vouchno (auto-generated from
// Dispatch — see includes/pendinginvoice_geninvoice.php) — either way,
// $totamt is exactly this invoice's own debit amount.
// A negative balance means the customer owes (Dr); positive means credit/advance (Cr).
$openbal    = (float)($showparty['openbal'] ?? 0);
$opendc     = $showparty['dc'] ?? '';
$openSigned = ($opendc === 'D') ? -$openbal : $openbal;

$balRes = mysqli_query($conn, "SELECT COALESCE(SUM(`amount`),0) AS bal FROM `actran`
    WHERE `accode`='" . (int)($getdata['customer'] ?? 0) . "' AND `date` <= '" . ($getdata['vouchdt'] ?? '0000-00-00') . "'AND vouchno <= '$getdata[vouchno]' ") or die(mysqli_error($conn));
$balRow      = mysqli_fetch_assoc($balRes);
$currBalance = $openSigned + (float)$balRow['bal'];
$prevBalance = $currBalance + (float)($getdata['totamt'] ?? 0);

function balfmt($v) {
    $v = (float)$v;
    return number_format(abs($v), 2) . ' ' . ($v < 0 ? 'Dr' : 'Cr');
}

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

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

$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();

$pdf->SetFont('aefurat', 'B', 20);
$pdf->Cell(190, 15, $getcmpname['pname'] ?? '', 'TRL', 0, 'C');
$pdf->Ln(15);

$pdf->SetFont('aefurat', '', 15);
$pdf->Cell(190, 8, "Sale Invoice", 'BRL', 0, 'C');
$pdf->Ln(8);

$pdf->SetFont('aefurat', 'B', 13);
$pdf->Cell(30, 6, "M/s. :", 'L', 0, 'L');
$pdf->SetFont('aefurat', '', 10);
$pdf->Cell(65, 6, $showparty['name'] ?? '', 0, 0, 'L');

$pdf->SetFont('aefurat', 'B', 13);
$pdf->Cell(30, 6, "Voucher :", 0, 0, 'L');
$pdf->SetFont('aefurat', '', 10);
$pdf->Cell(65, 6, "SAL#" . ($getdata['vouchno'] ?? ''), 'R', 0, 'L');
$pdf->Ln(6);

$pdf->SetFont('aefurat', 'B', 13);
$pdf->Cell(30, 6, "Address :", 'L', 0, 'L');
$pdf->SetFont('aefurat', '', 10);
$pdf->Cell(65, 6, trim(($showparty['add1'] ?? '') . ' ' . ($showparty['add2'] ?? '')), 0, 0, 'L');

$pdf->SetFont('aefurat', 'B', 13);
$pdf->Cell(30, 6, "Date :", 0, 0, 'L');
$pdf->SetFont('aefurat', 'B', 10);
$pdf->Cell(65, 6, $getdata['vouchdtprint'] ?? '', 'R', 0, 'L');
$pdf->Ln(6);

$pdf->SetFont('aefurat', 'B', 13);
$pdf->Cell(30, 6, "      ", 'L', 0, 'L');
$pdf->SetFont('aefurat', '', 10);
$pdf->Cell(65, 6, trim(($showparty['add3'] ?? '') . ' ' . ($showparty['city'] ?? '') . ' ' . ($showparty['pin'] ?? '')), 0, 0, 'L');
$pdf->SetFont('aefurat', 'B', 13);
$pdf->Cell(30, 6, "Salesman :", 0, 0, 'L');
$pdf->SetFont('aefurat', '', 10);
$pdf->Cell(65, 6, $showsalesm['name'] ?? '', 'R', 0, 'L');
$pdf->Ln(6);

$pdf->SetFont('aefurat', 'B', 13);
$pdf->Cell(30, 6, "Mobile. :", 'L', 0, 'L');
$pdf->SetFont('aefurat', '', 10);
$pdf->Cell(65, 6, trim(($showparty['mobile'] ?? '') . '   ' . ($showparty['mobile2'] ?? '')), 0, 0, 'L');
$pdf->SetFont('aefurat', 'B', 13);
$pdf->Cell(30, 6, "Godown :", 0, 0, 'L');
$pdf->SetFont('aefurat', '', 10);
$pdf->Cell(65, 6, $lgdw['name'] ?? '', 'R', 0, 'L');
$pdf->Ln(6);

if (trim($getdata['remarks'] ?? '') !== '') {
    $pdf->SetFont('aefurat', 'B', 13);
    $pdf->Cell(30, 6, "Remarks :", 'L', 0, 'L');
    $pdf->SetFont('aefurat', '', 10);
    $pdf->Cell(160, 6, $getdata['remarks'], 'R', 0, 'L');
    $pdf->Ln(6);
}

// ── Item table ───────────────────────────────────────────────────────────
$pdf->SetFont('aefurat', 'B', 13);
$pdf->Cell(10, 6, "Sr.", 'TLB', 0, 'C');
$pdf->Cell(80, 6, "Product", 'TLB', 0, 'C');
$pdf->Cell(30, 6, "Qty.", 'TLB', 0, 'R');
$pdf->Cell(35, 6, "Rate", 'TLRB', 0, 'R');
$pdf->Cell(35, 6, "Amount", 'TBR', 0, 'R');
$pdf->Ln(6);

$a = 0;
foreach ($lines as $ln) {
    $a++;
    $pdf->SetFont('aefurat', '', 10);
    $pdf->Cell(10, 6, (string)$a, 'BL', 0, 'C');
    $pdf->Cell(80, 6, $ln['description'] ?? '', 'LB', 0, 'L');
    $pdf->Cell(30, 6, pf2($ln['tqty'] ?? 0), 'BL', 0, 'R');
    $pdf->Cell(35, 6, pf2($ln['cost'] ?? 0), 'BLR', 0, 'R');
    $pdf->Cell(35, 6, pf2($ln['amt'] ?? 0), 'BR', 0, 'R');
    $pdf->Ln(6);
}
$newctr = 22 - $a;
for ($i = 0; $i <= $newctr; $i++) {
    $pdf->Cell(10, 6, "", 'BL', 0, 'C');
    $pdf->Cell(80, 6, "", 'LB', 0, 'C');
    $pdf->Cell(30, 6, "", 'BL', 0, 'C');
    $pdf->Cell(35, 6, "", 'BLR', 0, 'C');
    $pdf->Cell(35, 6, "", 'BR', 0, 'C');
    $pdf->Ln(6);
}

$pdf->SetFont('aefurat', 'B', 12);
$pdf->Cell(105, 6, "Subtotal", 'BL', 0, 'R');
$pdf->Cell(15, 6, pf2($getdata['tottqty'] ?? 0), 'B', 0, 'R');
$pdf->Cell(35, 6, "", 'B', 0, 'R');
$pdf->Cell(35, 6, pf2($subtotal), 'BR', 0, 'R');
$pdf->Ln(6);

if ((float)($getdata['packingcharges'] ?? 0) > 0) {
    $pdf->SetFont('aefurat', '', 12);
    $pdf->Cell(155, 6, "Packing Charges", 'BL', 0, 'R');
    $pdf->Cell(35, 6, pf2($getdata['packingcharges']), 'BR', 0, 'R');
    $pdf->Ln(6);
}

if ((float)($getdata['transport_charges'] ?? 0) > 0) {
    $pdf->SetFont('aefurat', '', 12);
    $pdf->Cell(155, 6, "Transport Charges", 'BL', 0, 'R');
    $pdf->Cell(35, 6, pf2($getdata['transport_charges']), 'BR', 0, 'R');
    $pdf->Ln(6);
}

if ((float)($getdata['other_charges'] ?? 0) > 0) {
    $pdf->SetFont('aefurat', '', 12);
    $pdf->Cell(155, 6, "Other Charges", 'BL', 0, 'R');
    $pdf->Cell(35, 6, pf2($getdata['other_charges']), 'BR', 0, 'R');
    $pdf->Ln(6);
}

$totamt = number_format((float)($getdata['totamt'] ?? 0), 2);

$pdf->SetFont('aefurat', 'B', 12);
$pdf->Cell(105, 6, "Total Amount", 'BL', 0, 'R');
$pdf->Cell(85, 6, $totamt, 'BR', 0, 'R');
$pdf->Ln(6);

$amountinwords = rsword(round((float)($getdata['totamt'] ?? 0)));
$pdf->SetFont('aefurat', '', 12);
$pdf->Cell(190, 6, "$amountinwords Only", 'BLR', 0, 'L');
$pdf->Ln(6);

$pdf->SetFont('aefurat', '', 12);
$pdf->Cell(105, 6, "Previous Balance", 'BL', 0, 'R');
$pdf->Cell(85, 6, balfmt($prevBalance), 'BR', 0, 'R');
$pdf->Ln(6);

$pdf->SetFont('aefurat', 'B', 12);
$pdf->Cell(105, 6, "Current Balance", 'BL', 0, 'R');
$pdf->Cell(85, 6, balfmt($currBalance), 'BR', 0, 'R');
$pdf->Ln(6);

$pdf->SetFont('aefurat', 'B', 12);
$pdf->Cell(190, 10, "For " . ($getcmpname['pname'] ?? ''), 0, 0, 'R');
$pdf->Ln(15);

$pdf->SetFont('aefurat', '', 8);
$pdf->Cell(190, 6, "AUTHORISED SIGNATORY", 0, 0, 'R');
$pdf->Ln(6);

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