<?php
// Sale Invoice PDF — modeled on saleprint_pdf.php's layout/style (helvetica
// 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). The Previous Balance / Advance / Total Balance section from
// saleprint_pdf.php is intentionally NOT included — this schema has no
// actran/gstmain running-balance concept tied to a plain Sale Invoice.
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 = 'saleorder';
$trandb = 'saleorderdtl';

// ── Mainpart 
$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 = [];
}

// ── Tranpart items 
$lines = [];
$gettran = mysqli_query($conn, "SELECT a.*,b.name as prodname FROM `$trandb` a 
                                       LEFT JOIN `product` b ON a.product = b.id
                                       WHERE a.`vouchno`='$vouch' ORDER BY a.`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);
}

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->Cell(190, 15, $getcmpname['name'] ?? '', 'TRL', 0, 'C');
// $pdf->Ln(15);

// $pdf->SetFont('helvetica', '', 15);
$pdf->SetFont('helvetica', 'B', 20);
$pdf->Cell(190, 8, "Order", 'TRL', 0, 'C');
$pdf->Ln(8);

$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(18, 6, "M/s.", 'TL', 0, 'L');
$pdf->Cell(2, 6, ":", 'T', 0, 'L');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(100, 6, $showparty['name'] ?? '', "T", 0, 'L');

$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(20, 6, "Voucher", "T", 0, 'R');
$pdf->Cell(2, 6, ":", 'T', 0, 'L');
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(48, 6, "SAL#" . ($getdata['vouchno'] ?? ''), 'TR', 0, 'L');
$pdf->Ln(6);

$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(18, 6, "Address", 'L', 0, 'L');
$pdf->Cell(2, 6, ":", '', 0, 'L');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(100, 6, trim(($showparty['add1'] ?? '') . ' ' . ($showparty['add2'] ?? '')), 0, 0, 'L');

$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(20, 6, "Date", '', 0, 'R');
$pdf->Cell(2, 6, ":", '', 0, 'L');
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(48, 6, $getdata['vouchdtprint'] ?? '', 'R', 0, 'L');
$pdf->Ln(6);

$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(18, 6, "", 'L', 0, 'L');
$pdf->Cell(2, 6, "", '', 0, 'L');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(100, 6, trim(($showparty['add3'] ?? '') . ' ' . ($showparty['city'] ?? '') . ' ' . ($showparty['pin'] ?? '')), 0, 0, 'L');
$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(20, 6, "Salesman", 0, 0, 'R');
$pdf->Cell(2, 6, ":", '', 0, 'L');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(48, 6, $showsalesm['name'] ?? '', 'R', 0, 'L');
$pdf->Ln(6);

$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(18, 6, "Mobile.", 'L', 0, 'L');
$pdf->Cell(2, 6, ":", '', 0, 'L');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(100, 6, trim(($showparty['mobile'] ?? '') . '   ' . ($showparty['mobile2'] ?? '')), 0, 0, 'L');
$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(20, 6, "Godown", 0, 0, 'L');
$pdf->Cell(2, 6, ":", '', 0, 'L');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(48, 6, $lgdw['name'] ?? '', 'R', 0, 'L');
$pdf->Ln(6);

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

// ── Item table ───────────────────────────────────────────────────────────
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(15, 6, "Sr.", 'TLB', 0, 'C');
$pdf->Cell(100, 6, "Product", 'TLB', 0, 'C');
$pdf->Cell(20, 6, "Qty.", 'TLB', 0, 'R');
$pdf->Cell(25, 6, "Rate", 'TLRB', 0, 'R');
$pdf->Cell(30, 6, "Amount", 'TBR', 0, 'R');
$pdf->Ln(6);

$a = 0;
foreach ($lines as $ln) {
    $a++;
    $pdf->SetFont('helvetica', '', 10);
    $pdf->Cell(15, 6, (string)$a, 'BL', 0, 'C');
    $pdf->Cell(100, 6, $ln['prodname'] ?? '', 'LB', 0, 'L');
    $pdf->Cell(20, 6, pf2($ln['qty'] ?? 0), 'BL', 0, 'R');
    $pdf->Cell(25, 6, pf2($ln['cost'] ?? 0), 'BLR', 0, 'R');
    $pdf->Cell(30, 6, pf2($ln['amount'] ?? 0), 'BR', 0, 'R');
    $pdf->Ln(6);

    $totqty +=  $ln['qty'];
    $totamt +=  $ln['amount'];
}

$newctr = 20 - $a;
for ($i = 0; $i <= $newctr; $i++) {
    $pdf->Cell(15, 6, "", 'BL', 0, 'C');
    $pdf->Cell(100, 6, "", 'LB', 0, 'C');
    $pdf->Cell(20, 6, "", 'BL', 0, 'C');
    $pdf->Cell(25, 6, "", 'BLR', 0, 'C');
    $pdf->Cell(30, 6, "", 'BR', 0, 'C');
    $pdf->Ln(6);
}

$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(115, 6, "Subtotal", 'BL', 0, 'R');
$pdf->Cell(20, 6, pf2($totqty ?? 0), 'B', 0, 'R');
$pdf->Cell(25, 6, "", 'B', 0, 'R');
$pdf->Cell(30, 6, pf2($totamt), 'BR', 0, 'R');
$pdf->Ln(6);

// if ((float)($getdata['packingcharges'] ?? 0) > 0) {
    $pdf->SetFont('helvetica', '', 12);
    $pdf->Cell(115, 6, "Narration :", 'BL', 0, 'L');
    $pdf->Cell(45, 6, "Packing Charges", 'BLR', 0, 'R');
    $pdf->Cell(30, 6, pf2($getdata['packingcharges']), 'BR', 0, 'R');
    $pdf->Ln(6);
// }

// if ((float)($getdata['transport_charges'] ?? 0) > 0) {
    $pdf->SetFont('helvetica', '', 12);
    $pdf->Cell(115, 6, "$getdata[remarks]", 'BL', 0, 'L');
    $pdf->Cell(45, 6, "Transport Charges", 'BLR', 0, 'R');
    $pdf->Cell(30, 6, pf2($getdata['transport_charges']), 'BR', 0, 'R');
    $pdf->Ln(6);
// }

if ((float)($getdata['other_charges'] ?? 0) > 0) {
    $pdf->SetFont('helvetica', '', 12);
    $pdf->Cell(115, 6, "", 'BL', 0, 'R');
    $pdf->Cell(45, 6, "Other Charges", 'BLR', 0, 'R');
    $pdf->Cell(30, 6, pf2($getdata['other_charges']), 'BR', 0, 'R');
    $pdf->Ln(6);
}

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

$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(115, 6, "Net Amount", 'BL', 0, 'R');
$pdf->Cell(75, 6, $totamt, 'BR', 0, 'R');
$pdf->Ln(6);

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

$pdf->SetFillColor(255, 243, 205);

// Heading
$pdf->SetFont('helvetica', '', 12);
$pdf->Cell(95, 20, 'Packing Instruction :', 1, 0, 'L', true);
$pdf->Cell(95, 20, 'Marka & Transport Details :', 1, 1, 'L', true);

// Big Boxes
$x = $pdf->GetX();
$y = $pdf->GetY();

$boxHeight = 30; // Increase to 60, 70, etc. if needed

$pdf->SetFont('helvetica', 'B', 11);

$pdf->MultiCell(
    95,
    $boxHeight,
    $showparty['packdtls'],
    1,
    'L',
    true,
    0,
    $x,
    $y,
    true
);

$pdf->MultiCell(
    95,
    $boxHeight,
    $showparty['transport'],
    1,
    'L',
    true,
    1,
    $x + 95,
    $y,
    true
);


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

$pdf->SetFont('helvetica', '', 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");
