<?php
session_start();
require_once 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get receipt parameters
$receipt_id = isset($_GET['receipt_id']) ? (int)$_GET['receipt_id'] : 0;
$payment_id = isset($_GET['payment_id']) ? (int)$_GET['payment_id'] : 0;
$order_id = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;
$auto_print = isset($_GET['auto_print']) ? true : false;

$receipt_data = null;

// Determine what type of receipt to generate
if ($receipt_id > 0) {
    // Get existing receipt
    $sql_receipt = "SELECT 
        r.*,
        o.order_number,
        o.order_date,
        o.total_amount as order_total,
        o.status as order_status,
        c.customer_id,
        c.first_name,
        c.last_name,
        c.customer_code,
        c.phone,
        c.email,
        c.address,
        u.full_name as issued_by_name
    FROM receipts r
    INNER JOIN orders o ON r.order_id = o.order_id
    INNER JOIN customers c ON r.customer_id = c.customer_id
    INNER JOIN users u ON r.issued_by = u.user_id
    WHERE r.receipt_id = ?";
    
    $stmt_receipt = $conn->prepare($sql_receipt);
    $stmt_receipt->bind_param("i", $receipt_id);
    $stmt_receipt->execute();
    $receipt_data = $stmt_receipt->get_result()->fetch_assoc();
    
} elseif ($payment_id > 0) {
    // Generate receipt from payment
    $sql_payment = "SELECT 
        p.*,
        o.order_number,
        o.order_date,
        o.total_amount as order_total,
        o.status as order_status,
        c.customer_id,
        c.first_name,
        c.last_name,
        c.customer_code,
        c.phone,
        c.email,
        c.address,
        pm.method_name,
        u.full_name as processed_by_name
    FROM payments p
    INNER JOIN orders o ON p.order_id = o.order_id
    INNER JOIN customers c ON p.customer_id = c.customer_id
    INNER JOIN payment_methods pm ON p.payment_method_id = pm.method_id
    INNER JOIN users u ON p.processed_by = u.user_id
    WHERE p.payment_id = ?";
    
    $stmt_payment = $conn->prepare($sql_payment);
    $stmt_payment->bind_param("i", $payment_id);
    $stmt_payment->execute();
    $payment_data = $stmt_payment->get_result()->fetch_assoc();
    
    if ($payment_data) {
        // Create receipt data structure from payment
        $receipt_data = [
            'receipt_number' => 'TMP' . date('Ymd') . str_pad($payment_id, 4, '0', STR_PAD_LEFT),
            'order_id' => $payment_data['order_id'],
            'customer_id' => $payment_data['customer_id'],
            'receipt_type' => 'PAYMENT',
            'total_amount' => $payment_data['amount'],
            'payment_method' => $payment_data['method_name'],
            'transaction_reference' => $payment_data['transaction_reference'],
            'issued_at' => $payment_data['payment_date'],
            'order_number' => $payment_data['order_number'],
            'order_date' => $payment_data['order_date'],
            'order_total' => $payment_data['order_total'],
            'order_status' => $payment_data['order_status'],
            'first_name' => $payment_data['first_name'],
            'last_name' => $payment_data['last_name'],
            'customer_code' => $payment_data['customer_code'],
            'phone' => $payment_data['phone'],
            'email' => $payment_data['email'],
            'address' => $payment_data['address'],
            'issued_by_name' => $payment_data['processed_by_name']
        ];
    }
    
} elseif ($order_id > 0) {
    // Generate receipt from order (for full payment)
    $sql_order = "SELECT 
        o.*,
        c.customer_id,
        c.first_name,
        c.last_name,
        c.customer_code,
        c.phone,
        c.email,
        c.address,
        SUM(p.amount) as total_paid
    FROM orders o
    INNER JOIN customers c ON o.customer_id = c.customer_id
    LEFT JOIN payments p ON o.order_id = p.order_id AND p.status = 'COMPLETED'
    WHERE o.order_id = ?
    GROUP BY o.order_id";
    
    $stmt_order = $conn->prepare($sql_order);
    $stmt_order->bind_param("i", $order_id);
    $stmt_order->execute();
    $order_data = $stmt_order->get_result()->fetch_assoc();
    
    if ($order_data) {
        // Create receipt data structure from order
        $receipt_data = [
            'receipt_number' => 'ORD' . date('Ymd') . str_pad($order_id, 4, '0', STR_PAD_LEFT),
            'order_id' => $order_data['order_id'],
            'customer_id' => $order_data['customer_id'],
            'receipt_type' => 'ORDER',
            'total_amount' => $order_data['total_paid'] ?: $order_data['total_amount'],
            'payment_method' => 'Multiple',
            'transaction_reference' => null,
            'issued_at' => date('Y-m-d H:i:s'),
            'order_number' => $order_data['order_number'],
            'order_date' => $order_data['order_date'],
            'order_total' => $order_data['total_amount'],
            'order_status' => $order_data['status'],
            'first_name' => $order_data['first_name'],
            'last_name' => $order_data['last_name'],
            'customer_code' => $order_data['customer_code'],
            'phone' => $order_data['phone'],
            'email' => $order_data['email'],
            'address' => $order_data['address'],
            'issued_by_name' => 'System Generated'
        ];
    }
}

if (!$receipt_data) {
    header('Location: list_payments.php?error=receipt_not_found');
    exit();
}

// Get company settings
$sql_settings = "SELECT setting_key, setting_value FROM settings WHERE category IN ('company', 'laundry')";
$result_settings = $conn->query($sql_settings);
$settings = [];
while ($row = $result_settings->fetch_assoc()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

// Get order items for detailed receipt
$sql_items = "SELECT 
    oi.*,
    s.service_name,
    sc.category_name
FROM order_items oi
INNER JOIN services s ON oi.service_id = s.service_id
INNER JOIN service_categories sc ON s.category_id = sc.category_id
WHERE oi.order_id = ?
ORDER BY sc.category_name, s.service_name";

$stmt_items = $conn->prepare($sql_items);
$stmt_items->bind_param("i", $receipt_data['order_id']);
$stmt_items->execute();
$result_items = $stmt_items->get_result();

// Get all payments for this order
$sql_payments = "SELECT 
    p.*,
    pm.method_name
FROM payments p
INNER JOIN payment_methods pm ON p.payment_method_id = pm.method_id
WHERE p.order_id = ? AND p.status = 'COMPLETED'
ORDER BY p.payment_date";

$stmt_payments = $conn->prepare($sql_payments);
$stmt_payments->bind_param("i", $receipt_data['order_id']);
$stmt_payments->execute();
$result_payments = $stmt_payments->get_result();

// Update print count if this is an existing receipt
if ($receipt_id > 0) {
    $sql_update_print = "UPDATE receipts SET printed_count = printed_count + 1 WHERE receipt_id = ?";
    $stmt_update_print = $conn->prepare($sql_update_print);
    $stmt_update_print->bind_param("i", $receipt_id);
    $stmt_update_print->execute();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Receipt - <?php echo $receipt_data['receipt_number']; ?></title>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Courier New', monospace;
            font-size: 12px;
            line-height: 1.4;
            color: #000;
            background: #fff;
        }
        
        .receipt-container {
            max-width: 300px;
            margin: 0 auto;
            padding: 10px;
            background: white;
        }
        
        .header {
            text-align: center;
            border-bottom: 2px solid #000;
            padding-bottom: 10px;
            margin-bottom: 15px;
        }
        
        .company-name {
            font-size: 16px;
            font-weight: bold;
            text-transform: uppercase;
            margin-bottom: 5px;
        }
        
        .company-info {
            font-size: 10px;
            line-height: 1.3;
        }
        
        .receipt-title {
            text-align: center;
            font-size: 14px;
            font-weight: bold;
            text-transform: uppercase;
            margin: 15px 0;
            border: 1px solid #000;
            padding: 5px;
        }
        
        .receipt-info {
            margin-bottom: 15px;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 3px;
        }
        
        .info-label {
            font-weight: bold;
        }
        
        .customer-section {
            border-top: 1px dashed #000;
            border-bottom: 1px dashed #000;
            padding: 10px 0;
            margin: 15px 0;
        }
        
        .section-title {
            font-weight: bold;
            text-transform: uppercase;
            margin-bottom: 5px;
        }
        
        .items-section {
            margin: 15px 0;
        }
        
        .items-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .items-table th {
            border-bottom: 1px solid #000;
            padding: 5px 2px;
            text-align: left;
            font-weight: bold;
            font-size: 10px;
        }
        
        .items-table td {
            padding: 3px 2px;
            font-size: 10px;
            border-bottom: 1px dotted #ccc;
        }
        
        .text-right {
            text-align: right;
        }
        
        .text-center {
            text-align: center;
        }
        
        .totals-section {
            border-top: 1px solid #000;
            padding-top: 10px;
            margin-top: 15px;
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 3px;
        }
        
        .total-row.grand-total {
            font-weight: bold;
            font-size: 14px;
            border-top: 1px solid #000;
            border-bottom: 2px solid #000;
            padding: 5px 0;
            margin-top: 5px;
        }
        
        .payment-section {
            margin: 15px 0;
            border-top: 1px dashed #000;
            padding-top: 10px;
        }
        
        .footer {
            text-align: center;
            border-top: 1px dashed #000;
            padding-top: 15px;
            margin-top: 20px;
            font-size: 10px;
        }
        
        .barcode {
            text-align: center;
            margin: 10px 0;
            font-family: 'Libre Barcode 128', cursive;
            font-size: 24px;
            letter-spacing: 1px;
        }
        
        .qr-placeholder {
            width: 80px;
            height: 80px;
            border: 2px solid #000;
            margin: 10px auto;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 8px;
            text-align: center;
        }
        
        .no-print {
            display: block;
        }
        
        @media print {
            body {
                margin: 0;
                padding: 0;
            }
            
            .receipt-container {
                max-width: none;
                width: 80mm;
                margin: 0;
                padding: 5mm;
            }
            
            .no-print {
                display: none;
            }
            
            .page-break {
                page-break-after: always;
            }
        }
        
        /* Print button styling */
        .print-controls {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            background: white;
            padding: 10px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .btn {
            padding: 8px 16px;
            margin: 0 5px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-primary {
            background: #059669;
            color: white;
        }
        
        .btn-secondary {
            background: #6b7280;
            color: white;
        }
        
        .btn:hover {
            opacity: 0.9;
        }
    </style>
    
    <!-- Barcode font -->
    <link href="https://fonts.googleapis.com/css2?family=Libre+Barcode+128&display=swap" rel="stylesheet">
</head>

<body>
    <!-- Print Controls -->
    <div class="print-controls no-print">
        <button onclick="window.print()" class="btn btn-primary">
            🖨️ Print Receipt
        </button>
        <a href="list_payments.php" class="btn btn-secondary">
            ← Back
        </a>
    </div>

    <div class="receipt-container">
        <!-- Header -->
        <div class="header">
            <div class="company-name"><?php echo strtoupper($settings['company_name'] ?? 'QuickWash Laundry'); ?></div>
            <div class="company-info">
                <?php echo $settings['company_address'] ?? 'Nanak House, Kimathi Street'; ?><br>
                <?php echo $settings['company_city'] ?? 'Nairobi'; ?>, <?php echo $settings['company_postal_code'] ?? '00100'; ?><br>
                Tel: <?php echo $settings['company_phone'] ?? '+254798805300'; ?><br>
                Email: <?php echo $settings['company_email'] ?? 'info@quickwash.co.ke'; ?>
            </div>
        </div>

        <!-- Receipt Title -->
        <div class="receipt-title">
            <?php 
            switch($receipt_data['receipt_type']) {
                case 'REFUND':
                    echo 'REFUND RECEIPT';
                    break;
                case 'PARTIAL':
                    echo 'PARTIAL PAYMENT RECEIPT';
                    break;
                default:
                    echo 'PAYMENT RECEIPT';
            }
            ?>
        </div>

        <!-- Receipt Information -->
        <div class="receipt-info">
            <div class="info-row">
                <span class="info-label">Receipt #:</span>
                <span><?php echo $receipt_data['receipt_number']; ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Date:</span>
                <span><?php echo date('d/m/Y H:i', strtotime($receipt_data['issued_at'])); ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Order #:</span>
                <span><?php echo $receipt_data['order_number']; ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Order Date:</span>
                <span><?php echo date('d/m/Y', strtotime($receipt_data['order_date'])); ?></span>
            </div>
            <?php if ($receipt_data['transaction_reference']): ?>
            <div class="info-row">
                <span class="info-label">Ref #:</span>
                <span><?php echo $receipt_data['transaction_reference']; ?></span>
            </div>
            <?php endif; ?>
        </div>

        <!-- Customer Information -->
        <div class="customer-section">
            <div class="section-title">Customer Details</div>
            <div><?php echo $receipt_data['first_name'] . ' ' . $receipt_data['last_name']; ?></div>
            <div>ID: <?php echo $receipt_data['customer_code']; ?></div>
            <div>Tel: <?php echo $receipt_data['phone']; ?></div>
            <?php if ($receipt_data['address']): ?>
            <div><?php echo $receipt_data['address']; ?></div>
            <?php endif; ?>
        </div>

        <!-- Order Items -->
        <div class="items-section">
            <div class="section-title">Order Details</div>
            <table class="items-table">
                <thead>
                    <tr>
                        <th>Item</th>
                        <th>Qty</th>
                        <th>Rate</th>
                        <th class="text-right">Amount</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $current_category = '';
                    $subtotal = 0;
                    while ($item = $result_items->fetch_assoc()): 
                        $subtotal += $item['total_price'];
                    ?>
                    <?php if ($current_category !== $item['category_name']): ?>
                        <?php $current_category = $item['category_name']; ?>
                        <tr>
                            <td colspan="4" style="font-weight: bold; background: #f0f0f0; text-transform: uppercase;">
                                <?php echo $current_category; ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                    <tr>
                        <td><?php echo $item['service_name']; ?></td>
                        <td class="text-center"><?php echo $item['quantity']; ?></td>
                        <td class="text-right"><?php echo number_format($item['unit_price'], 0); ?></td>
                        <td class="text-right"><?php echo number_format($item['total_price'], 0); ?></td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>

        <!-- Totals -->
        <div class="totals-section">
            <div class="total-row">
                <span>Subtotal:</span>
                <span>KES <?php echo number_format($subtotal, 0); ?></span>
            </div>
            <?php if (isset($receipt_data['discount_amount']) && $receipt_data['discount_amount'] > 0): ?>
            <div class="total-row">
                <span>Discount:</span>
                <span>KES <?php echo number_format($receipt_data['discount_amount'], 0); ?></span>
            </div>
            <?php endif; ?>
            <?php if (isset($receipt_data['tax_amount']) && $receipt_data['tax_amount'] > 0): ?>
            <div class="total-row">
                <span>Tax:</span>
                <span>KES <?php echo number_format($receipt_data['tax_amount'], 0); ?></span>
            </div>
            <?php endif; ?>
            <div class="total-row grand-total">
                <span>TOTAL:</span>
                <span>KES <?php echo number_format($receipt_data['order_total'], 0); ?></span>
            </div>
        </div>

        <!-- Payment Information -->
        <div class="payment-section">
            <div class="section-title">Payment Details</div>
            
            <?php if ($receipt_data['receipt_type'] === 'ORDER'): ?>
                <!-- Show all payments for order receipt -->
                <?php while ($payment = $result_payments->fetch_assoc()): ?>
                <div class="info-row">
                    <span><?php echo $payment['method_name']; ?>:</span>
                    <span>KES <?php echo number_format($payment['amount'], 0); ?></span>
                </div>
                <div style="font-size: 10px; color: #666; margin-bottom: 5px;">
                    <?php echo date('d/m/Y H:i', strtotime($payment['payment_date'])); ?>
                    <?php if ($payment['transaction_reference']): ?>
                    | Ref: <?php echo $payment['transaction_reference']; ?>
                    <?php endif; ?>
                </div>
                <?php endwhile; ?>
            <?php else: ?>
                <!-- Show single payment info -->
                <div class="info-row">
                    <span>Method:</span>
                    <span><?php echo $receipt_data['payment_method']; ?></span>
                </div>
                <div class="info-row">
                    <span><?php echo $receipt_data['receipt_type'] === 'REFUND' ? 'Refunded' : 'Paid'; ?>:</span>
                    <span>KES <?php echo number_format($receipt_data['total_amount'], 0); ?></span>
                </div>
            <?php endif; ?>
            
            <?php 
            // Calculate balance
            $total_paid = 0;
            $result_payments->data_seek(0); // Reset pointer
            while ($payment = $result_payments->fetch_assoc()) {
                $total_paid += $payment['amount'];
            }
            $balance = $receipt_data['order_total'] - $total_paid;
            ?>
            
            <?php if ($balance > 0): ?>
            <div class="info-row" style="font-weight: bold; color: #d97706;">
                <span>Balance Due:</span>
                <span>KES <?php echo number_format($balance, 0); ?></span>
            </div>
            <?php elseif ($balance < 0): ?>
            <div class="info-row" style="font-weight: bold; color: #059669;">
                <span>Change Given:</span>
                <span>KES <?php echo number_format(abs($balance), 0); ?></span>
            </div>
            <?php else: ?>
            <div class="info-row" style="font-weight: bold; color: #059669;">
                <span>Status:</span>
                <span>PAID IN FULL</span>
            </div>
            <?php endif; ?>
        </div>

        <!-- Barcode/QR Code -->
        <div class="text-center">
            <div class="barcode">*<?php echo $receipt_data['receipt_number']; ?>*</div>
            <div class="qr-placeholder">
                QR CODE<br>
                <?php echo $receipt_data['order_number']; ?>
            </div>
        </div>

        <!-- Footer -->
        <div class="footer">
            <div style="margin-bottom: 10px;">
                <?php echo $settings['receipt_footer'] ?? 'Thank you for choosing QuickWash Laundry Services!'; ?>
            </div>
            
            <div style="margin-bottom: 5px;">
                Served by: <?php echo $receipt_data['issued_by_name']; ?>
            </div>
            
            <div style="margin-bottom: 10px;">
                Status: <?php echo strtoupper($receipt_data['order_status']); ?>
            </div>
            
            <div style="border-top: 1px dashed #000; padding-top: 10px; margin-top: 10px;">
                <strong>Important Notes:</strong><br>
                • Please keep this receipt for pickup<br>
                • Items not collected within 30 days will be donated<br>
                • Check items before leaving premises<br>
                • No liability for items left in pockets
            </div>
            
            <div style="margin-top: 10px; font-size: 9px;">
                Printed: <?php echo date('d/m/Y H:i:s'); ?><br>
                Receipt ID: <?php echo $receipt_data['receipt_number']; ?><br>
                Visit us: <?php echo $settings['company_website'] ?? 'www.quickwash.co.ke'; ?>
            </div>
        </div>
    </div>

    <script>
        // Auto-print if requested
        <?php if ($auto_print): ?>
        window.onload = function() {
            setTimeout(function() {
                window.print();
            }, 500);
        };
        <?php endif; ?>
        
        // Print function
        function printReceipt() {
            window.print();
        }
        
        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Ctrl+P for print
            if (e.ctrlKey && e.key === 'p') {
                e.preventDefault();
                printReceipt();
            }
            
            // Escape to close
            if (e.key === 'Escape') {
                window.history.back();
            }
        });
        
        // Focus management for thermal printer compatibility
        document.addEventListener('DOMContentLoaded', function() {
            // Add print styles for thermal printers
            const style = document.createElement('style');
            style.textContent = `
                @media print {
                    @page {
                        size: 80mm auto;
                        margin: 0;
                    }
                    
                    body {
                        font-size: 10px;
                        width: 80mm;
                    }
                    
                    .receipt-container {
                        width: 80mm;
                        max-width: 80mm;
                        padding: 2mm;
                    }
                }
            `;
            document.head.appendChild(style);
        });
    </script>
</body>
</html>