<?php
session_start();
include 'db.php';
include 'includes/payment_methods.php'; // Include payment methods functions

$last_sale = null;
$last_items = [];
$fbr_enabled = false;
$branch_info = null;

$receipt_font_size = 16; // default
$result = $conn->query("SELECT value FROM settings WHERE code = 'receipt_font_size' AND is_active = 1 LIMIT 1");
if ($result && $row = $result->fetch_assoc()) {
    $receipt_font_size = intval($row['value']);
}

// Load FBR config
$fbr_result = $conn->query("SELECT is_enabled FROM fbr_config LIMIT 1");
if ($fbr_result && $fbr_row = $fbr_result->fetch_assoc()) {
    $fbr_enabled = intval($fbr_row['is_enabled']) === 1;
}

// Load branch info
$branch_result = $conn->query("SELECT * FROM branch_info LIMIT 1");
if ($branch_result && $branch_result->num_rows > 0) {
    $branch_info = $branch_result->fetch_assoc();
}

// Load sale + items
if (!empty($_GET['sale_id'])) {
    $sale_id = intval($_GET['sale_id']);
    $sale_result = $conn->query("SELECT s.*, dt.table_name, c.phone, c.address, do.delivery_address 
                                 FROM sales s 
                                 LEFT JOIN dinein_tables dt ON s.table_id = dt.id 
                                 LEFT JOIN customers c ON s.customer_id = c.id
                                 LEFT JOIN delivery_orders do ON s.id = do.sale_id
                                 WHERE s.id = $sale_id LIMIT 1");
    if ($sale_result && $sale_result->num_rows > 0) {
        $last_sale = $sale_result->fetch_assoc();
    }

    $items_result = $conn->query("SELECT * FROM sale_items WHERE sale_id = $sale_id");
    $sale_remarks = []; // Array to collect all remarks from sale items
    while ($item = $items_result->fetch_assoc()) {
        $last_items[] = $item;
        // Collect remarks if they exist
        if (!empty($item['remarks'])) {
            $sale_remarks[] = $item['remarks'];
        }
    }
}

// Load print settings
$print_customer_name = true; // default
$print_customer_number = true; // default  
$print_customer_address = true; // default
$print_datetime = true; // default
$print_remarks = true; // default

// Load dealer branding setting
$dealer_branding = 'IT Resources | 📞 0311-391-7777'; // default
$dealer_result = $conn->query("SELECT value FROM settings WHERE code = 'dealer_branding' AND is_active = 1 LIMIT 1");
if ($dealer_result && $dealer_row = $dealer_result->fetch_assoc()) {
    $dealer_branding = $dealer_row['value'];
}

$result = $conn->query("SELECT code, value FROM settings WHERE code IN ('print_cus_name', 'print_cus_number', 'print_cus_address', 'print_datetime', 'print_remarks') AND is_active = 1");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        switch ($row['code']) {
            case 'print_cus_name':
                $print_customer_name = $row['value'] === '1';
                break;
            case 'print_cus_number':
                $print_customer_number = $row['value'] === '1';
                break;
            case 'print_cus_address':
                $print_customer_address = $row['value'] === '1';
                break;
            case 'print_datetime':
                $print_datetime = $row['value'] === '1';
                break;
            case 'print_remarks':
                $print_remarks = $row['value'] === '1';
                break;
        }
    }
}

$receipt_logo_width = 100; // default
$result = $conn->query("SELECT value FROM settings WHERE code = 'receipt_logo_width' AND is_active = 1 LIMIT 1");
if ($result && $row = $result->fetch_assoc()) {
    $receipt_logo_width = intval($row['value']);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Receipt</title>
    <style>
body {
    font-family: Arial, sans-serif;
    font-size: <?= $receipt_font_size ?>px;
    margin: 0;
    padding: 0;
    background: #fff;
}

.receipt-wrapper {
    max-width: 80mm;
    margin: 0;
    padding: 5px;
    border: 0.5px solid #444;
    box-sizing: border-box;
}

/* A4 Print Layout */
.a4-layout .receipt-wrapper {
    max-width: 210mm;
    width: 100%;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #ccc;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

.a4-layout table {
    font-size: 14px;
}

.a4-layout td, .a4-layout th {
    padding: 8px 12px;
    font-size: 14px;
}

.a4-layout .summary-table {
    max-width: 400px;
}

.a4-layout .summary-table td {
    padding: 6px 0;
}

.a4-layout .summary-table .total {
    font-size: 16px;
}

h6, p {
    margin: 0;
    padding: 0;
    font-size: <?= $receipt_font_size ?>px;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
    border: 0.5px solid #444;
}

td, th {
    padding: 6px;
    font-size: <?= $receipt_font_size ?>px;
    border: 0.5px solid #444;
}

.text-end {
    text-align: right;
}

.center {
    text-align: center;
}

.logo {
    margin-bottom: 5px;
}

.barcode-img {
    margin-top: 10px;
    max-width: 150px;
}

hr {
    border: 0.5px dashed #666;
    margin: 8px 0;
}


.summary-table {
    width: 100%;
    max-width: 300px;
    margin-left: auto;
    margin-top: 10px;
    border: none;
    font-size: <?= $receipt_font_size ?>px;
}

.summary-table td {
    padding: 4px 0;
    border: none;
   border-bottom: 1px solid #ccc; /* Underline each row */
}

.summary-table tr:last-child td {
    border-bottom: 2px solid #000; /* Stronger line under Total */
}

.summary-table .label {
    text-align: left;
}

.summary-table .value {
    text-align: right;
}

.summary-table .total {
    font-weight: bold;
    font-size: <?= $receipt_font_size + 1 ?>px;
    padding-top: 6px;
    border-top: 1px solid #ccc;
}

.remarks-section {
    margin: 15px 0;
    padding: 10px;
    background-color: #f9f9f9;
    border-left: 3px solid #007bff;
}


/* ✅ Print-specific layout fix for thermal printers */
@media print {
    /* Default thermal printer settings */
    @page {
        margin: 2mm;
        size: 80mm auto;
    }

    body {
        margin: 0;
        padding: 0;
        font-size: <?= $receipt_font_size ?>px;
    }

    .receipt-wrapper {
        margin: 0;
        padding: 2mm;
        width: 100%;
        max-width: 80mm;
        box-sizing: border-box;
    }

    td, th, p, h6 {
        font-size: <?= $receipt_font_size + 2 ?>px;
    }

    img {
        max-width: 100%;
        height: auto;
    }

    /* A4 printer detection and styling */
    .a4-layout {
        @page {
            margin: 15mm;
            size: A4;
        }

        body {
            font-size: 12px;
        }

        .receipt-wrapper {
            margin: 0 auto;
            padding: 20px;
            width: 100%;
            max-width: 210mm;
            box-sizing: border-box;
        }

        td, th, p, h6 {
            font-size: 14px;
        }

        .summary-table {
            max-width: 400px;
        }

        .summary-table td {
            padding: 6px 0;
        }

        .summary-table .total {
            font-size: 16px;
        }

        .logo {
            max-width: 150px;
        }

        .barcode-img {
            max-width: 200px;
        }
    }
}




    </style>


</head>
<body>

<div class="receipt-wrapper">

<div class="center">
    <img src="assets/img/branch_logo.png" width="<?= $receipt_logo_width ?>" alt="Logo" class="logo"><br>

    <?php if ($branch_info): ?>
        <h6><?= htmlspecialchars($branch_info['branch_name']) ?></h6>
        <p><?= nl2br(htmlspecialchars($branch_info['branch_address'])) ?></p>

        <?php if (!empty($branch_info['branch_phone'])): ?>
            <p><strong>Phone:</strong> <?= htmlspecialchars($branch_info['branch_phone']) ?></p>
        <?php endif; ?>

        <?php if (!empty($branch_info['ntn'])): ?>
            <p><strong>NTN:</strong> <?= htmlspecialchars($branch_info['ntn']) ?></p>
        <?php endif; ?>

        <?php if (!empty($branch_info['strn'])): ?>
            <p><strong>STRN:</strong> <?= htmlspecialchars($branch_info['strn']) ?></p>
        <?php endif; ?>
    <?php endif; ?>
</div>

<hr>

<?php if (!empty($last_sale)): ?>
    <h6 class="center">Sale Invoice</h6>

    <?php if ($print_customer_name && !empty($last_sale['customer_name'])): ?>
        <p><strong>Name:</strong> <?= htmlspecialchars($last_sale['customer_name']) ?></p>
    <?php endif; ?>

    <?php if ($print_customer_number && !empty($last_sale['phone'])): ?>
        <p><strong>Phone:</strong> <?= htmlspecialchars($last_sale['phone']) ?></p>
    <?php endif; ?>

    <?php if ($print_customer_address && !empty($last_sale['address'])): ?>
        <p><strong>Address:</strong> <?= htmlspecialchars($last_sale['address']) ?></p>
    <?php endif; ?>

    <?php if ($print_customer_address && empty($last_sale['address']) && !empty($last_sale['delivery_address'])): ?>
        <p><strong>Delivery Address:</strong> <?= htmlspecialchars($last_sale['delivery_address']) ?></p>
    <?php endif; ?>
    <p><strong>Invoice No:</strong> <?= htmlspecialchars($last_sale['invoice_number']) ?></p>

    <?php if ($fbr_enabled && !empty($last_sale['fbr_invoice_number'])): ?>
        <p><strong>FBR Inv#:</strong> <?= htmlspecialchars($last_sale['fbr_invoice_number']) ?></p>
    <?php endif; ?>

    <?php if ($print_datetime): ?>
        <p><strong>Date:</strong> <?= date('d.m.Y', strtotime($last_sale['sale_date'] ?? $last_sale['created_at'])) ?></p>
        <p><strong>Time:</strong> <?= date('H:i:s', strtotime($last_sale['sale_date'] ?? $last_sale['created_at'])) ?></p>
    <?php endif; ?>

    <?php if (!empty($last_sale['order_mode'])): ?>
        <p><strong>Order Mode:</strong> <?= ucfirst(str_replace('_', ' ', $last_sale['order_mode'])) ?></p>
        <?php if ($last_sale['order_mode'] === 'dine_in' && !empty($last_sale['table_name'])): ?>
            <p><strong>Table:</strong> <?= htmlspecialchars($last_sale['table_name']) ?></p>
        <?php endif; ?>
    <?php endif; ?>

    <hr>

    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Item</th>
                <th>Qty</th>
                <th class="text-end">Total</th>
            </tr>
        </thead>
        <tbody>
        <?php
        $i = 1;
        $subtotal = 0;
        $tax_exempt_total = 0;
        $taxable_total = 0;
        
        foreach ($last_items as $item):
            $line_total = $item['unit_price'] * $item['quantity'];
            $subtotal += $line_total;
            
            // Check if item is tax exempt
            $is_tax_exempt = false;
            if (!empty($item['tax_type']) && $item['tax_type'] === 'nil') {
                $is_tax_exempt = true;
                $tax_exempt_total += $line_total;
            } else {
                $taxable_total += $line_total;
            }
        ?>
            <tr>
                <td><?= $i++ ?>.</td>
                <td>
                    <?= htmlspecialchars($item['item_name']) ?>
                    <?php if ($is_tax_exempt): ?>
                        <br><small class="text-muted">(Tax Exempt)</small>
                    <?php endif; ?>
                </td>
                <td><?= $item['quantity'] ?></td>
                <td class="text-end">Rs <?= number_format($line_total, 2) ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <hr>
    <table class="summary-table">
    <tr>
        <td class="label">Subtotal</td>
        <td class="value">Rs <?= number_format($last_sale['total_amount'] - $last_sale['tax_amount'], 2) ?></td>
    </tr>
    <tr>
        <td>Discount :</td>
        <td class="text-end">
            <?php
            if (!empty($last_sale['discount_type']) && $last_sale['discount_type'] === 'percent') {
                echo number_format($last_sale['discount_value'], 2) . '%';
            } elseif (!empty($last_sale['discount_type']) && $last_sale['discount_type'] === 'fixed') {
                echo 'Rs ' . number_format($last_sale['discount_value'], 2);
            } else {
                echo 'Rs ' . number_format($last_sale['discount_amount'] ?? 0, 2);
            }
            ?>
            (Rs <?= number_format($last_sale['discount_amount'] ?? 0, 2) ?>)
        </td>
    </tr>
    <?php if (!empty($last_sale['delivery_charges']) && $last_sale['delivery_charges'] > 0): ?>
    <tr>
        <td>Delivery Charges :</td>
        <td class="text-end">Rs <?= number_format($last_sale['delivery_charges'], 2) ?></td>
    </tr>
    <?php endif; ?>
    <tr>
        <td class="label">Payment Method</td>
        <td class="value">
            <?php
            $payment_method = $last_sale['payment_method'] ?? 'cash';
            $payment_display_name = ucfirst($payment_method);
            
            // Get payment method display name from database if available
            if (function_exists('getPaymentMethodDisplayName')) {
                $payment_display_name = getPaymentMethodDisplayName($conn, $payment_method);
            }
            
            // Get payment method tax rate
            $payment_tax_rate = 0;
            $tax_rate_query = $conn->prepare("SELECT tax_rate FROM payment_method_tax_rates WHERE payment_method = ? AND is_active = 1");
            $tax_rate_query->bind_param("s", $payment_method);
            $tax_rate_query->execute();
            $tax_rate_result = $tax_rate_query->get_result();
            if ($tax_rate_row = $tax_rate_result->fetch_assoc()) {
                $payment_tax_rate = floatval($tax_rate_row['tax_rate']);
            }
            $tax_rate_query->close();
            
            // Display payment method with tax rate if applicable
            if ($payment_tax_rate > 0) {
                echo htmlspecialchars($payment_display_name) . ' (' . number_format($payment_tax_rate, 2) . '%)';
            } else {
                echo htmlspecialchars($payment_display_name);
            }
            ?>
        </td>
    </tr>
    <tr>
        <td class="label">Tax</td>
        <td class="value">
            Rs <?= number_format($last_sale['tax_amount'], 2) ?>
            <?php
            // Show tax calculation method and details
            $tax_method = '';
            $tax_result = $conn->query("SELECT value FROM settings WHERE code = 'tax_calculation_method' AND is_active = 1 LIMIT 1");
            if ($tax_result && $tax_row = $tax_result->fetch_assoc()) {
                $tax_method = $tax_row['value'];
            }
            
            if ($tax_method === 'payment_method') {
                $payment_method = $last_sale['payment_method'] ?? 'cash';
                $payment_tax_rate = 0;
                $tax_rate_query = $conn->prepare("SELECT tax_rate FROM payment_method_tax_rates WHERE payment_method = ? AND is_active = 1");
                $tax_rate_query->bind_param("s", $payment_method);
                $tax_rate_query->execute();
                $tax_rate_result = $tax_rate_query->get_result();
                if ($tax_rate_row = $tax_rate_result->fetch_assoc()) {
                    $payment_tax_rate = floatval($tax_rate_row['tax_rate']);
                }
                $tax_rate_query->close();
                
                if ($payment_tax_rate > 0) {
                    echo '<br><small class="text-muted">(' . number_format($payment_tax_rate, 2) . '% on taxable items)</small>';
                }
            }
            
            // Show tax exempt information if applicable
            if ($tax_exempt_total > 0) {
                echo '<br><small class="text-muted">Tax Exempt: Rs ' . number_format($tax_exempt_total, 2) . '</small>';
            }
            ?>
        </td>
    </tr>
    <tr>
        <td class="label total">Total Payable</td>
        <td class="value total">Rs <?= number_format($last_sale['total_amount'], 2) ?></td>
    </tr>
</table>

    <?php if ($print_remarks && !empty($sale_remarks)): ?>
        <hr>
        <div class="remarks-section">
            <p><strong>Remarks:</strong></p>
            <?php foreach ($sale_remarks as $remark): ?>
                <p style="margin: 5px 0; padding-left: 20px;">• <?= htmlspecialchars($remark) ?></p>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>



    <div class="center">
        <?php if ($fbr_enabled && !empty($last_sale['fbr_qr_base64'])): ?>
            <img src="data:image/png;base64,<?= $last_sale['fbr_qr_base64'] ?>" class="barcode-img" alt="FBR QR Code">
        <?php elseif (!empty($last_sale['fbr_qr_filename'])): ?>
            <img src="uploads/qr/<?= htmlspecialchars($last_sale['fbr_qr_filename']) ?>" class="barcode-img" alt="FBR QR Code">
        <?php endif; ?>

        <?php 
        // KPRA QR Code
        $kpra_enabled = false;
        $kpra_result = $conn->query("SELECT is_enabled FROM kpra_config LIMIT 1");
        if ($kpra_result && $kpra_row = $kpra_result->fetch_assoc()) {
            $kpra_enabled = intval($kpra_row['is_enabled']) === 1;
        }
        
        if ($kpra_enabled && !empty($last_sale['kpra_qr_code_url'])): 
            include 'kpra_save_sale.php';
            $kpra_config = mysqli_fetch_assoc(mysqli_query($conn, "SELECT business_id FROM kpra_config LIMIT 1"));
            $business_id = $kpra_config['business_id'] ?? '';
            $qr_image_url = generate_kpra_qr_code_image($last_sale['invoice_number'], $business_id);
        ?>
            <div style="margin-top: 10px;">
                <img src="<?= $qr_image_url ?>" class="barcode-img" alt="KPRA QR Code" style="width: 100px; height: 100px;">
                <p style="font-size: 10px; margin: 5px 0;">Scan to verify with KPRA</p>
            </div>
        <?php endif; ?>

        <p>Sale #<?= $last_sale['id'] ?></p>
        <p>Thanks for your business!</p>

   <div style="margin-top: 10px; font-size: 11px; text-align: center; color: #666; border-top: 1px solid #eee; padding-top: 8px;">
        <p style="margin: 0;"><strong>ITR POS by:</strong> <?= htmlspecialchars($dealer_branding) ?></p>
    </div>


    <script>
        function detectPrintDestination() {
            // Check if the browser supports media queries for print
            const mediaQuery = window.matchMedia('print');
            
            // Function to apply layout based on detected printer type
            function applyLayout(isA4) {
                const body = document.body;
                const receiptWrapper = document.querySelector('.receipt-wrapper');
                
                if (isA4) {
                    body.classList.add('a4-layout');
                    console.log('A4 printer detected - applying A4 layout');
                } else {
                    body.classList.remove('a4-layout');
                    console.log('Thermal printer detected - applying thermal layout');
                }
            }
            
            // Try to detect printer type through various methods
            function detectPrinterType() {
                // Method 1: Check for A4 paper size in print media query
                const a4MediaQuery = window.matchMedia('(min-width: 210mm)');
                if (a4MediaQuery.matches) {
                    return 'a4';
                }
                
                // Method 2: Check window dimensions (A4 printers typically have larger viewport)
                if (window.innerWidth > 1000 || window.innerHeight > 1000) {
                    return 'a4';
                }
                
                // Method 3: Check for specific A4 printer indicators
                const userAgent = navigator.userAgent.toLowerCase();
                if (userAgent.includes('pdf') || userAgent.includes('print')) {
                    return 'a4';
                }
                
                // Method 4: Check if page is being printed to PDF or larger format
                if (window.matchMedia('print').matches) {
                    // If we're in print mode, try to detect based on available space
                    const printWidth = window.innerWidth;
                    if (printWidth > 800) {
                        return 'a4';
                    }
                }
                
                // Method 5: Check for common A4 printer names in navigator
                if (typeof navigator !== 'undefined' && navigator.userAgent) {
                    const printerKeywords = ['pdf', 'a4', 'laser', 'inkjet', 'office'];
                    const hasPrinterKeyword = printerKeywords.some(keyword => 
                        navigator.userAgent.toLowerCase().includes(keyword)
                    );
                    if (hasPrinterKeyword) {
                        return 'a4';
                    }
                }
                
                return 'thermal';
            }
            
            // Initial detection
            const printerType = detectPrinterType();
            applyLayout(printerType === 'a4');
            
            // Listen for print events to re-detect
            window.addEventListener('beforeprint', function() {
                const newPrinterType = detectPrinterType();
                applyLayout(newPrinterType === 'a4');
            });
            
            // Listen for media query changes
            mediaQuery.addListener(function(mq) {
                if (mq.matches) {
                    const newPrinterType = detectPrinterType();
                    applyLayout(newPrinterType === 'a4');
                }
            });
            
            // Add a manual toggle for testing
            window.toggleLayout = function() {
                const body = document.body;
                const isA4 = body.classList.contains('a4-layout');
                applyLayout(!isA4);
                updateLayoutIndicator();
            };
            
            // Add layout indicator for debugging
            function updateLayoutIndicator() {
                const indicator = document.getElementById('layout-indicator');
                if (indicator) {
                    const isA4 = document.body.classList.contains('a4-layout');
                    indicator.textContent = isA4 ? 'A4 Layout' : 'Thermal Layout';
                    indicator.className = isA4 ? 'badge bg-primary' : 'badge bg-secondary';
                }
            }
            
            // Create layout indicator if in debug mode
            if (window.location.search.includes('debug=1')) {
                const indicator = document.createElement('div');
                indicator.id = 'layout-indicator';
                indicator.style.position = 'fixed';
                indicator.style.top = '10px';
                indicator.style.right = '10px';
                indicator.style.zIndex = '9999';
                indicator.className = 'badge bg-secondary';
                indicator.textContent = 'Thermal Layout';
                indicator.onclick = window.toggleLayout;
                indicator.style.cursor = 'pointer';
                indicator.title = 'Click to toggle layout';
                document.body.appendChild(indicator);
                
                // Update indicator on layout change
                const originalApplyLayout = applyLayout;
                applyLayout = function(isA4) {
                    originalApplyLayout(isA4);
                    updateLayoutIndicator();
                };
            }
        }
        
        window.onload = function () {
            // Check for URL parameter to force layout type
            const urlParams = new URLSearchParams(window.location.search);
            const forceLayout = urlParams.get('layout');
            
            if (forceLayout === 'a4') {
                document.body.classList.add('a4-layout');
                console.log('A4 layout forced via URL parameter');
            } else if (forceLayout === 'thermal') {
                document.body.classList.remove('a4-layout');
                console.log('Thermal layout forced via URL parameter');
            } else {
                detectPrintDestination();
            }
            
            // Small delay to ensure layout is applied before printing
            setTimeout(function() {
                window.print();
            }, 100);
        };
    </script>

<?php else: ?>
    <p class="center">No sale data found.</p>
<?php endif; ?>



</body>
</html>

