<?php
include("../db/cn.php");
include("common/tx.php");
ob_start();
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

// Fetch order details from the database
$orderId = isset($_GET['order_id']) ? mysqli_real_escape_string($connection, $_GET['order_id']) : null;
$orderDetails = [];
$outletName = $loginUser = $userRole = $outletAddress = $dateTime = $totalAmount = $paidBy = $customerName = $customerPhone = $discountedAmount = $discounted = $discountPer = $cashAmount = $changeAmount = $taxAmount = null;

if ($orderId) {
    $query = "SELECT * FROM log_user_sales WHERE order_id = '$orderId'";
    $result = mysqli_query($connection, $query);

    if ($result && mysqli_num_rows($result) > 0) {
        $orderDetails = mysqli_fetch_all($result, MYSQLI_ASSOC);
        $order = $orderDetails[0];
        $outletName = $order['outlet_name'];
        $loginUser = $order['login_user'];
        $userRole = $order['user_role'];
        $outletAddress = $order['outlet_address'];
        $dateTime = $order['date_time'];
        $totalAmount = floatval($order['net_amount']);
        $paidBy = $order['paid_by'];
        $customerName = $order['customer_name'];
        $customerPhone = $order['customer_phone'];
        $discountedAmount = floatval($order['discount_amount']);
        $discounted = floatval($order['discounted']);
        $discountPer = $order['discount_per'];
        $cashAmount = floatval($order['cash_amount']);
        $changeAmount = floatval($order['change_amount']);
        $taxAmount = $order['tax_amount'];
        $pre = floatval($order['pre_amount']);
        $close = floatval($order['grand_amount']);
    }
}

$content = ob_get_clean();

// Handle exit and update customer balance
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['exit'])) {
    if (!empty($customerName) && $customerName != 'walkin') {
        $checkQuery = "SELECT 1 FROM creditor_closing WHERE creditor_name = '$customerName' LIMIT 1";
        $checkResult = mysqli_query($connection, $checkQuery);

        if (mysqli_num_rows($checkResult) > 0) {
            $updateQuery = "UPDATE creditor_closing SET remain_balance = $changeAmount WHERE creditor_name = '$customerName'";
            $updateResult = mysqli_query($connection, $updateQuery);
        } else {
            $insertQuery = "INSERT INTO creditor_closing (
                creditor_name, opening_cash, credit_sales, credit_recieved,
                remain_balance, date_time, login_user, user_role,
                outlet_name, outlet_address
            ) VALUES (
                '$customerName', 0, 0, 0, $changeAmount, NOW(), '$userName', '$userRole', '$outlet_name', '$outlet_address'
            )";
            $insertResult = mysqli_query($connection, $insertQuery);
        }
    }
    header("Location: mainpos.php");
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Thermal Receipt | <?php echo $tx; ?></title>
    <style>
        /* Thermal Receipt Styles - 80mm width */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            background: #e8ecf1;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
        }
        
        /* Receipt Container - 80mm width */
        .receipt {
            width: 80mm;
            max-width: 80mm;
            background: white;
            margin: 0 auto;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }
        
        /* Print Styles - Thermal Printer */
        @media print {
            body {
                background: white;
                padding: 0;
                margin: 0;
            }
            .receipt {
                width: 100%;
                max-width: 100%;
                box-shadow: none;
                margin: 0;
                padding: 0;
            }
            .no-print {
                display: none !important;
            }
            @page {
                size: 80mm auto;
                margin: 0mm;
            }
            .receipt-content {
                padding: 2mm 3mm;
            }
        }
        
        .receipt-content {
            padding: 8px 8px;
        }
        
        /* Header Styles */
        .text-center {
            text-align: center;
        }
        
        .text-left {
            text-align: left;
        }
        
        .text-right {
            text-align: right;
        }
        
        .shop-name {
            font-size: 14px;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 5px;
        }
        
        .shop-address {
            font-size: 9px;
            line-height: 1.3;
            margin-bottom: 5px;
        }
        
        .shop-contact {
            font-size: 9px;
            font-weight: bold;
            margin-bottom: 3px;
        }
        
        .divider {
            border-top: 1px dashed #000;
            margin: 6px 0;
        }
        
        .divider-double {
            border-top: 2px solid #000;
            margin: 6px 0;
        }
        
        .divider-dotted {
            border-top: 1px dotted #000;
            margin: 5px 0;
        }
        
        /* Info Row */
        .info-row {
            display: flex;
            justify-content: space-between;
            font-size: 9px;
            margin-bottom: 3px;
            font-family: 'Courier New', monospace;
        }
        
        .info-label {
            font-weight: bold;
        }
        
        /* Items Table */
        .items-header {
            display: flex;
            font-size: 9px;
            font-weight: bold;
            border-bottom: 1px dotted #000;
            padding-bottom: 4px;
            margin-bottom: 4px;
            font-family: 'Courier New', monospace;
        }
        
        .item-row {
            display: flex;
            font-size: 9px;
            padding: 3px 0;
            border-bottom: 1px dotted #eee;
            font-family: 'Courier New', monospace;
        }
        
        .col-sr { width: 10%; text-align: center; }
        .col-product { width: 40%; text-align: left; }
        .col-qty { width: 12%; text-align: center; }
        .col-price { width: 15%; text-align: right; }
        .col-discount { width: 10%; text-align: right; }
        .col-total { width: 13%; text-align: right; }
        
        .product-name {
            font-size: 8px;
            word-break: break-word;
            white-space: normal;
            line-height: 1.2;
        }
        
        /* Totals */
        .total-row {
            display: flex;
            justify-content: space-between;
            font-size: 9px;
            margin-bottom: 4px;
            font-family: 'Courier New', monospace;
        }
        
        .total-label {
            font-weight: bold;
        }
        
        .total-amount {
            font-weight: bold;
        }
        
        .grand-total {
            font-size: 11px;
            font-weight: bold;
            border-top: 1px dashed #000;
            margin-top: 5px;
            padding-top: 5px;
        }
        
        /* Footer */
        .thankyou {
            font-size: 11px;
            font-weight: bold;
            text-align: center;
            margin: 10px 0 5px;
        }
        
        .footer-note {
            font-size: 7px;
            text-align: center;
            color: #666;
            line-height: 1.3;
        }
        
        .exchange-policy {
            font-size: 7px;
            margin-top: 8px;
            padding: 5px;
            background: #f9f9f9;
            border: 1px dotted #ccc;
        }
        
        .exchange-policy p {
            margin: 2px 0;
        }
        
        .exchange-header {
            font-weight: bold;
            margin-bottom: 3px;
        }
        
        /* Buttons */
        .button-group {
            padding: 12px;
            background: #f8f9fc;
            border-top: 1px solid #e5e7eb;
            display: flex;
            gap: 10px;
            justify-content: center;
        }
        
        .btn-print, .btn-exit {
            padding: 8px 16px;
            border: none;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 600;
            cursor: pointer;
            font-family: 'Quicksand', sans-serif;
        }
        
        .btn-print {
            background: #0A4657;
            color: white;
        }
        
        .btn-print:hover {
            background: #063544;
        }
        
        .btn-exit {
            background: #e5e7eb;
            color: #333;
        }
        
        .btn-exit:hover {
            background: #d1d5db;
        }
        
        /* Barcode */
        .barcode {
            text-align: center;
            font-family: monospace;
            font-size: 10px;
            letter-spacing: 1px;
            margin: 8px 0;
        }
        
        /* Signature Line */
        .signature {
            font-size: 8px;
            text-align: center;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px dotted #000;
        }
        
        /* Payment Badge */
        .payment-badge {
            display: inline-block;
            padding: 2px 6px;
            background: #f0fdf4;
            border-radius: 4px;
            font-size: 8px;
        }
    </style>
</head>
<body>
<div class="receipt">
    <div class="receipt-content">
        <!-- Header Section -->
        <div class="text-center">
            <div class="shop-name"><?php echo $tx; ?></div>
           <div class="shop-address">
               Main Patang Chok 
            </div>
            <div class="shop-contact">
               M.Munsif : 03397788996 | Basit : 03190097393
            </div>
            <div class="divider"></div>
        </div>
        
        <!-- Invoice Info -->
        <div class="info-row">
            <span class="info-label">Invoice #:</span>
            <span><?php echo $orderId; ?></span>
        </div>
        <div class="info-row">
            <span class="info-label">Date:</span>
            <span><?php echo date('d-m-Y h:i A', strtotime($dateTime)); ?></span>
        </div>
        <div class="info-row">
            <span class="info-label">Cashier:</span>
            <span><?php echo $loginUser; ?></span>
        </div>
        
        <div class="divider-dotted"></div>
        
        <!-- Customer Info -->
        <?php if($customerName && $customerName != 'walkin' && $customerName != ''): ?>
        <div class="info-row">
            <span class="info-label">Customer:</span>
            <span><?php echo htmlspecialchars($customerName); ?></span>
        </div>
        <div class="info-row">
            <span class="info-label">Phone:</span>
            <span><?php echo $customerPhone; ?></span>
        </div>
        <?php else: ?>
        <div class="info-row">
            <span class="info-label">Customer:</span>
            <span>Walk-in Customer</span>
        </div>
        <?php endif; ?>
        
        <div class="info-row">
            <span class="info-label">Payment:</span>
            <span>
                <?php 
                    $paymentIcons = ['cash' => '💰', 'credit' => '💳', 'bank1' => '🏦', 'bank2' => '🏦', 'bank3' => '🏦'];
                    echo ($paymentIcons[$paidBy] ?? '💰') . ' ' . ucfirst($paidBy);
                ?>
            </span>
        </div>
        
        <div class="divider"></div>
        
        <!-- Items Header -->
        <div class="items-header">
            <div class="col-sr">#</div>
            <div class="col-product">Item</div>
            <div class="col-qty">Qty</div>
            <div class="col-price">Price</div>
            <div class="col-discount">Dis%</div>
            <div class="col-total">Total</div>
        </div>
        
        <!-- Items List -->
        <?php $sr = 1; ?>
        <?php foreach ($orderDetails as $order): ?>
        <div class="item-row">
            <div class="col-sr"><?php echo $sr++; ?></div>
            <div class="col-product">
                <div class="product-name"><?php echo htmlspecialchars($order['product_name']); ?></div>
            </div>
            <div class="col-qty"><?php echo $order['product_quantity']; ?></div>
            <div class="col-price"><?php echo number_format(floatval($order['product_price']), 0); ?></div>
            <div class="col-discount"><?php echo floatval($order['discount']); ?>%</div>
            <div class="col-total"><?php echo number_format(floatval($order['net_amount']), 0); ?></div>
        </div>
        <?php endforeach; ?>
        
        <div class="divider"></div>
        
        <!-- Calculate totals -->
        <?php
        $subTotal = 0;
        foreach ($orderDetails as $item) {
            $subTotal += floatval($item['product_total']);
        }
        ?>
        
        <!-- Totals Section -->
        <div class="total-row">
            <span class="total-label">Subtotal:</span>
            <span>Rs. <?php echo number_format($subTotal, 0); ?>/-</span>
        </div>
        
        <?php if($discounted > 0): ?>
        <div class="total-row">
            <span class="total-label">Discount:</span>
            <span>- Rs. <?php echo number_format($discounted, 0); ?>/-</span>
        </div>
        <?php endif; ?>
        
        <div class="total-row">
            <span class="total-label">Total Amount:</span>
            <span class="total-amount">Rs. <?php echo number_format($discountedAmount, 0); ?>/-</span>
        </div>
        
        <?php if($pre > 0): ?>
        <div class="total-row">
            <span class="total-label">Previous Due:</span>
            <span>Rs. <?php echo number_format($pre, 0); ?>/-</span>
        </div>
        <?php endif; ?>
        
        <div class="total-row grand-total">
            <span class="total-label">GRAND TOTAL:</span>
            <span>Rs. <?php echo number_format($close, 0); ?>/-</span>
        </div>
        
        <?php if($paidBy == 'cash' && $cashAmount > 0): ?>
        <div class="total-row">
            <span class="total-label">Cash Received:</span>
            <span>Rs. <?php echo number_format($cashAmount, 0); ?>/-</span>
        </div>
        <div class="total-row">
            <span class="total-label">Change:</span>
            <span>Rs. <?php echo number_format(abs($changeAmount), 0); ?>/-</span>
        </div>
        <?php endif; ?>
        
        <div class="divider-double"></div>
        
        <!-- Barcode -->
        <div class="barcode">
            * <?php echo $orderId; ?> *
        </div>
        
        <!-- Exchange Policy -->
        <div class="exchange-policy">
            <div class="exchange-header">📋 Exchange Policy:</div>
            <p>1. Exchanges accepted within 7 days</p>
            <p>2. Original condition with tags attached</p>
            <p>3. Valid receipt required for exchange</p>
        </div>
        
        <!-- Footer -->
        <div class="thankyou">
            ✨ THANK YOU! ✨
        </div>
        <div class="footer-note">
            This is a computer generated invoice<br>
            No signature required
        </div>
        
        <div class="signature">
            Authorized Signature
        </div>
    </div>
    
    <!-- Buttons - Hidden when printing -->
    <div class="button-group no-print">
        <button class="btn-print" onclick="window.print();">
            🖨️ Print Receipt
        </button>
        <form method="post" style="display:inline;">
            <button type="submit" name="exit" class="btn-exit">
                ✖️ Exit
            </button>
        </form>
    </div>
</div>

<!-- Print Scripts -->
<script>
// Handle print events
window.onbeforeprint = function() {
    var buttons = document.querySelectorAll('.button-group');
    buttons.forEach(function(btn) {
        btn.style.display = 'none';
    });
}

window.onafterprint = function() {
    var buttons = document.querySelectorAll('.button-group');
    buttons.forEach(function(btn) {
        btn.style.display = 'flex';
    });
}

// Keyboard shortcut for print (Ctrl+P)
document.addEventListener('keydown', function(e) {
    if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
        e.preventDefault();
        window.print();
    }
});

// Auto print on page load (optional - uncomment to enable)
// window.onload = function() {
//     setTimeout(function() {
//         window.print();
//     }, 500);
// }
</script>

</body>
</html>