<?php
// modules/sales/print_receipt.php
session_start();
require_once "../assets/db_connect.php";

// Check if PDO connection exists
if (!isset($pdo)) {
    die("Database connection failed");
}

// Validate user session
if (!isset($_SESSION['user']['shop_id'])) {
    die("Unauthorized access");
}

$shop_id = (int)$_SESSION['user']['shop_id'];
$sale_id = isset($_GET['sale_id']) ? (int)$_GET['sale_id'] : 0;

if ($sale_id <= 0) {
    die("Invalid sale ID");
}

try {
    // Get sale details
    $stmt = $pdo->prepare("
        SELECT 
            s.*,
            c.name as customer_name,
            c.phone as customer_phone,
            u.fullname as cashier_name,
            sh.name as shop_name,
            sh.address as shop_address,
            sh.phone as shop_phone
        FROM sales s
        LEFT JOIN customers c ON s.customer_id = c.id
        LEFT JOIN users u ON s.created_by = u.id
        LEFT JOIN shops sh ON s.shop_id = sh.id
        WHERE s.id = :sale_id AND s.shop_id = :shop_id
    ");
    
    $stmt->execute([':sale_id' => $sale_id, ':shop_id' => $shop_id]);
    $sale = $stmt->fetch();
    
    if (!$sale) {
        die("Sale not found");
    }
    
    // Get sale lines
    $stmt = $pdo->prepare("
        SELECT 
            sl.*,
            p.name as product_name,
            p.sku,
            p.unit,
            pb.batch_no,
            pb.expiry_date
        FROM sale_lines sl
        JOIN products p ON sl.product_id = p.id
        LEFT JOIN product_batches pb ON sl.batch_id = pb.id
        WHERE sl.sale_id = :sale_id
        ORDER BY sl.id
    ");
    
    $stmt->execute([':sale_id' => $sale_id]);
    $sale_lines = $stmt->fetchAll();
    
    // Get payments
    $stmt = $pdo->prepare("
        SELECT * FROM payments 
        WHERE sale_id = :sale_id 
        ORDER BY paid_at
    ");
    
    $stmt->execute([':sale_id' => $sale_id]);
    $payments = $stmt->fetchAll();
    
} catch (PDOException $e) {
    die("Error loading sale data: " . $e->getMessage());
}

// Set HTML headers for printing
?>
<!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; font-size: 12px; }
            .no-print { display: none !important; }
            .receipt { width: 80mm !important; margin: 0 !important; padding: 10px !important; }
        }
        
        body {
            font-family: 'Courier New', monospace;
            background: #f5f5f5;
            margin: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
        
        .receipt {
            width: 300px;
            background: white;
            padding: 20px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            border: 1px solid #ddd;
        }
        
        .header {
            text-align: center;
            border-bottom: 2px dashed #333;
            padding-bottom: 10px;
            margin-bottom: 15px;
        }
        
        .shop-name {
            font-size: 18px;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        .invoice-info {
            margin: 15px 0;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
            font-size: 12px;
        }
        
        .items-table th {
            text-align: left;
            border-bottom: 1px solid #ddd;
            padding: 5px 0;
            font-weight: bold;
        }
        
        .items-table td {
            padding: 4px 0;
            border-bottom: 1px dashed #eee;
        }
        
        .text-right { text-align: right; }
        .text-center { text-align: center; }
        
        .totals {
            margin-top: 20px;
            border-top: 2px dashed #333;
            padding-top: 10px;
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            margin: 3px 0;
        }
        
        .grand-total {
            font-size: 14px;
            font-weight: bold;
            border-top: 2px solid #333;
            padding-top: 8px;
            margin-top: 8px;
        }
        
        .footer {
            text-align: center;
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px dashed #ddd;
            color: #666;
            font-size: 11px;
        }
        
        .controls {
            text-align: center;
            margin-top: 20px;
        }
        
        .btn {
            padding: 8px 16px;
            margin: 5px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        
        .btn-print {
            background: #28a745;
            color: white;
        }
        
        .btn-close {
            background: #6c757d;
            color: white;
        }
    </style>
    <script>
        function printReceipt() {
            window.print();
        }
        
        function closeWindow() {
            window.close();
        }
        
        // Auto-print after 1 second
        window.onload = function() {
            setTimeout(function() {
                window.print();
            }, 1000);
        }
    </script>
</head>
<body>
    <div class="receipt">
        <!-- Shop Header -->
        <div class="header">
            <div class="shop-name"><?= htmlspecialchars($sale['shop_name'] ?? 'Pharmacy POS') ?></div>
            <div class="shop-address"><?= htmlspecialchars($sale['shop_address'] ?? '') ?></div>
            <div class="shop-address">Tel: <?= htmlspecialchars($sale['shop_phone'] ?? '') ?></div>
        </div>
        
        <!-- Invoice Info -->
        <div class="invoice-info">
            <div><strong>Invoice:</strong> <?= htmlspecialchars($sale['invoice_no']) ?></div>
            <div><strong>Date:</strong> <?= date('d/m/Y H:i:s', strtotime($sale['sale_date'])) ?></div>
            <div><strong>Cashier:</strong> <?= htmlspecialchars($sale['cashier_name'] ?? 'System') ?></div>
        </div>
        
        <!-- Customer Info -->
        <?php if ($sale['customer_name']): ?>
        <div class="invoice-info">
            <div><strong>Customer:</strong> <?= htmlspecialchars($sale['customer_name']) ?></div>
            <?php if ($sale['customer_phone']): ?>
                <div><strong>Phone:</strong> <?= htmlspecialchars($sale['customer_phone']) ?></div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
        <!-- Items Table -->
        <table class="items-table">
            <thead>
                <tr>
                    <th>Item</th>
                    <th class="text-right">Qty</th>
                    <th class="text-right">Price</th>
                    <th class="text-right">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $subtotal = 0;
                $vat_total = 0;
                foreach ($sale_lines as $line): 
                    $line_total = $line['qty'] * $line['unit_price'];
                    $discount_amount = $line_total * ($line['discount'] / 100);
                    $after_discount = $line_total - $discount_amount;
                    $vat_amount = $after_discount * (($line['vat_percent'] ?? 0) / 100);
                    $final_total = $after_discount + $vat_amount;
                    
                    $subtotal += $after_discount;
                    $vat_total += $vat_amount;
                ?>
                <tr>
                    <td>
                        <?= htmlspecialchars($line['product_name']) ?>
                        <?php if ($line['batch_no']): ?>
                            <br><small>Batch: <?= htmlspecialchars($line['batch_no']) ?></small>
                        <?php endif; ?>
                    </td>
                    <td class="text-right"><?= $line['qty'] ?></td>
                    <td class="text-right"><?= number_format($line['unit_price'], 2) ?></td>
                    <td class="text-right"><?= number_format($final_total, 2) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <!-- Totals -->
        <div class="totals">
            <div class="total-row">
                <span>Subtotal:</span>
                <span><?= number_format($subtotal, 2) ?></span>
            </div>
            <div class="total-row">
                <span>VAT:</span>
                <span><?= number_format($vat_total, 2) ?></span>
            </div>
            <?php if ($sale['paid'] > 0): ?>
            <div class="total-row">
                <span>Amount Paid:</span>
                <span><?= number_format($sale['paid'], 2) ?></span>
            </div>
            <?php endif; ?>
            <div class="total-row grand-total">
                <span>GRAND TOTAL:</span>
                <span><?= number_format($sale['total'], 2) ?></span>
            </div>
            <?php if ($sale['paid'] > $sale['total']): ?>
            <div class="total-row">
                <span>Change:</span>
                <span><?= number_format($sale['paid'] - $sale['total'], 2) ?></span>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Payment Information -->
        <?php if (!empty($payments)): ?>
        <div class="invoice-info">
            <strong>Payment Details:</strong>
            <?php foreach ($payments as $payment): ?>
                <div><?= $payment['method'] ?>: <?= number_format($payment['amount'], 2) ?></div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
        
        <!-- Thank You Message -->
        <div class="text-center" style="margin: 15px 0; font-style: italic; color: #666;">
            Thank you for your purchase!
        </div>
        
        <!-- Footer -->
        <div class="footer">
            <div>For returns, please bring this receipt</div>
            <div>Valid for 7 days from purchase date</div>
            <div>This is a computer generated receipt</div>
        </div>
        
        <!-- Print Controls (hidden when printing) -->
        <div class="controls no-print">
            <button class="btn btn-print" onclick="printReceipt()">
                <i class="fas fa-print"></i> Print Receipt
            </button>
            <button class="btn btn-close" onclick="closeWindow()">
                <i class="fas fa-times"></i> Close
            </button>
        </div>
    </div>
</body>
</html>