<?php
// Delivery Challan PDF for a Sale Order / Dispatch Alert — rebuilt as a real
// PDF (TCPDF), modeled on saleorder_pdf.php's layout/style (helvetica font,
// bordered header rows, item table, footer), instead of the old
// browser-print HTML page. Sourced from `saleorder`/`saleorderdtl`.
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
require("includes/config.php");
require("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);

// ── Defensive auto-migrate: this print page can be opened directly (new tab)
// without Dispatch Alert having run first in this financial-year DB, so
// re-declare every column it reads instead of assuming another page already
// migrated them ─────────────────────────────────────────────────────────
foreach ([
    'dispatchdate'   => "DATE NULL",
    'dispatchby'     => "VARCHAR(50) NOT NULL DEFAULT ''",
    'lrno'           => "VARCHAR(50) NOT NULL DEFAULT ''",
    'transporter'    => "VARCHAR(100) NOT NULL DEFAULT ''",
    'lrdate'         => "DATE NULL",
    'transportmode'  => "VARCHAR(30) NOT NULL DEFAULT ''",
    'invoiceno'      => "INT(11) NOT NULL DEFAULT 0",
    'invoicedate'    => "DATE NULL",
    'godown'         => "INT(11) NOT NULL DEFAULT 0",
] as $col => $def) {
    $chk = mysqli_query($conn, "SHOW COLUMNS FROM `saleorder` LIKE '$col'");
    if ($chk && mysqli_num_rows($chk) == 0)
        mysqli_query($conn, "ALTER TABLE `saleorder` ADD COLUMN `$col` $def");
}

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

// Delivery Challan is generated per Sale Order (the vouchno dispatch alert
// works against) — it documents the goods physically handed over, backed by
// the Sale Invoice once one has been generated against it.
$result = mysqli_query($conn,
    "SELECT s.*, a.name AS customername, a.add1, a.add2, a.add3, a.city, a.pin, a.mobile,
            g.name AS godownname
     FROM `saleorder` s
     LEFT JOIN `accmast` a ON a.accode = s.customer
     LEFT JOIN `godown`  g ON g.code   = s.godown
     WHERE s.vouchno='$vouchno'") or die(mysqli_error($conn));
$get = mysqli_fetch_array($result);
if (!$get) { die("Sale Order not found."); }

$tres = mysqli_query($conn,
    "SELECT d.*, p.name AS prodname
     FROM `saleorderdtl` d
     LEFT JOIN `product` p ON p.id = d.product
     WHERE d.vouchno='$vouchno' ORDER BY d.srl") or die(mysqli_error($conn));
$lines = [];
$totqty = 0;
while ($r = mysqli_fetch_array($tres)) { $lines[] = $r; $totqty += (float)$r['qty']; }

$compres = mysqli_query($conn, "SELECT * FROM $zdbroot.`company` WHERE `code`='$compcd'");
$comprow = $compres ? mysqli_fetch_assoc($compres) : null;
$compname = $comprow ? $comprow['name'] : '';

$vouchdt_disp    = (!empty($get['vouchdt']) && $get['vouchdt'] != '0000-00-00') ? date('d-m-Y', strtotime($get['vouchdt'])) : '';
$dispatchdt_disp = (!empty($get['dispatchdate']) && $get['dispatchdate'] != '0000-00-00') ? date('d-m-Y', strtotime($get['dispatchdate'])) : '';
$lrdt_disp       = (!empty($get['lrdate']) && $get['lrdate'] != '0000-00-00') ? date('d-m-Y', strtotime($get['lrdate'])) : '';
$invoice_disp    = ((int)($get['invoiceno'] ?? 0) > 0) ? 'SAL#' . (int)$get['invoiceno'] : '-';

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->SetFont('helvetica', 'B', 20);
$pdf->Cell(190, 8, "Delivery Challan", '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, $get['customername'] ?? '', "T", 0, 'L');

$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(20, 6, "SO#", "T", 0, 'R');
$pdf->Cell(2, 6, ":", 'T', 0, 'L');
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(48, 6, "SO#" . $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(($get['add1'] ?? '') . ' ' . ($get['add2'] ?? '')), 0, 0, 'L');

$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(20, 6, "Order Dt", '', 0, 'R');
$pdf->Cell(2, 6, ":", '', 0, 'L');
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(48, 6, $vouchdt_disp, '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(($get['add3'] ?? '') . ' ' . ($get['city'] ?? '') . ' ' . ($get['pin'] ?? '')), 0, 0, 'L');
$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(20, 6, "Dispatch", 0, 0, 'R');
$pdf->Cell(2, 6, ":", '', 0, 'L');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(48, 6, $dispatchdt_disp, '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(($get['mobile'] ?? '')), 0, 0, 'L');
$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(20, 6, "Invoice", 0, 0, 'R');
$pdf->Cell(2, 6, ":", '', 0, 'L');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(48, 6, $invoice_disp, 'R', 0, 'L');
$pdf->Ln(6);

$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(18, 6, "Godown", 'LB', 0, 'L');
$pdf->Cell(2, 6, ":", 'B', 0, 'L');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(100, 6, $get['godownname'] ?? '', 'B', 0, 'L');
$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(20, 6, "Transport", 'B', 0, 'R');
$pdf->Cell(2, 6, ":", 'B', 0, 'L');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(48, 6, trim(($get['transporter'] ?? '') . ($get['lrno'] ? ' LR#'.$get['lrno'] : '')), 'RB', 0, 'L');
$pdf->Ln(10);

// ── Item table (Product/Qty only — no pricing) ─────────────────────────────
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(15, 6, "Sr.", 'TLB', 0, 'C');
$pdf->Cell(145, 6, "Product", 'TLB', 0, 'C');
$pdf->Cell(30, 6, "Qty.", 'TLRB', 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(145, 6, $ln['prodname'] ?? '', 'LB', 0, 'L');
    $pdf->Cell(30, 6, pf2($ln['qty'] ?? 0), 'BLR', 0, 'R');
    $pdf->Ln(6);
}

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

$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(160, 6, "Total Qty", 'BL', 0, 'R');
$pdf->Cell(30, 6, pf2($totqty), 'BLR', 0, 'R');
$pdf->Ln(10);

$pdf->SetFont('helvetica', '', 9);
$noteInvoice = ((int)($get['invoiceno'] ?? 0) > 0) ? ' and covered by Tax Invoice SAL#' . (int)$get['invoiceno'] : '';
$pdf->MultiCell(190, 5, "This Delivery Challan is issued for goods dispatched against Sale Order SO#$vouchno$noteInvoice. Not a demand for payment.", 0, 'L');
$pdf->Ln(20);

$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(95, 6, "", 'T', 0, 'C');
$pdf->Cell(95, 6, "", 'T', 0, 'C');
$pdf->Ln(6);
$pdf->Cell(95, 6, "Receiver's Signature", 0, 0, 'C');
$pdf->Cell(95, 6, "For " . $compname, 0, 0, 'C');

if (ob_get_level() > 0) { ob_end_clean(); }
$pdf->Output("Delivery Challan-" . $vouchno . ".pdf", "I");
