<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

$user_id = (int)($_SESSION['user_id']);
$role    = $_SESSION['role'] ?? 'user';

function e($v) {
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}

function money($v) {
    return number_format((float)$v, 2, '.', ',');
}

function nl2($v) {
    return nl2br(e($v));
}

function embed_image($path) {
    if (!$path || !file_exists($path)) return '';
    $raw = @file_get_contents($path);
    if ($raw === false) return '';
    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    $mime = 'image/png';
    if (in_array($ext, ['jpg', 'jpeg'])) $mime = 'image/jpeg';
    elseif ($ext === 'gif') $mime = 'image/gif';
    elseif ($ext === 'webp') $mime = 'image/webp';
    return 'data:' . $mime . ';base64,' . base64_encode($raw);
}

/* =========================
   LOAD BILL
========================= */
$bill_id = (int)($_GET['id'] ?? 0);

if ($bill_id <= 0) {
    die('Invalid bill ID');
}

/* TEMP DIRECT CHECK - admin/user restriction removed */
$stmt = $conn->prepare("SELECT * FROM bills WHERE id = ?");
$stmt->bind_param("i", $bill_id);
$stmt->execute();
$bill = $stmt->get_result()->fetch_assoc();
$stmt->close();

/* DEBUG */
if (!$bill) {
    echo "<div style='padding:20px;font-size:20px;color:red;'>";
    echo "Bill ID " . $bill_id . " not found in bills table.";
    
    $check = $conn->query("SELECT id FROM bills ORDER BY id DESC LIMIT 10");
    if ($check && $check->num_rows > 0) {
        echo "<br><br>Available Bill IDs:<br>";
        while($r = $check->fetch_assoc()){
            echo $r['id'] . "<br>";
        }
    }

    echo "</div>";
    exit;
}
/* =========================
   LOAD ITEMS
========================= */
$stmt = $conn->prepare("SELECT * FROM bill_items WHERE bill_id = ? ORDER BY id ASC");
$stmt->bind_param("i", $bill_id);
$stmt->execute();
$res = $stmt->get_result();
$stmt->close();

$itemRows = [];
while ($row = $res->fetch_assoc()) {
    $qty = (float)($row['qty'] ?? 0);
    $price = (float)($row['price'] ?? 0);
    $total = (float)($row['total'] ?? ($qty * $price));

    $itemRows[] = [
        'product_name' => $row['product_name'] ?? '-',
        'description'   => $row['description'] ?? ($row['product_description'] ?? ''),
        'hsn_code'      => $row['hsn_code'] ?? ($bill['hsn_code'] ?? '-'),
        'pack_size'     => $row['pack_size'] ?? ($bill['pack_size'] ?? '-'),
        'qty'           => $qty,
        'uom'           => $row['uom'] ?? ($bill['uom'] ?? '-'),
        'price'         => $price,
        'unit'          => ($qty > 0) ? ($total / $qty) : $price,
        'total'         => $total,
    ];
}

/* =========================
   BILL DATA
========================= */
$billDate = !empty($bill['created_at']) ? date('d/m/Y', strtotime($bill['created_at'])) : date('d/m/Y');
$status   = strtolower((string)($bill['payment_status'] ?? 'unpaid'));

$subtotal       = (float)($bill['subtotal'] ?? 0);
$taxableAmount  = (float)($bill['taxable_amount'] ?? 0);
$sgstAmount     = (float)($bill['sgst_amount'] ?? 0);
$cgstAmount     = (float)($bill['cgst_amount'] ?? 0);

$insuranceAmount = (float)($bill['insurance'] ?? 0);
$freightAmount   = (float)($bill['freight'] ?? 0);

$grandTotal = (float)($bill['total_amount'] ?? 0) + $insuranceAmount + $freightAmount;
$discountAmount = max(0, $subtotal - $taxableAmount);

/* unpaid flow */
$paid_amount    = (float)($bill['advance_amount'] ?? 0);
$pending_amount = (float)($bill['due_amount'] ?? ($grandTotal - $paid_amount));
if ($pending_amount < 0) $pending_amount = 0;

$due_date = '-';
if (!empty($bill['unpaid_due_date'])) {
    $due_date = date('d/m/Y', strtotime($bill['unpaid_due_date']));
} elseif (!empty($bill['due_date'])) {
    $due_date = date('d/m/Y', strtotime($bill['due_date']));
}

if ($paid_amount > 0 && $pending_amount > 0) {
    $status_label = 'Advance';
    $status_class = 'advance';
} elseif ($pending_amount <= 0) {
    $status_label = 'Paid';
    $status_class = 'paid';
} else {
    $status_label = 'Unpaid';
    $status_class = 'unpaid';
}

/* =========================
   COMPANY / PARTY FALLBACKS
========================= */
$companyName  = $bill['company_name'] ?? 'Bionick Technology';
$companyAddr  = $bill['company_address'] ?? "A/1113, 11th Floor, Siddhi Vinayak Tower, Makarba, Near Kataria Arcade off S.G. Highway Ahmedabad";
$companyGST   = $bill['company_gst'] ?? '';
$companyPAN   = $bill['company_pan'] ?? '';
$companyCIN   = $bill['company_cin'] ?? '';
$companyPhone = $bill['company_phone'] ?? '';
$companyEmail = $bill['company_email'] ?? 'info@bionick.co.in';

$invoiceNo   = $bill['invoice_no'] ?? $bill['id'];
$invoiceDate = $bill['invoice_date'] ?? $billDate;

$consigneeName    = $bill['consignee_name'] ?? ($bill['customer_name'] ?? '');
$consigneeAddress = $bill['consignee_address'] ?? ($bill['customer_address'] ?? "");
$consigneePhone   = $bill['consignee_phone'] ?? '';
$buyerPhone       = $bill['buyer_phone'] ?? '';

$consigneeContact = trim($bill['consignee_contact'] ?? '');
if (!empty($consigneePhone)) {
    $consigneeContact .= "\nPhone: " . $consigneePhone;
}

$buyerContact = trim($bill['buyer_contact'] ?? '');
if (!empty($buyerPhone)) {
    $buyerContact .= "\nPhone: " . $buyerPhone;
}

$buyerName    = $bill['buyer_name'] ?? '';
$buyerAddress = $bill['buyer_address'] ?? "";

$countryOrigin      = $bill['country_of_origin'] ?? '';
$countryDestination = $bill['country_of_destination'] ?? '';
$portLoading        = $bill['port_of_loading'] ?? '';
$portDischarge      = $bill['port_of_discharge'] ?? '';
$incoterms          = $bill['incoterms'] ?? 'CIF SEA';
$paymentTerms       = $bill['payment_terms'] ?? 'LC 270 Days from the Shipment date or B/L';
$footerNote         = $bill['footer_note'] ?? 'Computer Generated Invoice';

$terms = [];
$table_check = $conn->query("SHOW TABLES LIKE 'terms_conditions'");
if ($table_check && $table_check->num_rows > 0 && !empty($_SESSION['email'])) {
    $terms_stmt = $conn->prepare("SELECT term_text FROM terms_conditions WHERE admin_email = ? ORDER BY id ASC");
    if ($terms_stmt) {
        $terms_stmt->bind_param("s", $_SESSION['email']);
        if ($terms_stmt->execute()) {
            $termsRes = $terms_stmt->get_result();
            while ($row = $termsRes->fetch_assoc()) {
                $txt = trim((string)($row['term_text'] ?? ''));
                if ($txt !== '') $terms[] = $txt;
            }
        }
        $terms_stmt->close();
    }
}

/* =========================
   LOGO
========================= */
$logoPath = '';
foreach ([
    __DIR__ . '/uploads/logo.png',
    __DIR__ . '/assets/img/logo.png',
    __DIR__ . '/assets/image/logo.png',
    __DIR__ . '/logo.png',
    __DIR__ . '/../assets/logo.png'
] as $p) {
    if (file_exists($p)) {
        $logoPath = $p;
        break;
    }
}
$logoSrc = $logoPath ? embed_image($logoPath) : '';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Invoice #<?php echo e($invoiceNo); ?></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<style>
:root{
    --paper:#fff;
    --border:#777;
    --ink:#1f2937;
    --muted:#667085;
    --bg:#eef2f7;
    --head1:#374151;
    --head2:#2f3d52;
    --green:#16a34a;
    --orange:#f59e0b;
    --red:#ef4444;
}

*{box-sizing:border-box}
body{
    margin:0;
    background:linear-gradient(180deg,#f8fafc,#e9eef5);
    font-family:Arial, Helvetica, sans-serif;
    color:var(--ink);
}
.page{
    max-width:1180px;
    margin:0 auto;
    padding:14px;
}
.sheet{
    background:var(--paper);
    border:1px solid #d7d7d7;
    box-shadow:0 10px 30px rgba(0,0,0,.08);
    padding:14px;
}

/* HEADER */
.top-brand{
    display:grid;
    grid-template-columns:160px 1fr;
    gap:8px;
    align-items:start;
    margin-bottom:0;
}
.logo-box{
    width:160px;
    min-height:110px;
    display:flex;
    align-items:flex-start;
    justify-content:flex-start;
    padding:0;
}
.logo-box img{
    width:145px;
    max-height:95px;
    object-fit:contain;
}
.center-head{
    border:1px solid #555;
    padding:6px 10px 4px;
    min-height:110px;
    display:flex;
    flex-direction:column;
    justify-content:flex-start;
}
.company-title{
    margin:0;
    text-align:center;
    font-size:14px;
    line-height:1.1;
    font-weight:800;
    color:#111;
    letter-spacing:.2px;
}
.company-line{
    margin:2px 0 0;
    text-align:center;
    font-size:9px;
    line-height:1.25;
    color:#111;
}
.small-line{
    margin:1px 0 0;
    text-align:center;
    font-size:8px;
    line-height:1.2;
}
.invoice-strip{
    margin-top:4px;
    border-top:1px solid #555;
    border-bottom:1px solid #555;
    background:#fafafa;
    font-size:9px;
    font-weight:700;
}
.invoice-title{
    text-align:center;
    padding:3px 8px;
    border-bottom:1px solid #555;
}
.invoice-meta-row{
    display:grid;
    grid-template-columns:1fr 1fr;
    font-size:9px;
    font-weight:700;
}
.invoice-meta-left,
.invoice-meta-right{
    padding:3px 8px;
}
.invoice-meta-left{
    border-right:1px solid #555;
}

/* TABLES */
.grid-table{
    width:100%;
    border-collapse:collapse;
    margin-top:4px;
    border:1px solid var(--border);
}
.grid-table td{
    border:1px solid var(--border);
    padding:4px 8px 3px;
    font-size:10px;
    vertical-align:top;
    line-height:1.2;
}
.grid-table .title{
    font-weight:700;
}
.grid-table .block{
    white-space:pre-line;
    line-height:1.15;
    margin-top:2px;
}

.table-wrap{
    overflow:visible;
    border-left:1px solid var(--border);
    border-right:1px solid var(--border);
    border-bottom:1px solid var(--border);
    width:100%;
}
table.inv{
    width:100%;
    min-width:0;
    table-layout:fixed;
    border-collapse:collapse;
    font-size:10px;
}
.inv th,
.inv td{
    border:1px solid var(--border);
    padding:6px 6px;
    vertical-align:top;
}
.inv th{
    background:#f0f0f0;
    text-align:center;
    font-weight:700;
}
.inv td{
    background:#fff;
}
.inv td.center{text-align:center}
.inv td.right{text-align:right}
.inv .desc{
    line-height:1.35;
}
.inv .desc strong{
    display:block;
    margin-bottom:2px;
}
.inv .desc small{
    display:block;
    color:#555;
}

/* TOTALS */
.total-box{
    display:grid;
    grid-template-columns:1.4fr 1fr;
    border-left:1px solid var(--border);
    border-right:1px solid var(--border);
    border-bottom:1px solid var(--border);
}
.total-left{
    border-right:1px solid var(--border);
    padding:6px 8px;
    font-size:11px;
    min-height:92px;
    line-height:1.45;
}
.total-right{
    display:block;
}
.total-row{
    display:grid;
    grid-template-columns:1fr 120px;
    border-bottom:1px solid var(--border);
    font-size:11px;
}
.total-row:last-child{border-bottom:none;}
.total-row div{
    padding:5px 8px;
}
.total-row .k{
    border-right:1px solid var(--border);
}
.total-row .v{
    text-align:right;
}
.total-row.grand{
    font-weight:800;
    font-size:12px;
}
.total-row.grand .v{
    font-weight:900;
}
.total-row.paid .v{
    color:var(--green);
    font-weight:800;
}
.total-row.pending .v{
    color:var(--red);
    font-weight:800;
}
.total-row.discount .v{
    color:var(--green);
}

/* NOTE / CERTIFICATION */
.note-box{
    display:grid;
    grid-template-columns: 1fr 1fr;
    border-left:1px solid var(--border);
    border-right:1px solid var(--border);
    border-bottom:1px solid var(--border);
    min-height:130px;
}
.note-left{
    border-right:1px solid var(--border);
    padding:6px 8px;
    font-size:11px;
    line-height:1.45;
    text-align:left;
}
.note-right{
    padding:8px;
    display:flex;
    flex-direction:column;
    justify-content:space-between;
    font-size:11px;
}
.cert{
    text-align:center;
    line-height:1.45;
}
.sign{
    text-align:center;
    font-weight:700;
    padding-top:10px;
}

/* FOOTER */
.footer-note{
    text-align:center;
    font-size:11px;
    color:#4b5563;
    margin-top:4px;
}
.footer-strip{
    display:grid;
    grid-template-columns:1fr 1fr 1fr;
    gap:0;
    align-items:center;
    text-align:center;
    margin-top:8px;
    padding-top:7px;
    border-top:1px solid #ddd;
    font-size:12px;
}
.footer-item{
    display:flex;
    justify-content:center;
    align-items:center;
    gap:8px;
}
.footer-item i{
    font-style:normal;
    font-weight:700;
}

/* ACTIONS */
.actions{
    display:flex;
    justify-content:flex-end;
    gap:10px;
    flex-wrap:wrap;
    margin-top:14px;
}
.btn{
    border:none;
    border-radius:26px;
    padding:12px 16px;
    text-decoration:none;
    display:inline-flex;
    align-items:center;
    gap:8px;
    font-size:15px;
    font-weight:800;
    cursor:pointer;
}
.btn.back{background:#e5e7eb;color:#111827}
.btn.dark{background:#334155;color:#fff}
.hide-in-pdf{display:none !important}

.status-pill{
    display:inline-block;
    margin-top:4px;
    padding:4px 12px;
    border-radius:999px;
    background:#eef2f7;
    border:1px solid #cbd5e1;
    font-size:12px;
    font-weight:800;
}
.status.paid{
    background:#e7f8ee;
    color:var(--green);
    border:1px solid #86efac;
}
.status.unpaid{
    background:#ffe7e7;
    color:var(--red);
    border:1px solid #fecaca;
}
.status.advance{
    background:#fff7e6;
    color:var(--orange);
    border:1px solid #fde68a;
}

@media print{
    body{background:#fff}
    .page{padding:0}
    .sheet{box-shadow:none;border:none;padding:10px}
    .actions{display:none}
    input[type="text"],
    input[type="number"]{
        border:none !important;
        outline:none !important;
        background:transparent !important;
        box-shadow:none !important;
        -webkit-appearance:none !important;
        appearance:none !important;
        padding:0 !important;
        margin:0 !important;
        width:100% !important;
        font-size:10px !important;
    }
}
@media (max-width: 900px){
    .top-brand{
        grid-template-columns:1fr;
    }
    .logo-box{
        width:auto;
    }
    .center-head{
        min-height:auto;
    }
}
</style>
</head>
<body>

<div class="page">
    <div class="sheet" id="invoice">

        <div class="top-brand">
            <div class="logo-box">
                <?php if ($logoSrc): ?>
                    <img src="<?php echo e($logoSrc); ?>" alt="Logo">
                <?php else: ?>
                    <img src="../logoB.png" alt="Logo">
                <?php endif; ?>
            </div>

            <div class="center-head">
                <h1 class="company-title"><?php echo e($companyName); ?></h1>
                <p class="company-line"><?php echo nl2($companyAddr); ?></p>
                <p class="small-line">
                    PHONE NUMBER: <?php echo e($companyPhone); ?> &nbsp;|&nbsp;
                    EMAIL: <?php echo e($companyEmail); ?>
                </p>
                <p class="small-line">
                    CIN NUMBER: <?php echo e($companyCIN); ?> &nbsp;|&nbsp;
                    GST NUMBER: <?php echo e($companyGST); ?> &nbsp;|&nbsp;
                    PAN NUMBER: <?php echo e($companyPAN); ?>
                </p>

                <div class="invoice-strip">
                    <div class="invoice-title">INVOICE</div>
                    <div class="invoice-meta-row">
                        <div class="invoice-meta-left">Invoice No: <?php echo e($invoiceNo); ?></div>
                        <div class="invoice-meta-right">Invoice Date: <?php echo e($invoiceDate); ?></div>
                    </div>
                </div>
            </div>
        </div>

        <table class="grid-table">
            <tr>
                <td style="width:50%;">
                    <div class="title">CONSIGNEE:</div>
                    <div class="block"><?php echo nl2($consigneeName . "\n" . $consigneeAddress); ?></div>
                </td>
                <td style="width:50%;">
                    <div class="title">BUYER:</div>
                    <div class="block"><?php echo nl2($buyerName . "\n" . $buyerAddress); ?></div>
                </td>
            </tr>
            <tr>
                <td>
                    <div class="block"><?php echo nl2($consigneeContact); ?></div>
                </td>
                <td>
                    <div class="block"><?php echo nl2($buyerContact); ?></div>
                </td>
            </tr>
        </table>

       <table class="grid-table" style="border-top:none;">
    <tr>
        <td style="width:25%;"><span class="title">Country of Origin</span><br><?php echo e($countryOrigin); ?></td>

        <td style="width:25%;">
            <span class="title">Port of Loading</span><br>
            <input type="text" name="port_of_loading"
                   value="<?php echo e($portLoading); ?>"
                   style="width:100%; border:none; background:transparent; font-size:10px;">
        </td>

        <td style="width:25%;">
            <span class="title">Port of Discharge</span><br>
            <input type="text" name="port_of_discharge"
                   value="<?php echo e($portDischarge); ?>"
                   style="width:100%; border:none; background:transparent; font-size:10px;">
        </td>

        <td style="width:25%;">
            <span class="title">Country of Destination</span><br>
            <input type="text" name="country_of_destination"
                   value="<?php echo e($countryDestination); ?>"
                   style="width:100%; border:none; background:transparent; font-size:10px;">
        </td>
    </tr>
</table>

        <div style="margin-top:6px;">
            <span class="status <?php echo e($status_class); ?>"><?php echo e($status_label); ?></span>
        </div>

        <div class="table-wrap" style="margin-top:6px;">
            <table class="inv">
                <thead>
                    <tr>
                        <th style="width:38px;">S.No.</th>
                        <th>Description / Product Description</th>
                        <th style="width:70px;">HSN Code</th>
                        <th style="width:60px;">Pack Size</th>
                        <th style="width:60px;">QTY/Pack</th>
                        <th style="width:55px;">UoM</th>
                        <th style="width:70px;">Rate (EUR)</th>
                        <th style="width:75px;">Amount</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!empty($itemRows)): ?>
                    <?php $i = 1; foreach ($itemRows as $item): ?>
                        <tr>
                            <td class="center"><?php echo $i++; ?></td>
                            <td class="desc">
                                <strong><?php echo e($item['product_name']); ?></strong>
                                <?php if (!empty($item['description'])): ?>
                                    <small><?php echo nl2($item['description']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td class="center"><?php echo e($item['hsn_code']); ?></td>
                            <td class="center">     <input type="text"            value="<?php echo e($item['pack_size']); ?>"            style="width:100%; border:none; background:transparent; text-align:center; font-size:10px;"> </td>
                            <td class="center"><?php echo money($item['qty']); ?></td>
                            <td class="center"><?php echo e($item['uom']); ?></td>
                            <td class="right"><?php echo money($item['unit']); ?></td>
                            <td class="right"><?php echo money($item['total']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="8" class="center">No items found</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div class="total-box">
            <div class="total-left">
                <div style="font-weight:700;margin-bottom:4px;">Description</div>
                <div style="margin-top:2px;">
                    <?php
                    function numberToWords($number) {
                        $number = round((float)$number, 2);
                        $whole = floor($number);
                        $decimal = round(($number - $whole) * 100);

                        $ones = [
                            0 => 'Zero', 1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four',
                            5 => 'Five', 6 => 'Six', 7 => 'Seven', 8 => 'Eight', 9 => 'Nine',
                            10 => 'Ten', 11 => 'Eleven', 12 => 'Twelve', 13 => 'Thirteen',
                            14 => 'Fourteen', 15 => 'Fifteen', 16 => 'Sixteen', 17 => 'Seventeen',
                            18 => 'Eighteen', 19 => 'Nineteen'
                        ];
                        $tens = [2 => 'Twenty', 3 => 'Thirty', 4 => 'Forty', 5 => 'Fifty', 6 => 'Sixty', 7 => 'Seventy', 8 => 'Eighty', 9 => 'Ninety'];

                        $convert = function($n) use (&$convert, $ones, $tens) {
                            if ($n < 20) return $ones[$n];
                            if ($n < 100) {
                                $t = intval($n / 10);
                                $r = $n % 10;
                                return $tens[$t] . ($r ? ' ' . $ones[$r] : '');
                            }
                            if ($n < 1000) {
                                $h = intval($n / 100);
                                $r = $n % 100;
                                return $ones[$h] . ' Hundred' . ($r ? ' ' . $convert($r) : '');
                            }
                            if ($n < 100000) {
                                $th = intval($n / 1000);
                                $r = $n % 1000;
                                return $convert($th) . ' Thousand' . ($r ? ' ' . $convert($r) : '');
                            }
                            if ($n < 10000000) {
                                $l = intval($n / 100000);
                                $r = $n % 100000;
                                return $convert($l) . ' Lakh' . ($r ? ' ' . $convert($r) : '');
                            }
                            $cr = intval($n / 10000000);
                            $r = $n % 10000000;
                            return $convert($cr) . ' Crore' . ($r ? ' ' . $convert($r) : '');
                        };

                        $words = $convert((int)$whole) . ' Euro';
                        if ($decimal > 0) {
                            $words .= ' and ' . $convert((int)$decimal) . ' Cents';
                        }
                        return $words . ' Only';
                    }

                    echo numberToWords($grandTotal);
                    ?>
                </div>
            </div>

            <div class="total-right">
                <div class="total-row">
                    <div class="k">Incoterms</div>
                    <div class="v"><?php echo e($incoterms); ?></div>
                </div>
                <div class="total-row">
    <div class="k">Insurance</div>
    <div class="v">
        <input type="number" step="0.01" id="insurance"
               value="<?php echo e($insuranceAmount); ?>"
               oninput="updateGrandTotal()"
               style="width:100%; border:none; background:transparent; text-align:right;">
    </div>
</div>
               <div class="total-row">
    <div class="k">Freight</div>
    <div class="v">
        <input type="number" step="0.01" id="freight"
               value="<?php echo e($freightAmount); ?>"
               oninput="updateGrandTotal()"
               style="width:100%; border:none; background:transparent; text-align:right;">
    </div>
</div>
                <div class="total-row">
                    <div class="k">Paid Amount</div>
                    <div class="v"><?php echo money($paid_amount); ?></div>
                </div>
                <div class="total-row">
                    <div class="k">Unpaid Amount</div>
                    <div class="v"><?php echo money($pending_amount); ?></div>
                </div>
                <div class="total-row grand">
                    <div class="k">Grand Total (in euro)</div>
                    <div class="v" id="grand_total"><?php echo money($grandTotal); ?></div>
                </div>
            </div>
        </div>

        <div class="note-box">
            <div class="note-left">
                <div style="font-weight:700;margin-bottom:4px;">Remarks / Terms</div>
                <?php if (!empty($terms)): ?>
                    <?php foreach ($terms as $idx => $t): ?>
                        <?php echo ($idx + 1) . '. ' . e($t) . "<br>"; ?>
                    <?php endforeach; ?>
                <?php else: ?>
                    1. Commercial Invoice<br>
                    2. Payment Terms: <?php echo e($paymentTerms); ?><br>
                    3. Due Date: <?php echo e($due_date); ?>
                <?php endif; ?>
            </div>
            <div class="note-right">
                <div class="cert"></div>
                <div class="sign">
                    For <?php echo e($companyName); ?><br><br><br>
                    Authorized Signatory
                </div>
            </div>
        </div>

        <div class="footer-note"><?php echo e($footerNote); ?></div>

        <div class="footer-strip">
            <div class="footer-item">☎ <?php echo e($companyPhone); ?></div>
            <div class="footer-item">✉ <?php echo e($companyEmail); ?></div>
            <div class="footer-item">🌐 www.bionick.co.in</div>
        </div>

        <div style="text-align:center;margin-top:6px;font-size:12px;color:#444;">
            <strong>Address:</strong> <?php echo e(trim(str_replace("\n", ', ', $companyAddr))); ?>
        </div>

        <div class="actions">
            <a href="javascript:history.back()" class="btn back">← Back</a>
            <a href="javascript:window.print()" class="btn dark">🖨 Print Invoice</a>
            <a href="javascript:void(0)" onclick="downloadPDF()" class="btn dark">PDF Download</a>
        </div>

    </div>
</div>

<script>
function downloadPDF() {
    const element = document.getElementById('invoice');
    const actions = document.querySelector('.actions');
    if (actions) actions.classList.add('hide-in-pdf');

    html2pdf()
        .from(element)
        .set({
            margin: 5,
            filename: 'Invoice_<?php echo e($invoiceNo); ?>.pdf',
            html2canvas: { scale: 2, useCORS: true },
            jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
        })
        .save()
        .finally(() => {
            if (actions) actions.classList.remove('hide-in-pdf');
        });
}
</script>
<script>
function updateGrandTotal() {
    let baseTotal = <?php echo (float)($bill['total_amount'] ?? 0); ?>;
    let insurance = parseFloat(document.getElementById('insurance').value) || 0;
    let freight   = parseFloat(document.getElementById('freight').value) || 0;

    let grandTotal = baseTotal + insurance + freight;

    document.getElementById('grand_total').innerText =
        grandTotal.toLocaleString('en-US', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
}
</script>
</body>
</html>