<?php
session_start();
include_once('../includes/config.php');

// Load receipt configuration
$receiptConfig = include('../includes/receipt-config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Get sale ID
$saleId = isset($_GET['sale_id']) ? (int)$_GET['sale_id'] : 0;

if (!$saleId) {
    echo json_encode(['success' => false, 'message' => 'Sale ID required']);
    exit();
}

try {
    // Get sale details with customer info
    $saleQuery = "
        SELECT s.*, c.CustomerName, c.Mobile, c.Area, c.CustomerType,
               u.FullName as CashierFullName
        FROM tblpossales s
        LEFT JOIN tblcustomers c ON s.CustomerID = c.ID
        LEFT JOIN tblusers u ON s.CashierID = u.ID
        WHERE s.ID = ?
    ";
    
    $stmt = $dbh->prepare($saleQuery);
    $stmt->execute([$saleId]);
    $sale = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$sale) {
        echo json_encode(['success' => false, 'message' => 'Sale not found']);
        exit();
    }
    
    // Calculate customer balances
    $customerId = $sale['CustomerID'];
    $saleDate = $sale['SaleDate'];
    $saleAmount = $sale['TotalAmount'];
    $paidAmount = $sale['PaidAmount'];
    $balanceAmount = $sale['BalanceAmount'];
    
    // Get old balance (before this sale)
    $oldBalanceQuery = "
        SELECT 
            COALESCE(SUM(CASE WHEN TransactionType = 'Debit' THEN Amount ELSE 0 END), 0) - 
            COALESCE(SUM(CASE WHEN TransactionType = 'Credit' THEN Amount ELSE 0 END), 0) as old_balance
        FROM tblcustomerpayments 
        WHERE CustomerID = ? 
        AND TransactionDate < ? 
        AND Status = 'Completed'
    ";
    
    $stmt = $dbh->prepare($oldBalanceQuery);
    $stmt->execute([$customerId, $saleDate]);
    $oldBalanceResult = $stmt->fetch(PDO::FETCH_ASSOC);
    $oldBalance = $oldBalanceResult['old_balance'] ?? 0;
    
    // Get current outstanding (after this sale)
    $outstandingQuery = "
        SELECT 
            COALESCE(SUM(CASE WHEN TransactionType = 'Debit' THEN Amount ELSE 0 END), 0) - 
            COALESCE(SUM(CASE WHEN TransactionType = 'Credit' THEN Amount ELSE 0 END), 0) as current_outstanding
        FROM tblcustomerpayments 
        WHERE CustomerID = ? 
        AND Status = 'Completed'
    ";
    
    $stmt = $dbh->prepare($outstandingQuery);
    $stmt->execute([$customerId]);
    $outstandingResult = $stmt->fetch(PDO::FETCH_ASSOC);
    $currentOutstanding = $outstandingResult['current_outstanding'] ?? 0;
    
    // Add balance information to sale data
    $sale['OldBalance'] = $oldBalance;
    $sale['BillBalance'] = $balanceAmount; // This sale's remaining balance
    $sale['CurrentOutstanding'] = $currentOutstanding; // Total outstanding after this sale
    
    // Get sale items
    $itemsQuery = "
        SELECT si.*, rb.RiceBagName, rb.Brand, rb.ManufactureType
        FROM tblpossaleitems si
        LEFT JOIN tblricebags rb ON si.ProductID = rb.ID
        WHERE si.SaleID = ?
        ORDER BY si.ID
    ";
    
    $stmt = $dbh->prepare($itemsQuery);
    $stmt->execute([$saleId]);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Generate receipt HTML
    $receiptHtml = generateReceiptHtml($sale, $items, $receiptConfig);
    
    echo json_encode([
        'success' => true,
        'data' => [
            'html' => $receiptHtml,
            'sale_number' => $sale['SaleNumber'],
            'total_amount' => $sale['TotalAmount']
        ]
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error generating receipt: ' . $e->getMessage()
    ]);
}

function generateReceiptHtml($sale, $items, $config) {
    $business = $config['business'];
    $receipt = $config['receipt'];
    $printer = $config['printer'];
    $features = $config['features'];
    $formatting = $config['formatting'];
    
    $receiptHtml = '
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Receipt - ' . htmlspecialchars($sale['SaleNumber']) . '</title>
        <style>
            /* 2-inch thermal receipt styles */
            @media print {
                @page {
                    size: ' . $printer['width_mm'] . 'mm auto;
                    margin: 0;
                }
                body { margin: 0; }
            }
            
            body {
                font-family: "Courier New", monospace;
                font-size: ' . $printer['font_size'] . 'px;
                line-height: ' . $printer['line_height'] . ';
                margin: 0;
                padding: ' . $printer['margin_mm'] . 'mm;
                width: ' . ($printer['width_mm'] - ($printer['margin_mm'] * 2)) . 'mm;
                background: white;
                color: black;
            }
            
            .receipt {
                width: 100%;
                max-width: ' . ($printer['width_mm'] - ($printer['margin_mm'] * 2)) . 'mm;
            }
            
            .header {
                text-align: center;
                border-bottom: 1px dashed #000;
                padding-bottom: 3px;
                margin-bottom: 3px;
            }
            
            .company-name {
                font-weight: bold;
                font-size: ' . ($printer['font_size'] + 1) . 'px;
                margin-bottom: 1px;
            }
            
            .company-tagline {
                font-size: ' . ($printer['font_size'] - 2) . 'px;
                margin-bottom: 1px;
            }
            
            .receipt-title {
                font-weight: bold;
                font-size: ' . ($printer['font_size'] - 1) . 'px;
                margin: 2px 0;
            }
            
            .sale-info {
                font-size: 9px;
                margin-bottom: 3px;
                border-bottom: 1px dashed #000;
                padding-bottom: 3px;
            }
            
            .info-row {
                display: flex;
                justify-content: space-between;
                margin-bottom: 1px;
            }
            
            .customer-info {
                background: #f8f8f8;
                padding: 2px;
                margin-bottom: 3px;
                border: 1px solid #ddd;
                font-size: 9px;
            }
            
            .items-section {
                margin-bottom: 3px;
            }
            
            .item {
                margin-bottom: 2px;
                font-size: 9px;
            }
            
            .item-name {
                font-weight: bold;
                word-wrap: break-word;
                line-height: 1.1;
            }
            
            .item-details {
                display: flex;
                justify-content: space-between;
                margin-top: 1px;
            }
            
            .item-qty-rate {
                font-size: 8px;
            }
            
            .item-total {
                font-weight: bold;
            }
            
            .separator {
                border-top: 1px dashed #000;
                margin: 3px 0;
            }
            
            .totals {
                font-size: 9px;
            }
            
            .total-row {
                display: flex;
                justify-content: space-between;
                margin-bottom: 1px;
            }
            
            .grand-total {
                font-weight: bold;
                font-size: 11px;
                border-top: 1px solid #000;
                border-bottom: 1px solid #000;
                padding: 2px 0;
                margin: 2px 0;
            }
            
            .payment-info {
                font-size: 9px;
                margin: 3px 0;
            }
            
            .footer {
                text-align: center;
                font-size: 8px;
                margin-top: 5px;
                border-top: 1px dashed #000;
                padding-top: 3px;
            }
            
            .thank-you {
                font-weight: bold;
                margin-bottom: 2px;
            }
            
            .no-print {
                display: none;
            }
            
            @media screen {
                body {
                    background: #f0f0f0;
                    padding: 10mm;
                }
                
                .receipt {
                    background: white;
                    padding: 4mm;
                    box-shadow: 0 0 10px rgba(0,0,0,0.1);
                    margin: 0 auto;
                }
                
                .no-print {
                    display: block;
                    text-align: center;
                    margin: 10px 0;
                }
                
                .print-btn {
                    background: #007185;
                    color: white;
                    border: none;
                    padding: 10px 20px;
                    border-radius: 4px;
                    font-size: 14px;
                    cursor: pointer;
                    margin: 0 5px;
                }
                
                .print-btn:hover {
                    background: #005a6b;
                }
            }
        </style>
    </head>
    <body>
        <div class="no-print">
            <button class="print-btn" onclick="window.print()">🖨️ Print Receipt</button>
            <button class="print-btn" onclick="window.close()" style="background: #666;">❌ Close</button>
        </div>
        
        <div class="receipt">
            <div class="header">
                <div class="company-name">' . htmlspecialchars($business['name']) . '</div>
                <div class="company-tagline">' . htmlspecialchars($business['tagline']) . '</div>';
    
    if (!empty($business['address'])) {
        $receiptHtml .= '<div style="font-size: ' . ($printer['font_size'] - 3) . 'px;">' . htmlspecialchars($business['address']) . '</div>';
    }
    
    if (!empty($business['phone'])) {
        $receiptHtml .= '<div style="font-size: ' . ($printer['font_size'] - 3) . 'px;">📞 ' . htmlspecialchars($business['phone']) . '</div>';
    }
    
    $receiptHtml .= '
                <div class="receipt-title">' . htmlspecialchars($receipt['title']) . '</div>
            </div>
            
            <div class="sale-info">
                <div class="info-row">
                    <span>Receipt#:</span>
                    <span>' . htmlspecialchars($sale['SaleNumber']) . '</span>
                </div>
                <div class="info-row">
                    <span>Date:</span>
                    <span>' . date($formatting['date_format'], strtotime($sale['SaleDate'])) . '</span>
                </div>
                <div class="info-row">
                    <span>Time:</span>
                    <span>' . date($formatting['time_format'], strtotime($sale['SaleTime'])) . '</span>
                </div>';
    
    if ($features['show_cashier_name']) {
        $receiptHtml .= '
                <div class="info-row">
                    <span>Cashier:</span>
                    <span>' . htmlspecialchars($sale['CashierFullName'] ?: $sale['CashierName']) . '</span>
                </div>';
    }
    
    $receiptHtml .= '
            </div>
            
            <div class="customer-info">
                <div><strong>CUSTOMER DETAILS</strong></div>
                <div>' . htmlspecialchars($sale['CustomerName']) . '</div>';
    
    if ($features['show_customer_mobile'] && $sale['Mobile']) {
        $receiptHtml .= '<div>📱 ' . htmlspecialchars($sale['Mobile']) . '</div>';
    }
    
    if ($features['show_customer_area'] && $sale['Area']) {
        $receiptHtml .= '<div>📍 ' . htmlspecialchars($sale['Area']) . '</div>';
    }
    
    if ($features['show_customer_type']) {
        $receiptHtml .= '<div>Type: ' . htmlspecialchars($sale['CustomerType']) . '</div>';
    }
    
    $receiptHtml .= '
            </div>';
    
    // Add customer balance section if enabled
    if ($features['show_customer_balance']) {
        $receiptHtml .= '
            
            <div class="customer-balance" style="background: #f0f8ff; padding: 2px; margin-bottom: 3px; border: 1px solid #b0d4f1; font-size: 9px;">
                <div><strong>ACCOUNT BALANCE</strong></div>
                <div class="info-row">
                    <span>Old Balance:</span>
                    <span>' . $formatting['currency_symbol'] . number_format($sale['OldBalance'], $formatting['decimal_places']) . '</span>
                </div>
                <div class="info-row">
                    <span>This Bill:</span>
                    <span>' . $formatting['currency_symbol'] . number_format($sale['TotalAmount'], $formatting['decimal_places']) . '</span>
                </div>
                <div class="info-row">
                    <span>Bill Balance:</span>
                    <span style="' . ($sale['BillBalance'] > 0 ? 'color: #d13212; font-weight: bold;' : 'color: #007600;') . '">' . $formatting['currency_symbol'] . number_format($sale['BillBalance'], $formatting['decimal_places']) . '</span>
                </div>
                <div class="info-row" style="border-top: 1px solid #b0d4f1; padding-top: 1px; margin-top: 1px;">
                    <span><strong>Total Outstanding:</strong></span>
                    <span style="' . ($sale['CurrentOutstanding'] > 0 ? 'color: #d13212; font-weight: bold;' : 'color: #007600; font-weight: bold;') . '">' . $formatting['currency_symbol'] . number_format($sale['CurrentOutstanding'], $formatting['decimal_places']) . '</span>
                </div>
            </div>';
    }
    
    $receiptHtml .= '
            
            <div class="items-section">';
    
    foreach ($items as $item) {
        $receiptHtml .= '
                <div class="item">
                    <div class="item-name">' . htmlspecialchars($item['ProductName']) . '</div>
                    <div class="item-details">
                        <span class="item-qty-rate">' . number_format($item['Quantity'], 1) . 'kg × ' . $formatting['currency_symbol'] . number_format($item['UnitPrice'], $formatting['decimal_places']) . '</span>
                        <span class="item-total">' . $formatting['currency_symbol'] . number_format($item['LineTotal'], $formatting['decimal_places']) . '</span>
                    </div>
                </div>';
    }
    
    $receiptHtml .= '
            </div>
            
            <div class="separator"></div>
            
            <div class="totals">
                <div class="total-row">
                    <span>Subtotal:</span>
                    <span>' . $formatting['currency_symbol'] . number_format($sale['SubTotal'], $formatting['decimal_places']) . '</span>
                </div>';
    
    if ($sale['DiscountAmount'] > 0) {
        $receiptHtml .= '
                <div class="total-row">
                    <span>Discount:</span>
                    <span>-' . $formatting['currency_symbol'] . number_format($sale['DiscountAmount'], $formatting['decimal_places']) . '</span>
                </div>';
    }
    
    $receiptHtml .= '
                <div class="total-row grand-total">
                    <span><strong>TOTAL:</strong></span>
                    <span><strong>' . $formatting['currency_symbol'] . number_format($sale['TotalAmount'], $formatting['decimal_places']) . '</strong></span>
                </div>
            </div>
            
            <div class="payment-info">
                <div class="total-row">
                    <span>Payment Method:</span>
                    <span>' . htmlspecialchars($sale['PaymentMethod']) . '</span>
                </div>
                <div class="total-row">
                    <span>Amount Paid:</span>
                    <span>' . $formatting['currency_symbol'] . number_format($sale['PaidAmount'], $formatting['decimal_places']) . '</span>
                </div>';
    
    if ($sale['ChangeAmount'] > 0) {
        $receiptHtml .= '
                <div class="total-row">
                    <span>Change:</span>
                    <span>' . $formatting['currency_symbol'] . number_format($sale['ChangeAmount'], $formatting['decimal_places']) . '</span>
                </div>';
    }
    
    if ($sale['BalanceAmount'] > 0) {
        $receiptHtml .= '
                <div class="total-row" style="background: #ffe6e6; padding: 2px;">
                    <span><strong>Balance Due:</strong></span>
                    <span><strong>' . $formatting['currency_symbol'] . number_format($sale['BalanceAmount'], $formatting['decimal_places']) . '</strong></span>
                </div>';
    }
    
    if ($features['show_reference_number'] && $sale['ReferenceNumber']) {
        $receiptHtml .= '
                <div class="total-row">
                    <span>Reference:</span>
                    <span>' . htmlspecialchars($sale['ReferenceNumber']) . '</span>
                </div>';
    }
    
    $receiptHtml .= '
                <div class="total-row">
                    <span>Status:</span>
                    <span><strong>' . htmlspecialchars($sale['PaymentStatus']) . '</strong></span>
                </div>
            </div>
            
            <div class="footer">
                <div class="thank-you">' . htmlspecialchars($receipt['footer_message']) . '</div>
                <div>' . htmlspecialchars($receipt['footer_submessage']) . '</div>
                <div>──────────────────</div>
                <div style="margin-top: 2px;">' . htmlspecialchars($receipt['footer_tagline']) . '</div>';
    
    if (!empty($receipt['powered_by'])) {
        $receiptHtml .= '<div style="font-size: 7px; margin-top: 2px;">' . htmlspecialchars($receipt['powered_by']) . '</div>';
    }
    
    $receiptHtml .= '
            </div>
        </div>
        
        <script>';
    
    if ($features['auto_print_on_sale']) {
        $receiptHtml .= '
            // Auto-print when opened
            window.onload = function() { window.print(); }';
    } else {
        $receiptHtml .= '
            // Auto-print disabled - user can click print button';
    }
    
    $receiptHtml .= '
            
            // Handle print completion
            window.onafterprint = function() {
                console.log("Receipt printed");
            }
        </script>
    </body>
    </html>';
    
    return $receiptHtml;
}
?>
