<?php
/**
 * Print Invoice Page
 * Printable invoice for unpaid bills - Redesigned
 */

session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

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

$invoice_id = isset($_GET['id']) ? intval($_GET['id']) : (isset($_GET['invoice_id']) ? intval($_GET['invoice_id']) : 0);

if (!$invoice_id) {
    die('Invalid invoice ID');
}

// Fetch invoice details
$invoice_sql = "SELECT 
    i.*,
    p.patient_id,
    p.patient_number,
    u.full_name as patient_name,
    u.gender,
    u.date_of_birth,
    u.phone_primary,
    u.email,
    u.address,
    ip.provider_name as insurance_provider,
    ip.provider_code as insurance_code,
    creator.full_name as created_by_name,
    pv.visit_id,
    pv.visit_number,
    pv.registration_type
FROM invoices i
INNER JOIN patients p ON i.patient_id = p.patient_id
INNER JOIN users u ON p.user_id = u.user_id
LEFT JOIN insurance_providers ip ON i.insurance_provider_id = ip.provider_id
LEFT JOIN users creator ON i.created_by = creator.user_id
LEFT JOIN patient_visits pv ON i.visit_id = pv.visit_id
WHERE i.invoice_id = ?";

$stmt = $conn->prepare($invoice_sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();

if (!$invoice) {
    die('Invoice not found');
}

// Fetch invoice items
$items_sql = "SELECT 
    ii.*
FROM invoice_items ii
WHERE ii.invoice_id = ?
ORDER BY ii.created_at, ii.item_id";

$stmt = $conn->prepare($items_sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$items_result = $stmt->get_result();

// Get hospital settings
$settings_sql = "SELECT setting_key, setting_value FROM system_settings 
                 WHERE setting_key IN ('hospital_name', 'hospital_address', 'hospital_phone', 
                                      'hospital_email', 'hospital_logo', 'hospital_tax_id')";
$settings_result = $conn->query($settings_sql);
$settings = [];
while ($row = $settings_result->fetch_assoc()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

// Helper function
function getSetting($key, $default = '') {
    global $settings;
    return $settings[$key] ?? $default;
}

// Get eTIMS QR code if available
$etims_qr_code = null;
$etims_invoice_number = null;
if (!empty($invoice['etims_invoice_number'])) {
    $etims_sql = "SELECT qr_code, invoice_number FROM etims_invoices WHERE invoice_number = ? OR invoice_id = ? LIMIT 1";
    $etims_stmt = $conn->prepare($etims_sql);
    $etims_invoice_num = $invoice['etims_invoice_number'];
    $etims_stmt->bind_param("si", $etims_invoice_num, $invoice_id);
    $etims_stmt->execute();
    $etims_result = $etims_stmt->get_result();
    if ($etims_row = $etims_result->fetch_assoc()) {
        $etims_qr_code = $etims_row['qr_code'];
        $etims_invoice_number = $etims_row['invoice_number'];
    }
}

// Determine patient type
$patient_type = 'WALK-IN';
if ($invoice['insurance_provider']) {
    $patient_type = 'INSURANCE';
} elseif ($invoice['registration_type'] == 'CORPORATE') {
    $patient_type = 'CORPORATE';
}

// Calculate totals
$subtotal = floatval($invoice['subtotal'] ?? 0);
$tax_amount = floatval($invoice['tax_amount'] ?? 0);
$discount_amount = floatval($invoice['discount_amount'] ?? 0);
$total_amount = floatval($invoice['total_amount'] ?? 0);
$item_count = $items_result->num_rows;

$invoice_data = [
    'subtotal' => $subtotal,
    'tax' => $tax_amount,
    'discount' => $discount_amount,
    'total' => $total_amount,
    'item_count' => $item_count
];

// Convert amount to words function
function convertToWords($number) {
    $ones = ['', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE'];
    $teens = ['TEN', 'ELEVEN', 'TWELVE', 'THIRTEEN', 'FOURTEEN', 'FIFTEEN', 'SIXTEEN', 'SEVENTEEN', 'EIGHTEEN', 'NINETEEN'];
    $tens = ['', '', 'TWENTY', 'THIRTY', 'FORTY', 'FIFTY', 'SIXTY', 'SEVENTY', 'EIGHTY', 'NINETY'];
    $thousands = ['', 'THOUSAND', 'MILLION'];
    
    if ($number == 0) return 'ZERO';
    
    $words = '';
    $level = 0;
    
    while ($number > 0) {
        $chunk = $number % 1000;
        if ($chunk) {
            $chunk_words = '';
            $hundreds = floor($chunk / 100);
            if ($hundreds) {
                $chunk_words .= $ones[$hundreds] . ' HUNDRED ';
            }
            $remainder = $chunk % 100;
            if ($remainder >= 20) {
                $chunk_words .= $tens[floor($remainder / 10)] . ' ';
                $remainder %= 10;
            } elseif ($remainder >= 10) {
                $chunk_words .= $teens[$remainder - 10] . ' ';
                $remainder = 0;
            }
            if ($remainder > 0) {
                $chunk_words .= $ones[$remainder] . ' ';
            }
            $words = $chunk_words . $thousands[$level] . ' ' . $words;
        }
        $number = floor($number / 1000);
        $level++;
    }
    return trim($words);
}

$amount_words = convertToWords(floor($total_amount)) . ' SHILLINGS ONLY';

// Get printed by name
$printed_by_name = $invoice['created_by_name'] ?? 'SYSTEM';
if (isset($_SESSION['user_id'])) {
    $user_sql = "SELECT full_name FROM users WHERE user_id = ?";
    $user_stmt = $conn->prepare($user_sql);
    $user_stmt->bind_param("i", $_SESSION['user_id']);
    $user_stmt->execute();
    $user_result = $user_stmt->get_result();
    if ($user_row = $user_result->fetch_assoc()) {
        $printed_by_name = $user_row['full_name'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars(getSetting('hospital_name', 'ENT Hospital')); ?> - Invoice</title>
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: Arial, sans-serif;
            font-size: 11px;
            line-height: 1.4;
            background: white;
            color: #000;
        }
        
        .invoice-container {
            width: 210mm;
            min-height: 297mm;
            margin: 0 auto;
            padding: 8mm;
            background: white;
            position: relative;
        }
        
        .watermark {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 80px;
            color: rgba(56, 148, 90, 0.08);
            font-weight: bold;
            z-index: 0;
            pointer-events: none;
        }
        
        .content {
            position: relative;
            z-index: 1;
        }
        
        .header {
            text-align: center;
            border-bottom: 2px solid #38945a;
            padding-bottom: 6px;
            margin-bottom: 10px;
            position: relative;
        }
        
        .header h1 {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 3px;
            letter-spacing: 0.5px;
            text-transform: uppercase;
            color: #333;
        }
        
        .header .invoice-title {
            font-size: 20px;
            font-weight: bold;
            color: #38945a;
            margin: 6px 0;
            text-transform: uppercase;
            letter-spacing: 2px;
        }
        
        @supports (-webkit-background-clip: text) {
            .header .invoice-title {
                background: linear-gradient(135deg, #b0c258 0%, #38945a 50%, #417c54 100%);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                background-clip: text;
            }
        }
        
        .header .address { font-size: 8px; margin-bottom: 2px; color: #555; }
        .header .contact { font-size: 8px; font-weight: bold; color: #333; }
        
        .logo-section {
            position: absolute;
            right: 0;
            top: 0;
        }
        
        .logo-section img {
            max-height: 50px;
            max-width: 100px;
        }
        
        .invoice-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 12px;
        }
        
        .info-section {
            border: 1px solid #333;
            padding: 6px;
            border-radius: 4px;
            background: #f9f9f9;
        }
        
        .info-section h3 {
            font-size: 10px;
            font-weight: bold;
            margin-bottom: 5px;
            padding-bottom: 3px;
            border-bottom: 1px solid #38945a;
            color: #38945a;
            text-transform: uppercase;
        }
        
        .info-row {
            display: flex;
            margin-bottom: 3px;
            font-size: 8px;
        }
        
        .info-label {
            font-weight: bold;
            width: 110px;
            flex-shrink: 0;
            color: #555;
        }
        
        .info-value {
            flex: 1;
            color: #000;
        }
        
        .invoice-items {
            border: 1px solid #333;
            margin-bottom: 8px;
            border-radius: 4px;
            overflow: hidden;
        }
        
        .items-header {
            background: linear-gradient(135deg, #b0c258 0%, #38945a 50%, #417c54 100%);
            color: white;
            padding: 4px;
            font-weight: bold;
            text-align: center;
            font-size: 10px;
            text-transform: uppercase;
        }
        
        .invoice-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .invoice-table thead {
            background: #f1f1f1;
        }
        
        .invoice-table th {
            border-right: 1px solid #ddd;
            border-bottom: 1px solid #333;
            padding: 4px 3px;
            font-size: 7px;
            font-weight: bold;
            text-align: left;
            color: #333;
            text-transform: uppercase;
        }
        
        .invoice-table th:last-child { border-right: none; }
        
        .invoice-table td {
            border-right: 1px solid #ddd;
            border-bottom: 1px solid #ddd;
            padding: 3px;
            font-size: 8px;
            vertical-align: top;
        }
        
        .invoice-table td:last-child { border-right: none; }
        
        .amount-column {
            text-align: right;
            font-weight: 600;
            font-family: 'Courier New', monospace;
        }
        
        .module-header {
            background: #e9ecef;
            font-weight: bold;
            color: #495057;
            font-size: 8px;
        }
        
        .totals-section {
            display: flex;
            justify-content: flex-end;
            margin-bottom: 8px;
        }
        
        .totals-table {
            width: 300px;
            border: 1px solid #333;
            border-radius: 4px;
            overflow: hidden;
        }
        
        .totals-row {
            display: flex;
            justify-content: space-between;
            padding: 4px 8px;
            border-bottom: 1px solid #ddd;
            font-size: 9px;
        }
        
        .totals-row:last-child {
            border-bottom: none;
        }
        
        .totals-row.subtotal {
            background: #f8f9fa;
        }
        
        .totals-row.total {
            background: linear-gradient(135deg, #b0c258 0%, #38945a 50%, #417c54 100%);
            color: white;
            font-weight: bold;
            font-size: 11px;
        }
        
        .totals-label {
            font-weight: bold;
        }
        
        .totals-amount {
            font-family: 'Courier New', monospace;
            font-weight: bold;
        }
        
        .amount-words {
            text-align: center;
            font-size: 9px;
            font-style: italic;
            margin: 8px 0;
            border: 1px dashed #38945a;
            padding: 6px;
            background: linear-gradient(135deg, rgba(176, 194, 88, 0.05) 0%, rgba(56, 148, 90, 0.05) 50%, rgba(65, 124, 84, 0.05) 100%);
            border-radius: 4px;
            font-weight: 600;
        }
        
        .verification-section {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 8px;
            margin: 8px 0;
            padding: 6px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: #f9f9f9;
        }
        
        .barcode-container {
            text-align: left;
        }
        
        .barcode-container h5 {
            font-size: 8px;
            font-weight: bold;
            margin-bottom: 3px;
        }
        
        .barcode-container svg {
            max-width: 100%;
            height: 60px;
        }
        
        .qr-container {
            text-align: center;
            border-left: 1px solid #ddd;
            padding-left: 8px;
        }
        
        .qr-container h5 {
            font-size: 8px;
            font-weight: bold;
            margin-bottom: 3px;
        }
        
        .qr-container canvas {
            display: block;
            margin: 0 auto;
            width: 100px;
            height: 100px;
        }
        
        .qr-container img {
            display: block;
            margin: 0 auto;
            max-width: 100px;
            max-height: 100px;
        }
        
        .footer {
            margin-top: 8px;
            text-align: center;
            font-size: 7px;
            border-top: 1px solid #333;
            padding-top: 6px;
        }
        
        .footer p { margin-bottom: 2px; }
        
        .footer .important-note {
            color: #38945a;
            font-weight: bold;
            font-size: 8px;
            margin-top: 4px;
        }
        
        .signature-section {
            margin: 8px 0;
            padding: 6px 0;
            border-top: 1px solid #333;
        }
        
        .signature-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-top: 6px;
        }
        
        .signature-box {
            padding: 0;
            background: transparent;
        }
        
        .signature-header {
            font-size: 9px;
            font-weight: bold;
            text-align: left;
            margin-bottom: 6px;
            padding-bottom: 3px;
            border-bottom: 1px solid #38945a;
            color: #38945a;
            text-transform: uppercase;
        }
        
        .signature-field {
            margin-bottom: 8px;
        }
        
        .signature-field:last-child {
            margin-bottom: 0;
        }
        
        .signature-label {
            font-size: 8px;
            font-weight: bold;
            margin-bottom: 2px;
            color: #555;
            text-transform: uppercase;
        }
        
        .signature-line {
            border-bottom: 1px solid #333;
            padding-bottom: 2px;
            min-height: 18px;
            display: flex;
            align-items: flex-end;
        }
        
        .signature-space {
            min-height: 35px;
            border-bottom: 1px solid #333;
            padding-bottom: 3px;
        }
        
        .signature-text {
            font-size: 9px;
            font-weight: 600;
            color: #000;
            letter-spacing: 0.3px;
        }
        
        .signature-placeholder {
            font-size: 8px;
            color: #999;
            font-style: italic;
        }
        
        @media print {
            body {
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .invoice-container {
                margin: 0;
                padding: 10mm;
            }
            
            .no-print { display: none; }
        }
    </style>
</head>
<body>
    <div class="watermark"><?php echo $invoice['status'] == 'PAID' ? 'PAID' : 'UNPAID'; ?></div>
    
    <div class="invoice-container">
        <div class="content">
            <!-- Header -->
            <div class="header">
                <?php if (!empty(getSetting('hospital_logo'))): ?>
                    <div class="logo-section">
                        <img src="<?php echo htmlspecialchars(getSetting('hospital_logo')); ?>" 
                             alt="<?php echo htmlspecialchars(getSetting('hospital_name', 'ENT Hospital')); ?>">
                    </div>
                <?php endif; ?>
                
                <h1><?php echo strtoupper(getSetting('hospital_name', 'ENT Hospital')); ?></h1>
                <div class="address"><?php echo strtoupper(getSetting('hospital_address', '')); ?></div>
                <div class="contact"><?php echo getSetting('hospital_phone', ''); ?> | <?php echo getSetting('hospital_email', ''); ?></div>
                
                <div class="invoice-title">INVOICE</div>
            </div>
            
            <!-- Invoice Information -->
            <div class="invoice-info">
                <div class="info-section">
                    <h3>Bill To:</h3>
                    <div class="info-row">
                        <div class="info-label">Patient Name:</div>
                        <div class="info-value"><?php echo strtoupper($invoice['patient_name']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">Patient ID:</div>
                        <div class="info-value"><?php echo htmlspecialchars($invoice['patient_number']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">Phone:</div>
                        <div class="info-value"><?php echo htmlspecialchars($invoice['phone_primary'] ?? 'N/A'); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">Email:</div>
                        <div class="info-value"><?php echo htmlspecialchars($invoice['email'] ?? 'N/A'); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">Patient Type:</div>
                        <div class="info-value"><?php echo strtoupper($patient_type); ?></div>
                    </div>
                    <?php if ($invoice['insurance_provider']): ?>
                    <div class="info-row">
                        <div class="info-label">Insurance:</div>
                        <div class="info-value"><?php echo htmlspecialchars($invoice['insurance_provider']); ?></div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div class="info-section">
                    <h3>Invoice Details:</h3>
                    <div class="info-row">
                        <div class="info-label">Invoice Number:</div>
                        <div class="info-value"><?php echo htmlspecialchars($invoice['invoice_number']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">Invoice Date:</div>
                        <div class="info-value"><?php echo date('d F Y', strtotime($invoice['invoice_date'])); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">Due Date:</div>
                        <div class="info-value"><?php echo date('d F Y', strtotime($invoice['due_date'])); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">Status:</div>
                        <div class="info-value" style="color: <?php echo $invoice['status'] == 'PAID' ? '#38945a' : '#417c54'; ?>; font-weight: bold;">
                            <?php echo strtoupper($invoice['status']); ?>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">Total Items:</div>
                        <div class="info-value"><?php echo $item_count; ?></div>
                    </div>
                    <?php if ($invoice['visit_number']): ?>
                    <div class="info-row">
                        <div class="info-label">Visit Number:</div>
                        <div class="info-value"><?php echo htmlspecialchars($invoice['visit_number']); ?></div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Invoice Items -->
            <div class="invoice-items">
                <div class="items-header">Invoice Items</div>
                <table class="invoice-table">
                    <thead>
                        <tr>
                            <th style="width: 5%;">No</th>
                            <th style="width: 12%;">Item Type</th>
                            <th style="width: 38%;">Description</th>
                            <th style="width: 10%;">Date</th>
                            <th style="width: 6%;">Qty</th>
                            <th style="width: 14%;" class="amount-column">Unit Price</th>
                            <th style="width: 15%;" class="amount-column">Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $item_no = 1;
                        if ($items_result->num_rows > 0):
                            while($item = $items_result->fetch_assoc()): 
                                $line_total = floatval($item['line_total'] ?? ($item['unit_price'] * $item['quantity']));
                        ?>
                        <tr>
                            <td><?php echo $item_no++; ?></td>
                            <td><?php echo htmlspecialchars($item['item_type'] ?? 'GENERAL'); ?></td>
                            <td><?php echo htmlspecialchars($item['description'] ?? 'Service'); ?></td>
                            <td><?php echo date('d/m/Y', strtotime($item['created_at'] ?? $invoice['invoice_date'])); ?></td>
                            <td><?php echo number_format($item['quantity'], 0); ?></td>
                            <td class="amount-column">KES <?php echo number_format($item['unit_price'], 2); ?></td>
                            <td class="amount-column">KES <?php echo number_format($line_total, 2); ?></td>
                        </tr>
                        <?php 
                            endwhile;
                        else:
                        ?>
                        <tr>
                            <td colspan="7" style="text-align: center; padding: 10px;">No items found</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Totals -->
            <div class="totals-section">
                <div class="totals-table">
                    <div class="totals-row subtotal">
                        <div class="totals-label">Subtotal:</div>
                        <div class="totals-amount">KES <?php echo number_format($subtotal, 2); ?></div>
                    </div>
                    <?php if ($tax_amount > 0): ?>
                    <div class="totals-row">
                        <div class="totals-label">Tax:</div>
                        <div class="totals-amount">KES <?php echo number_format($tax_amount, 2); ?></div>
                    </div>
                    <?php endif; ?>
                    <?php if ($discount_amount > 0): ?>
                    <div class="totals-row">
                        <div class="totals-label">Discount:</div>
                        <div class="totals-amount">KES <?php echo number_format($discount_amount, 2); ?></div>
                    </div>
                    <?php endif; ?>
                    <div class="totals-row total">
                        <div class="totals-label">TOTAL AMOUNT <?php echo $invoice['status'] == 'PAID' ? 'PAID' : 'DUE'; ?>:</div>
                        <div class="totals-amount">KES <?php echo number_format($total_amount, 2); ?></div>
                    </div>
                    <?php if ($invoice['status'] != 'PAID' && $invoice['balance'] > 0): ?>
                    <div class="totals-row" style="background: #f7b84b; color: #000;">
                        <div class="totals-label">Balance:</div>
                        <div class="totals-amount">KES <?php echo number_format($invoice['balance'], 2); ?></div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Amount in Words -->
            <div class="amount-words">
                Amount in Words: <strong><?php echo $amount_words; ?></strong>
            </div>
            
            <!-- Verification Section -->
            <div class="verification-section">
                <div class="barcode-container">
                    <h5>Invoice Barcode:</h5>
                    <svg id="invoice-barcode"></svg>
                </div>
                
                <div class="qr-container">
                    <h5>E-TIMS QR Code:</h5>
                    <?php if (!empty($etims_qr_code)): ?>
                        <img src="<?php echo htmlspecialchars($etims_qr_code); ?>" alt="E-TIMS QR Code" id="etims-qr-image" style="max-width: 100px; max-height: 100px;">
                        <div style="font-size: 7px; margin-top: 3px; color: #666;">E-TIMS Verified</div>
                        <?php if ($etims_invoice_number): ?>
                        <div style="font-size: 6px; margin-top: 2px; color: #666;"><?php echo htmlspecialchars($etims_invoice_number); ?></div>
                        <?php endif; ?>
                    <?php else: ?>
                        <div id="qr-code"></div>
                        <div style="font-size: 7px; margin-top: 3px; color: #999;">Not yet submitted to eTIMS</div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Signature Section -->
            <div class="signature-section">
                <div class="signature-grid">
                    <!-- Patient Signature -->
                    <div class="signature-box">
                        <div class="signature-header">Patient Acknowledgment</div>
                        <div class="signature-field">
                            <div class="signature-label">Patient Name:</div>
                            <div class="signature-line">
                                <span class="signature-text"><?php echo strtoupper($invoice['patient_name']); ?></span>
                            </div>
                        </div>
                        <div class="signature-field">
                            <div class="signature-label">Signature:</div>
                            <div class="signature-line signature-space">
                                <span class="signature-placeholder">_________________________</span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Staff Signature -->
                    <div class="signature-box">
                        <div class="signature-header">Authorized By</div>
                        <div class="signature-field">
                            <div class="signature-label">Printed By:</div>
                            <div class="signature-line">
                                <span class="signature-text"><?php echo strtoupper($printed_by_name); ?></span>
                            </div>
                        </div>
                        <div class="signature-field">
                            <div class="signature-label">Signature/Stamp:</div>
                            <div class="signature-line signature-space">
                                <span class="signature-placeholder">_________________________</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Footer -->
            <div class="footer">
                <p><strong>Thank you for choosing <?php echo htmlspecialchars(getSetting('hospital_name', 'ENT Hospital')); ?></strong></p>
                <p style="margin-top: 8px; font-size: 8px;">
                    This invoice is system generated. For any billing queries, please visit our billing department.
                </p>
            </div>
        </div>
    </div>
    
    <!-- Print Buttons -->
    <div class="no-print" style="text-align: center; margin: 20px; padding: 20px; background: #f8f9fa; border-radius: 8px;">
        <button onclick="window.print()" style="padding: 12px 30px; background: linear-gradient(135deg, #b0c258 0%, #38945a 50%, #417c54 100%); color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; margin-right: 10px;">
            Print Invoice
        </button>
        <button onclick="window.close()" style="padding: 12px 30px; background: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px;">
            Close
        </button>
    </div>
    
    <script>
        function generateBothCodes() {
            try {
                // 1. Generate Barcode with invoice details
                const invoiceNo = "<?php echo htmlspecialchars($invoice['invoice_number']); ?>";
                const patientId = "<?php echo htmlspecialchars($invoice['patient_number']); ?>";
                
                // Create invoice details as JSON string for barcode
                const invoiceDetails = {
                    invoice: invoiceNo,
                    patient_id: patientId,
                    patient_name: "<?php echo addslashes($invoice['patient_name']); ?>",
                    amount: "<?php echo number_format($total_amount, 2, '.', ''); ?>",
                    date: "<?php echo date('Y-m-d', strtotime($invoice['invoice_date'])); ?>",
                    due_date: "<?php echo date('Y-m-d', strtotime($invoice['due_date'])); ?>",
                    status: "<?php echo $invoice['status']; ?>",
                    hospital: "<?php echo addslashes(getSetting('hospital_name', 'ENT Hospital')); ?>"
                };
                
                // Generate barcode with JSON data
                const barcodeData = JSON.stringify(invoiceDetails);
                
                JsBarcode("#invoice-barcode", barcodeData, {
                    format: "CODE128",
                    width: 2,
                    height: 60,
                    displayValue: true,
                    fontSize: 10,
                    text: invoiceNo
                });
                
                // 2. QR Code - Use eTIMS QR if available, otherwise generate
                <?php if (empty($etims_qr_code)): ?>
                const qrContainer = document.getElementById('qr-code');
                if (qrContainer) {
                    qrContainer.innerHTML = '';
                    
                    new QRCode(qrContainer, {
                        text: barcodeData,
                        width: 100,
                        height: 100,
                        colorDark: "#000000",
                        colorLight: "#ffffff",
                        correctLevel: QRCode.CorrectLevel.M
                    });
                }
                <?php endif; ?>
                
                console.log('Barcode generated successfully');
                
            } catch (error) {
                console.error('Error generating codes:', error);
            }
        }
        
        window.addEventListener('load', function() {
            setTimeout(function() {
                generateBothCodes();
            }, 300);
        });
    </script>
</body>
</html>
