<?php
// Updated: 2025-11-05 - Cache cleared
session_start();
include_once('../../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    header('location:../../login.php');
    exit();
}

$invoiceNumber = isset($_GET['invoice']) ? mysqli_real_escape_string($con, $_GET['invoice']) : '';

if (empty($invoiceNumber)) {
    die('Invalid invoice number');
}

function formatAmountToWords($amount)
{
    $value = (int) floor(floatval($amount));

    if ($value < 0) {
        return 'Minus ' . formatAmountToWords(abs($value));
    }

    if (class_exists('NumberFormatter')) {
        $formatter = new NumberFormatter('en_IN', NumberFormatter::SPELLOUT);
        return ucwords($formatter->format($value));
    }

    return fallbackNumberToWords($value);
}

function fallbackNumberToWords($number)
{
    if ($number === 0) {
        return 'Zero';
    }

    static $words = [
        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'
    ];

    static $tens = [
        20 => 'Twenty',
        30 => 'Thirty',
        40 => 'Forty',
        50 => 'Fifty',
        60 => 'Sixty',
        70 => 'Seventy',
        80 => 'Eighty',
        90 => 'Ninety'
    ];

    static $scales = [
        10000000 => 'Crore',
        100000 => 'Lakh',
        1000 => 'Thousand',
        100 => 'Hundred'
    ];

    $result = '';

    foreach ($scales as $value => $label) {
        if ($number >= $value) {
            $count = (int) floor($number / $value);
            $number %= $value;
            $separator = $value === 100 && $number > 0 ? ' and ' : ' ';
            $result .= fallbackNumberToWords($count) . ' ' . $label;
            if ($number > 0) {
                $result .= $separator;
            }
        }
    }

    if ($number > 0) {
        if ($number < 20) {
            $result .= $words[$number];
        } else {
            $tensValue = (int) floor($number / 10) * 10;
            $unitsValue = $number % 10;
            $result .= $tens[$tensValue];
            if ($unitsValue > 0) {
                $result .= ' ' . $words[$unitsValue];
            }
        }
    }

    $cleanResult = trim(preg_replace('/\s+/', ' ', $result));
    return ucwords($cleanResult);
}

// Get store settings
$storeSettingsQuery = "SELECT * FROM tblstore_settings WHERE StoreCode = 'ST0002' LIMIT 1";
$storeSettingsResult = mysqli_query($con, $storeSettingsQuery);
$storeSettings = null;

if ($storeSettingsResult && mysqli_num_rows($storeSettingsResult) > 0) {
    $storeSettings = mysqli_fetch_assoc($storeSettingsResult);
}

// Get invoice settings
$invoiceSettingsQuery = "SELECT * FROM tblinvoice_settings WHERE StoreCode = 'ST0002' LIMIT 1";
$invoiceSettingsResult = mysqli_query($con, $invoiceSettingsQuery);
$invoiceSettings = null;

if ($invoiceSettingsResult && mysqli_num_rows($invoiceSettingsResult) > 0) {
    $invoiceSettings = mysqli_fetch_assoc($invoiceSettingsResult);
}

// Get font settings
$fontSettingsQuery = "SELECT * FROM tblfont_settings WHERE StoreCode = 'ST0002' LIMIT 1";
$fontSettingsResult = mysqli_query($con, $fontSettingsQuery);
$fontSettings = null;

if ($fontSettingsResult && mysqli_num_rows($fontSettingsResult) > 0) {
    $fontSettings = mysqli_fetch_assoc($fontSettingsResult);
}

// Get sale data with customer balance and GST information
$saleSql = "SELECT s.*, c.CustomerName, c.CustomerCode, c.Mobile, c.Address, c.City, c.State, c.GSTNumber, c.CurrentBalance 
            FROM tblsales s 
            JOIN tblcustomers c ON s.CustomerID = c.ID 
            WHERE s.InvoiceNumber = '$invoiceNumber'";
$saleResult = mysqli_query($con, $saleSql);

if (!$saleResult) {
    die('Database query error: ' . mysqli_error($con));
}

if (mysqli_num_rows($saleResult) == 0) {
    die('Invoice not found: ' . htmlspecialchars($invoiceNumber));
}

$sale = mysqli_fetch_assoc($saleResult);

// Get sale details with GST information and MRP from items table
$detailsSql = "SELECT sd.*, i.MRP 
               FROM tblsales_gst_details sd 
               LEFT JOIN tblitems i ON sd.ProductID = i.ID 
               WHERE sd.SaleID = " . $sale['ID'] . " 
               ORDER BY sd.ID";
$detailsResult = mysqli_query($con, $detailsSql);

if (!$detailsResult) {
    die('Database query error: ' . mysqli_error($con));
}

// Calculate GST summary
$gstSummary = [];
$totalTaxableAmount = 0;
$totalCGST = 0;
$totalSGST = 0;
$totalIGST = 0;
$totalGSTAmount = 0;
$totalDiscountAmount = 0;

mysqli_data_seek($detailsResult, 0);
while ($item = mysqli_fetch_assoc($detailsResult)) {
    $taxPercent = floatval($item['TaxPercentage']);
    
    // Get discount directly from table
    $itemDiscount = floatval($item['DiscountAmount']);
    
    if (!isset($gstSummary[$taxPercent])) {
        $gstSummary[$taxPercent] = [
            'taxable' => 0,
            'cgst' => 0,
            'sgst' => 0,
            'igst' => 0,
            'total' => 0
        ];
    }
    
    $gstSummary[$taxPercent]['taxable'] += floatval($item['TaxableAmount']);
    $gstSummary[$taxPercent]['cgst'] += floatval($item['CGSTAmount']);
    $gstSummary[$taxPercent]['sgst'] += floatval($item['SGSTAmount']);
    $gstSummary[$taxPercent]['igst'] += floatval($item['IGSTAmount']);
    $gstSummary[$taxPercent]['total'] += floatval($item['TotalTaxAmount']);
    
    $totalTaxableAmount += floatval($item['TaxableAmount']);
    $totalCGST += floatval($item['CGSTAmount']);
    $totalSGST += floatval($item['SGSTAmount']);
    $totalIGST += floatval($item['IGSTAmount']);
    $totalGSTAmount += floatval($item['TotalTaxAmount']);
    $totalDiscountAmount += $itemDiscount;
}

// Reset pointer for item display
mysqli_data_seek($detailsResult, 0);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Estimate - <?php echo $invoiceNumber; ?></title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Tamil:wght@400;700&display=swap');
        
        @page {
            size: A4;
            margin: 5mm;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: <?php echo $fontSettings['TableBodyFont'] ?? 'Arial'; ?>, 'Noto Sans Tamil', 'Segoe UI', 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif;
            font-size: <?php echo $fontSettings['TableBodySize'] ?? 9; ?>px;
            font-weight: <?php echo $fontSettings['TableBodyWeight'] ?? 'normal'; ?>;
            line-height: 1.2;
            color: <?php echo $fontSettings['TableBodyColor'] ?? '#000'; ?>;
        }
        
        .invoice-container {
            width: 200mm;
            min-height: 287mm;
            border: 1px solid #000;
            padding: 0;
            background: #fff;
            display: flex;
            flex-direction: column;
            margin: 0 auto;
        }

        .invoice-content {
            flex: 1 0 auto;
            padding: 1mm;
            border: 1px solid #000;
            border-bottom: none;
            background: #fff;
        }

        .invoice-bottom {
            margin-top: auto;
            padding: 1mm;
            border: 1px solid #000;
            border-top: none;
            background: #fff;
        }

        .invoice-bottom .summary-section {
            margin-top: 0;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border: 1px solid #000;
            padding: 5px;
            margin-bottom: 2px;
            gap: 5px;
        }
        
        .company-logo {
            width: 80px;
            height: 80px;
            background: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            flex-shrink: 0;
        }
        
        .company-logo img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        
        .company-details {
            flex: 1;
            padding: 0 10px;
            text-align: center;
        }
        
        .company-details h1 {
            font-family: <?php echo $fontSettings['CompanyNameFont'] ?? 'Arial'; ?>, 'Noto Sans Tamil', sans-serif;
            font-size: <?php echo $fontSettings['CompanyNameSize'] ?? 18; ?>px;
            font-weight: <?php echo $fontSettings['CompanyNameWeight'] ?? 'bold'; ?>;
            margin-bottom: 2px;
            color: <?php echo $fontSettings['CompanyNameColor'] ?? '#000'; ?>;
        }
        
        .company-details p {
            font-family: <?php echo $fontSettings['AddressFont'] ?? 'Arial'; ?>, 'Noto Sans Tamil', sans-serif;
            margin: 1px 0;
            font-size: <?php echo $fontSettings['AddressSize'] ?? 9; ?>px;
            font-weight: <?php echo $fontSettings['AddressWeight'] ?? 'normal'; ?>;
            color: <?php echo $fontSettings['AddressColor'] ?? '#000'; ?>;
        }
        
        .invoice-title {
            text-align: center;
            padding: 3px;
            border: 1px solid #000;
            background: #fff;
            margin-bottom: 2px;
        }
        
        .invoice-title h2 {
            font-family: <?php echo $fontSettings['InvoiceTitleFont'] ?? 'Arial'; ?>, sans-serif;
            font-size: <?php echo $fontSettings['InvoiceTitleSize'] ?? 14; ?>px;
            font-weight: <?php echo $fontSettings['InvoiceTitleWeight'] ?? 'bold'; ?>;
            color: <?php echo $fontSettings['InvoiceTitleColor'] ?? '#000'; ?>;
        }
        
        .invoice-title p {
            font-family: <?php echo $fontSettings['InvoiceTitleFont'] ?? 'Arial'; ?>, sans-serif;
            font-size: <?php echo ($fontSettings['InvoiceTitleSize'] ?? 14) - 5; ?>px;
            margin-top: 1px;
            color: <?php echo $fontSettings['InvoiceTitleColor'] ?? '#000'; ?>;
        }
        
        .bill-details {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2px;
            gap: 4px;
        }
        
        .bill-to, .ship-to, .invoice-info {
            border: 1px solid #000;
            padding: 5px;
        }
        
        .bill-to {
            width: 50%;
        }
        
        .ship-to {
            width: 50%;
        }
        
        .invoice-info {
            width: 35%;
        }
        
        .section-title {
            font-family: <?php echo $fontSettings['SectionTitleFont'] ?? 'Arial'; ?>, sans-serif;
            background: #f0f0f0;
            padding: 2px 5px;
            font-weight: <?php echo $fontSettings['SectionTitleWeight'] ?? 'bold'; ?>;
            font-size: <?php echo $fontSettings['SectionTitleSize'] ?? 10; ?>px;
            margin-bottom: 4px;
            border: 1px solid #000;
            margin: -5px -5px 4px -5px;
            color: <?php echo $fontSettings['SectionTitleColor'] ?? '#000'; ?>;
        }
        
        .detail-row {
            display: flex;
            margin: 2px 0;
            font-family: <?php echo $fontSettings['ContactFont'] ?? 'Arial'; ?>, sans-serif;
            font-size: <?php echo $fontSettings['ContactSize'] ?? 9; ?>px;
            font-weight: <?php echo $fontSettings['ContactWeight'] ?? 'normal'; ?>;
            color: <?php echo $fontSettings['ContactColor'] ?? '#000'; ?>;
        }
        
        .detail-label {
            font-weight: bold;
            width: 100px;
        }
        
        .detail-value {
            flex: 1;
        }
        
        table {
            font-family: <?php echo $fontSettings['TableBodyFont'] ?? 'Arial'; ?>, sans-serif;
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 2px;
            font-size: <?php echo $fontSettings['TableBodySize'] ?? 9; ?>px;
        }
        
        table th {
            font-family: <?php echo $fontSettings['TableHeaderFont'] ?? 'Arial'; ?>, sans-serif;
            background: <?php echo $fontSettings['TableHeaderBgColor'] ?? '#f0f0f0'; ?>;
            border: 1px solid #000;
            padding: 4px 2px;
            text-align: center;
            font-weight: <?php echo $fontSettings['TableHeaderWeight'] ?? 'bold'; ?>;
            font-size: <?php echo $fontSettings['TableHeaderSize'] ?? 9; ?>px;
            color: <?php echo $fontSettings['TableHeaderColor'] ?? '#000'; ?>;
        }
        
        table td {
            border: 1px solid #000;
            padding: 3px 2px;
            text-align: left;
            font-weight: <?php echo $fontSettings['TableBodyWeight'] ?? 'normal'; ?>;
            color: <?php echo $fontSettings['TableBodyColor'] ?? '#000'; ?>;
        }
        
        .text-right {
            text-align: right !important;
        }
        
        .text-center {
            text-align: center !important;
        }
        
        .summary-section {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2px;
            margin-top: 5px;
            gap: 4px;
        }
        
        .bank-details {
            width: 55%;
            border: 1px solid #000;
            padding: 5px;
        }
        
        .amount-summary {
            width: 42%;
        }
        
        .amount-summary table {
            margin-bottom: 0;
        }
        
        .amount-summary table td {
            padding: 3px 5px;
            font-size: 9px;
        }
        
        .grand-total {
            background: #f9f9f9;
            font-weight: bold;
            font-size: 10px;
        }
        
        .footer-section {
            display: flex;
            justify-content: space-between;
            margin-top: 5px;
            margin-bottom: 2px;
            gap: 4px;
        }
        
        .declaration {
            font-family: <?php echo $fontSettings['DeclarationFont'] ?? 'Arial'; ?>, sans-serif;
            width: 60%;
            border: 1px solid #000;
            padding: 5px;
            font-size: <?php echo $fontSettings['DeclarationSize'] ?? 8; ?>px;
            font-weight: <?php echo $fontSettings['DeclarationWeight'] ?? 'normal'; ?>;
            color: <?php echo $fontSettings['DeclarationColor'] ?? '#000'; ?>;
        }
        
        .signature-section {
            width: 37%;
            border: 1px solid #000;
            padding: 5px;
            text-align: center;
        }
        
        .qr-code {
            width: 80px;
            height: 80px;
            border: 1px solid #000;
            margin: 5px auto;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #fff;
        }
        
        .thank-you {
            font-family: <?php echo $fontSettings['FooterFont'] ?? 'Arial'; ?>, sans-serif;
            text-align: center;
            padding: 4px;
            border: 1px solid #000;
            margin-top: 2px;
            font-weight: <?php echo $fontSettings['FooterWeight'] ?? 'bold'; ?>;
            font-size: <?php echo $fontSettings['FooterSize'] ?? 10; ?>px;
            color: <?php echo $fontSettings['FooterColor'] ?? '#000'; ?>;
        }
        
        @media print {
            body {
                padding: 0;
            }
            
            .no-print {
                display: none !important;
            }
            
            .invoice-container {
                border: none;
                padding: 0;
            }
        }
        
        .gst-summary th {
            font-size: 9px;
            padding: 3px;
        }
        
        .gst-summary td {
            font-size: 9px;
            padding: 3px;
        }
    </style>
</head>
<body>
    <div class="invoice-container">
        <div class="invoice-content">
        <!-- Header -->
        <div class="header">
            <!-- Left Logo -->
            <div class="company-logo">
                <?php if ($storeSettings && !empty($storeSettings['StoreLogo1'])): ?>
                    <img src="../../<?php echo htmlspecialchars($storeSettings['StoreLogo1']); ?>" alt="Logo" onerror="this.parentElement.innerHTML='<div style=\'font-size:24px;color:#1976d2;\'>🏪</div>'">
                <?php else: ?>
                    <div style='font-size:24px;color:#1976d2;'>🏪</div>
                <?php endif; ?>
            </div>
            
            <!-- Center Company Details -->
            <div class="company-details">
                <h1><?php echo htmlspecialchars($storeSettings['StoreName'] ?? 'STORE NAME'); ?></h1>
                <?php if (!empty($storeSettings['City']) || !empty($storeSettings['Postcode'])): ?>
                <p><strong><?php echo htmlspecialchars($storeSettings['City'] ?? ''); ?><?php echo !empty($storeSettings['Postcode']) ? ' - ' . htmlspecialchars($storeSettings['Postcode']) : ''; ?></strong></p>
                <?php endif; ?>
                <?php if (!empty($storeSettings['Address'])): ?>
                <p><?php echo htmlspecialchars($storeSettings['Address']); ?></p>
                <?php endif; ?>
                <?php if (!empty($storeSettings['Mobile']) || !empty($storeSettings['Phone'])): ?>
                <p><strong>Contact No. :</strong> <?php echo htmlspecialchars($storeSettings['Mobile'] ?? ''); ?><?php echo !empty($storeSettings['Phone']) ? ', ' . htmlspecialchars($storeSettings['Phone']) : ''; ?></p>
                <?php endif; ?>
                <?php if (!empty($storeSettings['Email'])): ?>
                <p><strong>Email :</strong> <?php echo htmlspecialchars($storeSettings['Email']); ?></p>
                <?php endif; ?>
                <?php if (!empty($storeSettings['StoreWebsite'])): ?>
                <p><strong>Website :</strong> <?php echo htmlspecialchars($storeSettings['StoreWebsite']); ?></p>
                <?php endif; ?>
            </div>
            
            <!-- Right Logo -->
            <div class="company-logo">
                <?php if ($storeSettings && !empty($storeSettings['StoreLogo2'])): ?>
                    <img src="../../<?php echo htmlspecialchars($storeSettings['StoreLogo2']); ?>" alt="Logo 2" onerror="this.parentElement.innerHTML='<div style=\'font-size:24px;color:#1976d2;\'>🏬</div>'">
                <?php else: ?>
                    <div style='font-size:24px;color:#1976d2;'>🏬</div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Invoice Title -->
        <div class="invoice-title">
            <h2>Estimate</h2>
        </div>
        
        <!-- Bill Details Row 1 -->
        <div class="bill-details">
            <div class="bill-to">
                <div class="section-title">Bill To</div>
                <div class="detail-row">
                    <span class="detail-label">Name :</span>
                    <span class="detail-value"><?php echo htmlspecialchars($sale['CustomerName']); ?></span>
                </div>
                <?php if (!empty($sale['Address'])): ?>
                <div class="detail-row">
                    <span class="detail-label">Address :</span>
                    <span class="detail-value"><?php echo htmlspecialchars($sale['Address']); ?></span>
                </div>
                <?php endif; ?>
                <?php if (!empty($sale['State'])): ?>
                <div class="detail-row">
                    <span class="detail-label">State :</span>
                    <span class="detail-value"><?php echo htmlspecialchars($sale['State']); ?></span>
                </div>
                <?php endif; ?>
            </div>
            
            <div class="invoice-info">
                <div class="section-title">Invoice Details</div>
                <div class="detail-row">
                    <span class="detail-label"># Inv. No. :</span>
                    <span class="detail-value"><?php echo htmlspecialchars($sale['InvoiceNumber']); ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Inv. Date :</span>
                    <span class="detail-value"><?php echo date('d-m-Y', strtotime($sale['SaleDate'])); ?></span>
                </div>
                <?php if (!empty($sale['PaymentMode'])): ?>
                <div class="detail-row">
                    <span class="detail-label">Payment Mode :</span>
                    <span class="detail-value"><?php echo htmlspecialchars($sale['PaymentMode']); ?></span>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
    <!-- Items Table -->
        <table>
            <!-- Generated: <?php echo date('Y-m-d H:i:s'); ?> -->
            <thead>
                <tr>
                    <th style="width: 5%;">Sr</th>
                    <th style="width: 50%;">Description</th>
                    <th style="width: 15%;" class="text-right">Quantity</th>
                    <th style="width: 15%;" class="text-right">Price</th>
                    <th style="width: 15%;" class="text-right">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $sno = 1;
                $totalQuantity = 0;
                while ($item = mysqli_fetch_assoc($detailsResult)): 
                    $itemTotal = floatval($item['FinalAmount']);
                    $rate = floatval($item['Rate']);
                    $quantity = floatval($item['Quantity']);
                    $totalQuantity += $quantity;
                ?>
                <tr>
                    <td class="text-center"><?php echo $sno; ?></td>
                    <td><?php echo htmlspecialchars($item['ProductName']); ?></td>
                    <td class="text-right"><?php echo number_format($quantity, 2); ?></td>
                    <td class="text-right"><?php echo number_format($rate, 2); ?></td>
                    <td class="text-right"><?php echo number_format($itemTotal, 2); ?></td>
                </tr>
                <?php 
                    $sno++;
                endwhile; 
                ?>
                
                <tr>
                    <td class="text-right" colspan="2"><strong>Sub-Total:</strong></td>
                    <td class="text-right"><strong><?php echo number_format($totalQuantity, 2); ?></strong></td>
                    <td>&nbsp;</td>
                    <td class="text-right"><strong><?php echo number_format($sale['FinalAmount'] ?: $sale['TotalAmount'], 2); ?></strong></td>
                </tr>
            </tbody>
        </table>
        
        </div>

        <div class="invoice-bottom">
            <!-- Summary Section -->
            <div class="summary-section">
                <div class="bank-details">
                    <div style="margin-top: 4px; font-weight: bold; font-size: 9px;">
                        Invoice Total in Word
                    </div>
                    <div style="font-size: 9px; font-weight: bold; margin-top: 2px;">
                        Rupees <?php 
                        $amount = $sale['FinalAmount'] ?: $sale['TotalAmount'];
                        echo formatAmountToWords($amount);
                        ?> Only
                    </div>
                </div>
                
                <div class="amount-summary">
                    <table class="gst-summary">
                        <tbody>
                            <?php if (!empty($sale['CooliAmount']) && $sale['CooliAmount'] > 0): ?>
                            <tr>
                                <td colspan="2">Freight Packing Charges :</td>
                                <td class="text-right"><?php echo number_format($sale['CooliAmount'], 2); ?></td>
                            </tr>
                            <?php endif; ?>
                            <?php if (!empty($sale['RoundOffAmount']) && $sale['RoundOffAmount'] != 0): ?>
                            <tr>
                                <td colspan="2">Round off :</td>
                                <td class="text-right"><?php echo number_format($sale['RoundOffAmount'], 2); ?></td>
                            </tr>
                            <?php endif; ?>
                            <tr class="grand-total">
                                <td colspan="2"><strong>Total Amount :</strong></td>
                                <td class="text-right"><strong><?php echo number_format($sale['FinalAmount'] ?: $sale['TotalAmount'], 2); ?></strong></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="thank-you">
                Thank You For Business With Us!
            </div>
        </div>
    </div>
    
    <!-- Print Button -->
    <div class="no-print" style="text-align: center; margin: 20px; position: fixed; top: 10px; right: 10px; background: white; padding: 10px; border: 2px solid #1976d2; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.2); z-index: 9999;">
        <button onclick="window.print()" style="padding: 10px 20px; font-size: 14px; cursor: pointer; background: #1976d2; color: white; border: none; border-radius: 3px; margin-right: 5px;">
            🖨️ Print
        </button>
        <button onclick="window.location.href='../index.php'" style="padding: 10px 20px; font-size: 14px; cursor: pointer; background: #28a745; color: white; border: none; border-radius: 3px; margin-right: 5px;">
            🏠 Back to Sales
        </button>
        <button onclick="window.close()" style="padding: 10px 20px; font-size: 14px; cursor: pointer; background: #dc3545; color: white; border: none; border-radius: 3px;">
            ❌ Close
        </button>
    </div>
    
    <script>
        // Auto-print if autoprint parameter is set
        window.addEventListener('load', function() {
            <?php if (isset($_GET['autoprint']) && $_GET['autoprint'] == '1'): ?>
            // Auto-trigger print dialog
            setTimeout(function() {
                window.print();
            }, 500);
            <?php endif; ?>
        });
        
        // After printing, automatically navigate back to sales page
        window.addEventListener('afterprint', function() {
            setTimeout(function() {
                window.location.href = '../index.php';
            }, 300);
        });
    </script>
</body>
</html>
