
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

date_default_timezone_set('Asia/Colombo');
include '../config.php';

$sale_id = $_GET['id'] ?? 0;

// Get sale details
$stmt = $conn->prepare("
    SELECT s.*, c.name as customer_name, c.phone as customer_phone 
    FROM sales s 
    LEFT JOIN customers c ON s.customer_id = c.id 
    WHERE s.id = ?
");
$stmt->bind_param("i", $sale_id);
$stmt->execute();
$sale = $stmt->get_result()->fetch_assoc();

if (!$sale) {
    echo "Sale not found";
    exit;
}

// Get sale items
$stmt = $conn->prepare("
    SELECT si.*, p.name as product_name 
    FROM sale_items si 
    JOIN products p ON si.product_id = p.id 
    WHERE si.sale_id = ?
");
$stmt->bind_param("i", $sale_id);
$stmt->execute();
$items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get exchange information if this is an exchange receipt
$stmt = $conn->prepare("SELECT * FROM exchange_log WHERE sale_id = ? ORDER BY exchanged_at DESC LIMIT 1");
$stmt->bind_param("i", $sale_id);
$stmt->execute();
$exchange = $stmt->get_result()->fetch_assoc();

// Check if this sale has exchanges - simplified
$is_exchange = false;
if ($exchange) {
    $is_exchange = true;
}

// Get sales officer (if any) associated with this sale via sales_commissions
$stmt = $conn->prepare("SELECT so.name FROM sales_commissions sc JOIN sales_officers so ON sc.sales_officer_id = so.id WHERE sc.sale_id = ? ORDER BY sc.id DESC LIMIT 1");
$stmt->bind_param("i", $sale_id);
$stmt->execute();
$officer_row = $stmt->get_result()->fetch_assoc();
$sales_officer_name = $officer_row['name'] ?? null;
?>
<!DOCTYPE html>
<html>
<head>
    <title>Receipt - Sale #<?= $sale_id ?></title>
    <style>
        body { font-family: 'Courier New', monospace; margin: 20px; }
        .receipt { width: 300px; margin: 0 auto; }
        .header { text-align: center; border-bottom: 2px solid #000; padding-bottom: 10px; }
        .item { display: flex; justify-content: space-between; padding: 2px 0; }
        .total { border-top: 2px solid #000; padding-top: 10px; font-weight: bold; }
        @media print {
            .no-print { display: none; }
            @page { margin: 0; }
            body { margin: 0; }
        }
    </style>
</head>
<body>
    <div class="receipt">
        <div class="header">
                <img src="../products/uploads/dilrukshitext.png" alt="Logo" style="height:180px; display:block; margin:0 auto 0.5em auto;">
            <div style="font-size:1.6em; font-weight:900; text-align:center; letter-spacing:1px; text-transform:uppercase;">Dilrukshi Tex</div>
            <div style="text-align:center; font-size:13px;">
                <span style="font-weight:bold;">Anamaduwa Road, Pallama</span><br>
                <span style="font-weight:bold;">dilrukshitex630@gmail.com</span><br>
                <span style="font-weight:bold;">0713074178, 0767516000, 0767190203 </span>
            </div>
            <hr style="margin:8px 0; border-top:1px solid #000;">
            <div style="display:flex; justify-content:space-between; font-size:12px;">
                <div>
                    <span style="font-weight:bold;">Date</span><br>
                    <span style="font-weight:bold;">Invoice</span>
                </div>
                <div style="text-align:right;">
                    <span style="font-weight:bold;"><?= date('M d, Y') ?></span><br>
                    <span style="font-weight:bold;"><?= str_pad($sale_id, 8, '0', STR_PAD_LEFT) ?></span>
                </div>
                <div style="margin-left:20px;">
                    <span style="font-weight:bold;">Time</span><br>
                    <span style="font-weight:bold;">Cashier</span>
                </div>
                <div style="text-align:right;">
                    <span style="font-weight:bold;"><?= date('h:i:s A') ?></span><br>
                    <span style="font-weight:bold;">Admin User</span>
                    <?php if (!empty($sales_officer_name)): ?>
                        <br><span style="font-weight:bold;">Sales Officer: <?= htmlspecialchars($sales_officer_name) ?></span>
                    <?php endif; ?>
                </div>
            </div>
            
        </div>
        
        <?php if ($sale['customer_name']): ?>
        <div style="font-size:12px; margin:2px 0 4px 0; padding:0;">
            <strong>Customer:</strong> <?= htmlspecialchars($sale['customer_name']) ?>
            <?php if ($sale['customer_phone']): ?> | <strong>Phone:</strong> <?= htmlspecialchars($sale['customer_phone']) ?><?php endif; ?>
        </div>
        <?php endif; ?>
        
    <div style="margin: 4px 0 0 0;">
            <table style="width:100%; font-size:13px; border-collapse:collapse;">
                <thead>
                    <tr style="border-bottom:1px solid #000;">
                        <th style="text-align:left;">Item</th>
                        <th style="text-align:left;">Our Price</th>
                        <th style="text-align:center;">QTY</th>
                        <th style="text-align:right;">Amount</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($items as $item): ?>
                    <tr>
                        <td style="max-width:90px; word-break:break-word; white-space:normal;"> <?= htmlspecialchars($item['product_name']) ?> </td>
                        <td><?= number_format($item['unit_price'], 2) ?></td>
                        <td style="text-align:center;"><?= $item['quantity'] ?></td>
                        <td style="text-align:right;"><?= number_format($item['total_price'], 2) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
    <div class="total" style="margin-top:4px;">
            <?php
            $subtotal = array_sum(array_column($items, 'total_price'));
            ?>
            <div style="display:flex; justify-content:space-between; font-size:13px;">
                <span>Gross Total</span>
                <span><?= number_format($subtotal, 2) ?></span>
            </div>
            <div style="display:flex; justify-content:space-between; font-size:13px;">
                <span>Paid Amount</span>
                <span><?= number_format($sale['paid_amount'], 2) ?></span>
            </div>
            <div style="display:flex; justify-content:space-between; font-size:15px; font-weight:bold;">
                <span>Invoice Amount</span>
                <span><?= number_format($sale['total_amount'], 2) ?></span>
            </div>
            <div style="display:flex; justify-content:space-between; font-size:13px;">
                <span>Balance</span>
                <span><?= number_format($sale['paid_amount'] - $sale['total_amount'], 2) ?></span>
            </div>
        </div>
    <div style="font-size:11px; margin-top:4px;">Sold items: <?= count($items) ?></div>
        
        <div style="text-align: center; margin-top: 8px; border-top: 1px solid #000; padding-top: 4px;">
            <p style="font-weight: bold; font-size: 12px; color: #000; margin:0;">Payment Method: <?= strtoupper($sale['payment_method']) ?></p>
            <p style="font-weight: bold; font-size: 12px; color: #000; margin:0;">Thank You Come Again!</p>
             <p style="font-weight: bold; font-size: 10px; color: #000; margin:0;">භාන්ඩ නැවත මාරු කිරීම සදහා දින 07 ක් ඇතුලත බිල්පත හා බාන්ඩයේ සදහන් ටැග් පත ඉවත් නොකර නැවත ඉදිරිපත් කල යුතුය.</p>
            <div style="border-top: 1px dotted #000; margin-top: 6px; padding-top: 4px; font-size: 10px; color: #000;">
                <p style="margin:0;">System by Ecodez Digital - 0751534972</p>
            </div>
        </div>
    </div>
    
    <div class="no-print" style="text-align: center; margin-top: 20px;">
        <button onclick="window.print()">Print Receipt</button>
        <button onclick="window.close()">Close</button>
    </div>
    
    <script>
        // Auto-print when opened
        window.onload = function() {
            window.print();
        };
        
        // Close window with Enter key
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Enter') {
                window.close();
            }
        });
    </script>
</body>
</html>
