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

if (!isset($_SESSION['user']['id'])) {
    die('Unauthorized access');
}

$sale_id = $_GET['sale_id'] ?? 0;
$sale_id = intval($sale_id);
$shop_id = $_SESSION['user']['shop_id'];

// Get sale details
$sale_sql = "SELECT 
                s.*,
                c.name as customer_name,
                c.phone as customer_phone,
                u.fullname as cashier_name,
                sh.name as shop_name,
                sh.phone as shop_phone,
                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 = ?";

$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 or access denied');
}

// Get sale lines
$lines_sql = "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 = ? AND sl.shop_id = ?
             ORDER BY sl.id";

$lines_stmt = $pdo->prepare($lines_sql);
$lines_stmt->execute([$sale_id, $shop_id]);
$sale_lines = $lines_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get payment details
$payment_sql = "SELECT * FROM payments WHERE sale_id = ? ORDER BY id DESC LIMIT 1";
$payment_stmt = $pdo->prepare($payment_sql);
$payment_stmt->execute([$sale_id]);
$payment = $payment_stmt->fetch(PDO::FETCH_ASSOC);

// Calculate totals
$subtotal = 0;
$total_discount = 0;
$total_vat = 0;

foreach ($sale_lines as $line) {
    $line_subtotal = $line['qty'] * $line['unit_price'];
    $line_discount = $line_subtotal * ($line['discount'] / 100);
    $line_after_discount = $line_subtotal - $line_discount;
    
    // Get VAT from product
    $vat_sql = "SELECT vat_percent FROM products WHERE id = ?";
    $vat_stmt = $pdo->prepare($vat_sql);
    $vat_stmt->execute([$line['product_id']]);
    $vat_percent = $vat_stmt->fetchColumn() ?? 0;
    $line_vat = $line_after_discount * ($vat_percent / 100);
    
    $subtotal += $line_subtotal;
    $total_discount += $line_discount;
    $total_vat += $line_vat;
}

$grand_total = $subtotal - $total_discount + $total_vat;
$change = $sale['paid'] - $grand_total;
?>
<!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-container {
                box-shadow: none !important;
                border: none !important;
            }
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Courier New', monospace;
        }
        
        body {
            background: #f5f5f5;
            padding: 20px;
        }
        
        .receipt-container {
            max-width: 400px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            border: 1px solid #ddd;
        }
        
        .receipt-header {
            text-align: center;
            margin-bottom: 20px;
            border-bottom: 2px dashed #333;
            padding-bottom: 15px;
        }
        
        .shop-name {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 5px;
            text-transform: uppercase;
        }
        
        .shop-details {
            font-size: 12px;
            color: #666;
            line-height: 1.4;
        }
        
        .receipt-title {
            text-align: center;
            margin: 15px 0;
            font-size: 18px;
            font-weight: bold;
        }
        
        .receipt-info {
            margin: 15px 0;
            border-bottom: 1px dashed #ccc;
            padding-bottom: 10px;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
            font-size: 14px;
        }
        
        .info-label {
            font-weight: bold;
        }
        
        .items-table {
            width: 100%;
            margin: 15px 0;
            border-collapse: collapse;
            font-size: 12px;
        }
        
        .items-table th {
            text-align: left;
            padding: 8px 5px;
            border-bottom: 1px solid #333;
            font-weight: bold;
        }
        
        .items-table td {
            padding: 5px;
            border-bottom: 1px dotted #ddd;
        }
        
        .items-table .text-right {
            text-align: right;
        }
        
        .items-table .text-center {
            text-align: center;
        }
        
        .totals-section {
            margin: 20px 0;
            border-top: 2px dashed #333;
            padding-top: 10px;
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .grand-total {
            font-weight: bold;
            font-size: 16px;
            border-top: 1px solid #333;
            border-bottom: 1px solid #333;
            padding: 10px 0;
            margin: 10px 0;
        }
        
        .payment-info {
            background: #f8f9fa;
            padding: 15px;
            margin: 20px 0;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .footer {
            text-align: center;
            margin-top: 30px;
            padding-top: 15px;
            border-top: 2px dashed #333;
            font-size: 12px;
            color: #666;
            line-height: 1.4;
        }
        
        .barcode {
            text-align: center;
            margin: 20px 0;
        }
        
        .actions {
            text-align: center;
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        
        .btn {
            padding: 10px 20px;
            margin: 0 5px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
        }
        
        .btn-print {
            background: #28a745;
            color: white;
        }
        
        .btn-close {
            background: #6c757d;
            color: white;
        }
        
        .thank-you {
            text-align: center;
            font-style: italic;
            margin: 20px 0;
            color: #28a745;
            font-weight: bold;
        }
        
        .signature {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px dashed #333;
            text-align: center;
        }
        
        .signature-line {
            width: 200px;
            border-bottom: 1px solid #333;
            margin: 0 auto 5px;
            height: 20px;
        }
        
        .signature-label {
            font-size: 12px;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="receipt-container">
        <!-- Shop Header -->
        <div class="receipt-header">
            <div class="shop-name"><?= htmlspecialchars($sale['shop_name'] ?? 'PHARMACY STORE') ?></div>
            <div class="shop-details">
                <?php if (!empty($sale['shop_address'])): ?>
                <div><?= htmlspecialchars($sale['shop_address']) ?></div>
                <?php endif; ?>
                <?php if (!empty($sale['shop_phone'])): ?>
                <div>Tel: <?= htmlspecialchars($sale['shop_phone']) ?></div>
                <?php endif; ?>
                <div>Date: <?= date('d/m/Y H:i:s', strtotime($sale['sale_date'])) ?></div>
            </div>
        </div>
        
        <!-- Receipt Title -->
        <div class="receipt-title">TAX INVOICE</div>
        
        <!-- Sale Information -->
        <div class="receipt-info">
            <div class="info-row">
                <span class="info-label">Invoice No:</span>
                <span><?= htmlspecialchars($sale['invoice_no']) ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Cashier:</span>
                <span><?= htmlspecialchars($sale['cashier_name'] ?? 'N/A') ?></span>
            </div>
            <?php if (!empty($sale['customer_name'])): ?>
            <div class="info-row">
                <span class="info-label">Customer:</span>
                <span><?= htmlspecialchars($sale['customer_name']) ?></span>
            </div>
            <?php if (!empty($sale['customer_phone'])): ?>
            <div class="info-row">
                <span class="info-label">Phone:</span>
                <span><?= htmlspecialchars($sale['customer_phone']) ?></span>
            </div>
            <?php endif; ?>
            <?php else: ?>
            <div class="info-row">
                <span class="info-label">Customer:</span>
                <span>WALK-IN CUSTOMER</span>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Items Table -->
        <table class="items-table">
            <thead>
                <tr>
                    <th width="5%">#</th>
                    <th>Item</th>
                    <th width="10%" class="text-center">Qty</th>
                    <th width="20%" class="text-right">Price</th>
                    <th width="20%" class="text-right">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($sale_lines as $index => $line): ?>
                <?php
                    $line_total = $line['qty'] * $line['unit_price'];
                    $line_discount = $line_total * ($line['discount'] / 100);
                    $line_after_discount = $line_total - $line_discount;
                ?>
                <tr>
                    <td><?= $index + 1 ?></td>
                    <td>
                        <?= htmlspecialchars($line['product_name']) ?>
                        <?php if (!empty($line['batch_no'])): ?>
                        <br><small>Batch: <?= htmlspecialchars($line['batch_no']) ?></small>
                        <?php endif; ?>
                    </td>
                    <td class="text-center"><?= $line['qty'] ?></td>
                    <td class="text-right"><?= number_format($line['unit_price'], 2) ?></td>
                    <td class="text-right"><?= number_format($line_after_discount, 2) ?></td>
                </tr>
                <?php if ($line['discount'] > 0): ?>
                <tr>
                    <td></td>
                    <td colspan="3" style="font-size: 10px; color: #666;">
                        &nbsp;&nbsp;Discount: <?= $line['discount'] ?>%
                    </td>
                    <td class="text-right" style="font-size: 10px; color: #666;">
                        -<?= number_format($line_discount, 2) ?>
                    </td>
                </tr>
                <?php endif; ?>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <!-- Totals -->
        <div class="totals-section">
            <div class="total-row">
                <span>Subtotal:</span>

                <span>TZS <?= number_format($subtotal, 2) ?></span>
            </div>
            <?php if ($total_discount > 0): ?>
            <div class="total-row">
                <span>Discount:</span>
                <span>-TZS <?= number_format($total_discount, 2) ?></span>
            </div>
            <?php endif; ?>
            <?php if ($total_vat > 0): ?>
            <div class="total-row">
                <span>VAT:</span>
                <span>+TZS <?= number_format($total_vat, 2) ?></span>
            </div>
            <?php endif; ?>
            <div class="total-row grand-total">
                <span>TOTAL:</span>
                <span>TZS <?= number_format($grand_total, 2) ?></span>
            </div>
        </div>
        
        <!-- Payment Information -->
        <div class="payment-info">
            <div class="info-row">
                <span class="info-label">Payment Method:</span>
                <span><?= htmlspecialchars($payment['method'] ?? 'CASH') ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Amount Paid:</span>
                <span>TZS <?= number_format($sale['paid'], 2) ?></span>
            </div>
            <?php if ($change > 0): ?>
            <div class="info-row">
                <span class="info-label">Change:</span>
                <span>TZS <?= number_format($change, 2) ?></span>
            </div>
            <?php endif; ?>
            <div class="info-row">
                <span class="info-label">Status:</span>
                <span style="color: #28a745; font-weight: bold;"><?= strtoupper($sale['status']) ?></span>
            </div>
        </div>
        
        <!-- Thank You Message -->
        <div class="thank-you">
            THANK YOU FOR YOUR BUSINESS!
        </div>
        
        <!-- Footer -->
        <div class="footer">
            <div>*** THIS IS A COMPUTER GENERATED RECEIPT ***</div>
            <div>NO VALID WITHOUT OFFICIAL STAMP</div>
            <div>Goods sold are not returnable unless faulty</div>
            <div>For inquiries, please contact our support</div>
            <div style="margin-top: 10px;">Receipt ID: <?= $sale_id ?></div>
        </div>
        
        <!-- Barcode (optional) -->
        <div class="barcode">
            <div style="margin-bottom: 5px;">Scan for verification:</div>
            <div style="font-family: 'Libre Barcode 128', cursive; font-size: 40px; letter-spacing: 2px;">
                *<?= $sale['invoice_no'] ?>*
            </div>
        </div>
        
        <!-- Signature -->
        <div class="signature">
            <div class="signature-line"></div>
            <div class="signature-label">Cashier's Signature</div>
        </div>
    </div>
    
    <!-- Action Buttons (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>
        <button class="btn btn-print" onclick="downloadReceipt()">
            <i class="fas fa-download"></i> Download PDF
        </button>
    </div>
    
    <script>
        // Auto-print option
        window.onload = function() {
            // Uncomment the line below to auto-print when page loads
            // setTimeout(() => window.print(), 1000);
        };
        
        function downloadReceipt() {
            // For now, just trigger print with save as PDF option
            window.print();
        }
        
        // Close window after print (optional)
        window.onafterprint = function() {
            // Uncomment to close window after printing
            // setTimeout(() => window.close(), 1000);
        };
    </script>
    
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <!-- Barcode font -->
    <link href="https://fonts.googleapis.com/css2?family=Libre+Barcode+128&display=swap" rel="stylesheet">
</body>
</html>