<?php
session_start();
require_once '../assets/db_connect.php';

$sale_id = $_GET['id'] ?? 0;
$shop_id = $_SESSION['user']['shop_id'] ?? 0;

if (!$sale_id) {
    die("Invalid sale ID");
}

// Get sale details
$sale_sql = "SELECT s.*, c.name as customer_name, c.phone as customer_phone,
                    sh.name as shop_name, sh.address as shop_address,
                    u.fullname as cashier_name
             FROM sales s
             LEFT JOIN customers c ON s.customer_id = c.id
             LEFT JOIN shops sh ON s.shop_id = sh.id
             LEFT JOIN users u ON s.created_by = u.id
             WHERE s.id = ? AND s.shop_id = ?";
$sale_stmt = $pdo->prepare($sale_sql);
$sale_stmt->execute([$sale_id, $shop_id]);
$sale = $sale_stmt->fetch(PDO::FETCH_ASSOC);

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

// Get sale lines
$lines_sql = "SELECT sl.*, p.name as product_name, p.sku,
                     pb.batch_no, pb.expiry_date
              FROM sale_lines sl
              JOIN products p ON sl.product_id = p.id
              JOIN product_batches pb ON sl.batch_id = pb.id
              WHERE sl.sale_id = ?
              ORDER BY sl.id";
$lines_stmt = $pdo->prepare($lines_sql);
$lines_stmt->execute([$sale_id]);
$lines = $lines_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get payments
$payment_sql = "SELECT * FROM payments WHERE sale_id = ? ORDER BY paid_at";
$payment_stmt = $pdo->prepare($payment_sql);
$payment_stmt->execute([$sale_id]);
$payments = $payment_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Receipt - <?= htmlspecialchars($sale['invoice_no']) ?></title>
    <style>
        @media print {
            body { margin: 0; padding: 0; }
            .no-print { display: none !important; }
            .receipt { width: 80mm; margin: 0 auto; }
        }
        
        body {
            font-family: 'Courier New', monospace;
            max-width: 80mm;
            margin: 0 auto;
            padding: 10px;
            background: white;
        }
        
        .receipt {
            border: 1px solid #ccc;
            padding: 15px;
            background: white;
        }
        
        .header {
            text-align: center;
            border-bottom: 2px dashed #000;
            padding-bottom: 10px;
            margin-bottom: 15px;
        }
        
        .header h2 {
            margin: 0;
            font-size: 18px;
            font-weight: bold;
        }
        
        .header p {
            margin: 3px 0;
            font-size: 12px;
        }
        
        .info {
            margin-bottom: 15px;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            margin: 3px 0;
            font-size: 13px;
        }
        
        .items {
            width: 100%;
            border-collapse: collapse;
            margin: 10px 0;
        }
        
        .items th {
            border-bottom: 2px solid #000;
            padding: 5px 0;
            text-align: left;
            font-size: 12px;
        }
        
        .items td {
            padding: 4px 0;
            font-size: 12px;
        }
        
        .items .qty {
            width: 15%;
            text-align: center;
        }
        
        .items .desc {
            width: 45%;
        }
        
        .items .price {
            width: 20%;
            text-align: right;
        }
        
        .items .total {
            width: 20%;
            text-align: right;
        }
        
        .totals {
            margin-top: 15px;
            border-top: 2px dashed #000;
            padding-top: 10px;
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            margin: 5px 0;
            font-size: 13px;
        }
        
        .total-row.grand {
            font-weight: bold;
            font-size: 14px;
            border-top: 1px solid #000;
            padding-top: 8px;
            margin-top: 8px;
        }
        
        .payments {
            margin-top: 15px;
            font-size: 12px;
        }
        
        .payment-row {
            display: flex;
            justify-content: space-between;
            margin: 3px 0;
        }
        
        .footer {
            text-align: center;
            margin-top: 20px;
            padding-top: 10px;
            border-top: 2px dashed #000;
            font-size: 11px;
            color: #666;
        }
        
        .actions {
            text-align: center;
            margin: 20px 0;
        }
        
        .btn {
            padding: 10px 20px;
            margin: 5px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .btn-print {
            background: #007bff;
            color: white;
        }
        
        .btn-close {
            background: #6c757d;
            color: white;
        }
        
        .barcode {
            text-align: center;
            margin: 10px 0;
        }
        
        .thank-you {
            text-align: center;
            margin: 15px 0;
            font-weight: bold;
            font-size: 13px;
        }
    </style>
</head>
<body>
    <div class="receipt">
        <!-- Header -->
        <div class="header">
            <h2><?= htmlspecialchars($sale['shop_name']) ?></h2>
            <p><?= htmlspecialchars($sale['shop_address']) ?></p>
            <p>Tel: <?= $sale['shop_phone'] ?? 'N/A' ?></p>
            <p>--------------------------------</p>
        </div>
        
        <!-- Sale Info -->
        <div class="info">
            <div class="info-row">
                <span>Invoice:</span>
                <span><?= htmlspecialchars($sale['invoice_no']) ?></span>
            </div>
            <div class="info-row">
                <span>Date:</span>
                <span><?= date('Y-m-d H:i:s', strtotime($sale['sale_date'])) ?></span>
            </div>
            <div class="info-row">
                <span>Cashier:</span>
                <span><?= htmlspecialchars($sale['cashier_name']) ?></span>
            </div>
            <?php if($sale['customer_name']): ?>
            <div class="info-row">
                <span>Customer:</span>
                <span><?= htmlspecialchars($sale['customer_name']) ?></span>
            </div>
            <?php endif; ?>
            <p>--------------------------------</p>
        </div>
        
        <!-- Items -->
        <table class="items">
            <thead>
                <tr>
                    <th class="qty">Qty</th>
                    <th class="desc">Description</th>
                    <th class="price">Price</th>
                    <th class="total">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($lines as $line): ?>
                <tr>
                    <td class="qty"><?= $line['qty'] ?></td>
                    <td class="desc">
                        <?= htmlspecialchars($line['product_name']) ?>
                        <?php if($line['batch_no']): ?>
                            <br><small>Batch: <?= $line['batch_no'] ?></small>
                        <?php endif; ?>
                    </td>
                    <td class="price"><?= number_format($line['unit_price'], 2) ?></td>
                    <td class="total"><?= number_format($line['line_total'], 2) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <!-- Totals -->
        <div class="totals">
            <div class="total-row">
                <span>Subtotal:</span>
                <span>TZS <?= number_format($sale['total'], 2) ?></span>
            </div>
            <div class="total-row">
                <span>Paid:</span>
                <span>TZS <?= number_format($sale['paid'], 2) ?></span>
            </div>
            <div class="total-row">
                <span>Balance:</span>
                <span>TZS <?= number_format($sale['total'] - $sale['paid'], 2) ?></span>
            </div>
            <div class="total-row grand">
                <span>TOTAL:</span>
                <span>TZS <?= number_format($sale['total'], 2) ?></span>
            </div>
        </div>
        
        <!-- Payments -->
        <?php if(!empty($payments)): ?>
        <div class="payments">
            <p><strong>PAYMENTS:</strong></p>
            <?php foreach($payments as $payment): ?>
            <div class="payment-row">
                <span><?= $payment['method'] ?>:</span>
                <span>TZS <?= number_format($payment['amount'], 2) ?></span>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
        
        <!-- Barcode (Optional) -->
        <div class="barcode">
            <!-- You can add barcode here if needed -->
        </div>
        
        <!-- Footer -->
        <div class="footer">
            <p>--------------------------------</p>
            <p>Thank you for your business!</p>
            <p>Please keep this receipt for reference</p>
            <p>--------------------------------</p>
            <p>Generated: <?= date('Y-m-d H:i:s') ?></p>
        </div>
        
        <!-- Thank You -->
        <div class="thank-you">
            HAVE A NICE DAY!
        </div>
    </div>
    
    <!-- Actions (Hidden when printing) -->
    <div class="actions no-print">
        <button class="btn btn-print" onclick="window.print()">
            <i class="fas fa-print"></i> Print Receipt
        </button>
        <button class="btn btn-close" onclick="window.close()">
            <i class="fas fa-times"></i> Close
        </button>
    </div>
    
    <script>
        // Auto-print on page load (optional)
        // window.onload = function() {
        //     setTimeout(function() {
        //         window.print();
        //     }, 1000);
        // };
        
        // Close window after printing (optional)
        window.onafterprint = function() {
            // Uncomment to auto-close after printing
            // setTimeout(function() {
            //     window.close();
            // }, 1000);
        };
    </script>
</body>
</html>