<?php
// Thermal Printer Template (3 inch)
// Updated: 2025-11-05
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');
}

// 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 loyalty points
$saleSql = "SELECT s.*, c.CustomerName, c.CustomerCode, c.Mobile, c.Address, c.City, c.State, c.GSTNumber, c.CurrentBalance, 
            c.LoyaltyPoints, c.TotalPointsEarned, c.TotalPointsRedeemed 
            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 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);

// Calculate totals including MRP sum and GST
$totalMRP = 0;
$totalCGST = 0;
$totalSGST = 0;
$totalIGST = 0;
$totalGSTAmount = 0;

mysqli_data_seek($detailsResult, 0);
while ($item = mysqli_fetch_assoc($detailsResult)) {
    $quantity = floatval($item['Quantity']);
    $mrp = floatval($item['MRP']);
    $totalMRP += ($mrp * $quantity);
    $totalCGST += floatval($item['CGSTAmount']);
    $totalSGST += floatval($item['SGSTAmount']);
    $totalIGST += floatval($item['IGSTAmount']);
    $totalGSTAmount += floatval($item['TotalTaxAmount']);
}

// Reset pointer for item display
mysqli_data_seek($detailsResult, 0);

// Calculate savings (MRP Total - Invoice Total)
$totalInvoiceAmount = floatval($sale['FinalAmount'] ?: $sale['TotalAmount']);
$todaysSavings = $totalMRP - $totalInvoiceAmount;

// Get loyalty points earned for this bill
$billPointsEarned = 0;
$loyaltyPointsQuery = "SELECT Points FROM tblcustomer_loyalty_points 
                       WHERE SaleID = " . intval($sale['ID']) . " 
                       AND TransactionType = 'EARNED' 
                       ORDER BY ID DESC LIMIT 1";
$loyaltyPointsResult = mysqli_query($con, $loyaltyPointsQuery);
if ($loyaltyPointsResult && mysqli_num_rows($loyaltyPointsResult) > 0) {
    $loyaltyData = mysqli_fetch_assoc($loyaltyPointsResult);
    $billPointsEarned = floatval($loyaltyData['Points']);
}

// Get logged-in user name
$loggedInUserName = 'N/A';
if (isset($_SESSION['uid']) && !empty($_SESSION['uid'])) {
    $userQuery = "SELECT FullName FROM tblusers WHERE ID = " . intval($_SESSION['uid']);
    $userResult = mysqli_query($con, $userQuery);
    if ($userResult && mysqli_num_rows($userResult) > 0) {
        $userData = mysqli_fetch_assoc($userResult);
        $loggedInUserName = $userData['FullName'];
    }
}

// Extract invoice number (remove prefix)
$invoiceDisplayNumber = preg_replace('/[^0-9]/', '', $sale['InvoiceNumber']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-t">
    <title>Estimate</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Tamil:wght@400;700&display=swap');
        
        @page { size: 80mm auto; margin: 0; }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: <?php echo $fontSettings['TableBodyFont'] ?? 'Arial'; ?>, 'Noto Sans Tamil', 'Courier New', monospace;
            font-size: <?php echo ($fontSettings['TableBodySize'] ?? 10) * 0.9; ?>px;
            font-weight: <?php echo $fontSettings['TableBodyWeight'] ?? 'normal'; ?>;
            line-height: 1.3;
            color: <?php echo $fontSettings['TableBodyColor'] ?? '#000'; ?>;
            width: 80mm;
            padding: 5mm;
        }
        
        .header {
            text-align: center;
            margin-bottom: 8px;
            border-bottom: 1px dashed #000;
            padding-bottom: 8px;
        }
        
        .header-top {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            margin-bottom: 5px;
        }
        
        .header-top.no-logo {
            justify-content: center;
        }
        
        .header-top.no-logo .company-info {
            text-align: center;
        }
        
        .logo-container {
            width: 40px;
            height: 40px;
            flex-shrink: 0;
        }
        
        .logo-container img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
        
        .company-info {
            flex: 1;
            text-align: center;
        }
        
        .address-info {
            width: 100%;
            text-align: center;
        }
        
        .store-name {
            font-family: <?php echo $fontSettings['CompanyNameFont'] ?? 'Arial'; ?>, 'Noto Sans Tamil', sans-serif;
            font-size: <?php echo ($fontSettings['CompanyNameSize'] ?? 20) * 0.7; ?>px;
            font-weight: <?php echo $fontSettings['CompanyNameWeight'] ?? 'bold'; ?>;
            margin-bottom: 3px;
            color: <?php echo $fontSettings['CompanyNameColor'] ?? '#000'; ?>;
        }
        
        .store-info {
            font-family: <?php echo $fontSettings['AddressFont'] ?? 'Arial'; ?>, 'Noto Sans Tamil', sans-serif;
            font-size: <?php echo ($fontSettings['AddressSize'] ?? 10) * 0.7; ?>px;
            font-weight: <?php echo $fontSettings['AddressWeight'] ?? 'normal'; ?>;
            margin: 1px 0;
            color: <?php echo $fontSettings['AddressColor'] ?? '#000'; ?>;
        }
        
        .bill-title {
            font-family: <?php echo $fontSettings['InvoiceTitleFont'] ?? 'Arial'; ?>, sans-serif;
            font-size: <?php echo ($fontSettings['InvoiceTitleSize'] ?? 14) * 0.8; ?>px;
            font-weight: <?php echo $fontSettings['InvoiceTitleWeight'] ?? 'bold'; ?>;
            text-align: center;
            border-top: 1px dashed #000;
            border-bottom: 1px dashed #000;
            padding: 4px 0;
            margin-bottom: 8px;
        }

        .bill-info {
            font-family: <?php echo $fontSettings['ContactFont'] ?? 'Arial'; ?>, sans-serif;
            margin: 8px 0;
            font-size: <?php echo ($fontSettings['ContactSize'] ?? 10) * 0.8; ?>px;
            font-weight: <?php echo $fontSettings['ContactWeight'] ?? 'normal'; ?>;
            color: <?php echo $fontSettings['ContactColor'] ?? '#000'; ?>;
            border-bottom: 1px dashed #000;
            padding-bottom: 8px;
        }
        
        .bill-info-row { display: flex; justify-content: space-between; margin: 2px 0; }
        
        table {
            font-family: <?php echo $fontSettings['TableBodyFont'] ?? 'Arial'; ?>, sans-serif;
            width: 100%;
            border-collapse: collapse;
            margin: 8px 0;
            font-size: <?php echo ($fontSettings['TableBodySize'] ?? 10) * 0.8; ?>px;
        }
        
        table th {
            font-family: <?php echo $fontSettings['TableHeaderFont'] ?? 'Arial'; ?>, sans-serif;
            background: <?php echo $fontSettings['TableHeaderBgColor'] ?? '#f0f0f0'; ?>;
            border-bottom: 1px solid #000;
            padding: 3px 2px;
            text-align: left;
            font-weight: <?php echo $fontSettings['TableHeaderWeight'] ?? 'bold'; ?>;
            font-size: <?php echo ($fontSettings['TableHeaderSize'] ?? 10) * 0.8; ?>px;
            color: <?php echo $fontSettings['TableHeaderColor'] ?? '#000'; ?>;
        }
        
        table td {
            padding: 3px 2px;
            text-align: left;
            border-bottom: 1px dashed #ddd;
            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; }
        
        .totals {
            margin: 8px 0;
            font-size: 9px;
            border-top: 1px dashed #000;
            padding-top: 5px;
        }
        
        .total-row { 
            display: flex; 
            justify-content: space-between; 
            margin: 2px 0;
            font-size: 10px;
            font-weight: bold;
        }
        
        .grand-total-row {
            display: flex; 
            justify-content: space-between; 
            margin: 4px 0;
            padding: 5px;
            background: #f0f0f0;
            border: 1px solid #000;
            font-size: 14px;
            font-weight: bold;
        }
        
        .footer {
            font-family: <?php echo $fontSettings['FooterFont'] ?? 'Arial'; ?>, sans-serif;
            text-align: center;
            margin-top: 10px;
            border-top: 1px dashed #000;
            padding-top: 8px;
            font-size: <?php echo ($fontSettings['FooterSize'] ?? 11) * 0.8; ?>px;
            font-weight: <?php echo $fontSettings['FooterWeight'] ?? 'normal'; ?>;
            color: <?php echo $fontSettings['FooterColor'] ?? '#000'; ?>;
        }
        
        @media print { body { padding: 3mm; } .no-print { display: none !important; } }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-top<?php echo (empty($storeSettings['StoreLogo1'])) ? ' no-logo' : ''; ?>">
            <?php if ($storeSettings && !empty($storeSettings['StoreLogo1'])): ?>
            <div class="logo-container">
                <img src="../../<?php echo htmlspecialchars($storeSettings['StoreLogo1']); ?>" alt="Logo">
            </div>
            <?php endif; ?>
            <div class="company-info">
                <div class="store-name"><?php echo strtoupper(htmlspecialchars($storeSettings['StoreName'] ?? 'STORE NAME')); ?></div>
            </div>
        </div>
        <div class="address-info">
            <?php if (!empty($storeSettings['Address'])): ?>
            <div class="store-info"><?php echo htmlspecialchars($storeSettings['Address']); ?></div>
            <?php endif; ?>
            <?php if (!empty($storeSettings['City'])): ?>
            <div class="store-info"><?php echo htmlspecialchars($storeSettings['City']); ?><?php echo !empty($storeSettings['Postcode']) ? ' - ' . htmlspecialchars($storeSettings['Postcode']) : ''; ?></div>
            <?php endif; ?>
            <?php if (!empty($storeSettings['Mobile'])): ?>
            <div class="store-info">Ph: <?php echo htmlspecialchars($storeSettings['Mobile']); ?></div>
            <?php endif; ?>
        </div>
    </div>
    <div class="bill-title">ESTIMATE</div>
    <div class="bill-info">
        <div class="bill-info-row">
            <span>Bill: #<?php echo htmlspecialchars($invoiceDisplayNumber); ?></span>
            <span><?php echo date('d-m-Y h:i A', strtotime($sale['SaleDate'])); ?></span>
        </div>
        <div class="bill-info-row">
            <span>👤 <?php echo htmlspecialchars($sale['CustomerName']); ?><?php echo !empty($sale['Mobile']) ? ' - 📱 ' . htmlspecialchars($sale['Mobile']) : ''; ?></span>
        </div>
        <div class="bill-info-row">
            <span>Billed By: <?php echo htmlspecialchars($loggedInUserName); ?></span>
        </div>
    </div>
    <table>
        <thead>
            <tr>
                <th style="width: 5%;">No</th>
                <th style="width: 45%;">Item</th>
                <th style="width: 15%;" class="text-right">Qty</th>
                <th style="width: 15%;" class="text-right">Price</th>
                <th style="width: 20%;" class="text-right">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $sno = 1;
            $totalQuantity = 0;
            mysqli_data_seek($detailsResult, 0);
            while ($item = mysqli_fetch_assoc($detailsResult)): 
                $quantity = floatval($item['Quantity']);
                $rate = floatval($item['Rate']);
                $amount = floatval($item['FinalAmount']);
                $totalQuantity += $quantity;
            ?>
            <tr>
                <td><?php echo $sno; ?></td>
                <td><?php echo htmlspecialchars($item['ProductName']); ?></td>
                <td class="text-right"><?php echo number_format($quantity, 0); ?></td>
                <td class="text-right"><?php echo number_format($rate, 2); ?></td>
                <td class="text-right"><?php echo number_format($amount, 2); ?></td>
            </tr>
            <?php $sno++; endwhile; ?>
        </tbody>
    </table>
    <div class="totals">
        <div class="total-row">
            <span>Total Items: <?php echo ($sno - 1); ?></span>
            <span>Total Qty: <?php echo number_format($totalQuantity, 0); ?></span>
        </div>
    </div>
    
    <div class="grand-total-row">
        <strong>BILL AMOUNT:</strong>
        <strong>Rs <?php echo number_format($totalInvoiceAmount, 2); ?></strong>
    </div>
    
    <div class="footer">
        <div style="margin-bottom: 5px;">Thank You! Visit Again</div>
        <?php if (!empty($storeSettings['StoreWebsite'])): ?>
        <div><?php echo htmlspecialchars($storeSettings['StoreWebsite']); ?></div>
        <?php endif; ?>
    </div>
    <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: 1000;">
        <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'): ?>
            setTimeout(function() {
                window.print();
            }, 500);
            <?php endif; ?>
        });
        
        // After printing, user can navigate back
        window.addEventListener('afterprint', function() {
            setTimeout(function() {
                if (confirm('Print completed. Return to sales page?')) {
                    window.location.href = '../index.php';
                }
            }, 500);
        });
    </script>
</body>
</html>
