<?php
require_once '../../auth/check_session.php';
require_once '../../config/database.php';

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

try {
    $db = getDatabaseConnection();
    
    // Get sale details
    $sql = "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
            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 = ? AND s.shop_id = ?";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([$sale_id, $_SESSION['user']['shop_id']]);
    $sale = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$sale) {
        die('Sale not found');
    }
    
    // Get sale lines
    $sql = "SELECT sl.*, p.name as product_name, p.sku,
                   pb.batch_no, p.unit
            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 = ?
            ORDER BY sl.id";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([$sale_id]);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get payment
    $sql = "SELECT * FROM payments WHERE sale_id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$sale_id]);
    $payment = $stmt->fetch(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    die('Database error');
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Invoice <?= $sale['invoice_no'] ?></title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Courier New', monospace; font-size: 12px; padding: 20px; }
        .invoice { max-width: 300px; margin: 0 auto; }
        .header { text-align: center; margin-bottom: 15px; }
        .header h2 { font-size: 16px; margin-bottom: 5px; }
        .header p { font-size: 10px; margin: 2px 0; }
        .divider { border-top: 1px dashed #000; margin: 10px 0; }
        .table { width: 100%; border-collapse: collapse; }
        .table th, .table td { padding: 4px 2px; border-bottom: 1px dotted #ccc; }
        .table th { text-align: left; }
        .text-right { text-align: right; }
        .text-center { text-align: center; }
        .totals { margin-top: 10px; }
        .totals .row { display: flex; justify-content: space-between; margin: 3px 0; }
        .footer { margin-top: 20px; text-align: center; font-size: 10px; }
        .barcode { text-align: center; margin: 10px 0; font-family: 'Libre Barcode 128', cursive; font-size: 24px; }
        @media print {
            .no-print { display: none; }
            body { padding: 0; }
        }
    </style>
    <script>
        window.onload = function() {
            window.print();
            setTimeout(function() {
                window.close();
            }, 1000);
        };
    </script>
</head>
<body>
    <div class="invoice">
        <div class="header">
            <h2>PHARMACY INVOICE</h2>
            <p><?= htmlspecialchars($sale['shop_name']) ?></p>
            <p><?= htmlspecialchars($sale['shop_address']) ?></p>
            <p>Tel: <?= $_SESSION['user']['shop_phone'] ?? 'N/A' ?></p>
            <div class="divider"></div>
            <p>INVOICE: <?= $sale['invoice_no'] ?></p>
            <p>DATE: <?= date('d/m/Y H:i', strtotime($sale['sale_date'])) ?></p>
            <p>CASHIER: <?= htmlspecialchars($sale['cashier_name']) ?></p>
        </div>
        
        <div class="divider"></div>
        
        <?php if ($sale['customer_name']): ?>
        <div style="margin-bottom: 10px;">
            <p><strong>CUSTOMER:</strong> <?= htmlspecialchars($sale['customer_name']) ?></p>
            <?php if ($sale['customer_phone']): ?>
            <p><strong>PHONE:</strong> <?= htmlspecialchars($sale['customer_phone']) ?></p>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
        <table class="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 foreach ($items as $item): ?>
                <tr>
                    <td><?= substr($item['product_name'], 0, 15) ?></td>
                    <td class="text-right"><?= $item['qty'] ?> <?= $item['unit'] ?></td>
                    <td class="text-right"><?= number_format($item['unit_price'], 2) ?></td>
                    <td class="text-right"><?= number_format($item['line_total'], 2) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <div class="divider"></div>
        
        <div class="totals">
            <div class="row">
                <span>Subtotal:</span>
                <span>TZS <?= number_format($sale['total'], 2) ?></span>
            </div>
            <?php if ($payment): ?>
            <div class="row">
                <span>Payment:</span>
                <span><?= $payment['method'] ?></span>
            </div>
            <div class="row">
                <span>Amount Paid:</span>
                <span>TZS <?= number_format($payment['amount'], 2) ?></span>
            </div>
            <?php endif; ?>
            <div class="row" style="font-weight: bold; border-top: 1px solid #000; padding-top: 5px;">
                <span>GRAND TOTAL:</span>
                <span>TZS <?= number_format($sale['total'], 2) ?></span>
            </div>
        </div>
        
        <div class="divider"></div>
        
        <div class="barcode">
            *<?= $sale['invoice_no'] ?>*
        </div>
        
        <div class="footer">
            <p>Thank you for your purchase!</p>
            <p>Goods sold are not returnable</p>
            <p>For inquiries: <?= $_SESSION['user']['shop_phone'] ?? 'Contact shop' ?></p>
        </div>
    </div>
    
    <div class="no-print text-center" style="margin-top: 20px;">
        <button onclick="window.print()" class="btn btn-primary">Print Again</button>
        <button onclick="window.close()" class="btn btn-secondary">Close</button>
    </div>
</body>
</html>