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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

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

$user_id = $_SESSION['user_id'];
$order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;

if (!$order_id) {
    die('Invalid order ID');
}

// Fetch complete order details with customer and payment information
$sql_order = "SELECT o.*, 
                     c.first_name, c.last_name, c.phone, c.email, c.address, c.customer_code,
                     creator.full_name as created_by_name,
                     pm_latest.method_name as latest_payment_method
              FROM orders o
              LEFT JOIN customers c ON o.customer_id = c.customer_id
              LEFT JOIN users creator ON o.created_by = creator.user_id
              LEFT JOIN (
                  SELECT p1.order_id, pm.method_name 
                  FROM payments p1
                  INNER JOIN payment_methods pm ON p1.payment_method_id = pm.method_id
                  WHERE p1.payment_id = (
                      SELECT MAX(p2.payment_id) FROM payments p2 WHERE p2.order_id = p1.order_id
                  )
              ) pm_latest ON o.order_id = pm_latest.order_id
              WHERE o.order_id = ?";

$stmt_order = $conn->prepare($sql_order);
$stmt_order->bind_param("i", $order_id);
$stmt_order->execute();
$order = $stmt_order->get_result()->fetch_assoc();

if (!$order) {
    die('Order not found');
}

// Fetch order items
$sql_items = "SELECT oi.*, s.service_name, s.unit, sc.category_name
              FROM order_items oi
              LEFT JOIN services s ON oi.service_id = s.service_id
              LEFT JOIN service_categories sc ON s.category_id = sc.category_id
              WHERE oi.order_id = ?
              ORDER BY oi.item_id";

$stmt_items = $conn->prepare($sql_items);
$stmt_items->bind_param("i", $order_id);
$stmt_items->execute();
$order_items = $stmt_items->get_result();

// Fetch all payments for this order
$sql_payments = "SELECT p.*, pm.method_name, u.full_name as processed_by_name
                 FROM payments p
                 LEFT JOIN payment_methods pm ON p.payment_method_id = pm.method_id
                 LEFT JOIN users u ON p.processed_by = u.user_id
                 WHERE p.order_id = ? AND p.status = 'COMPLETED'
                 ORDER BY p.created_at ASC";

$stmt_payments = $conn->prepare($sql_payments);
$stmt_payments->bind_param("i", $order_id);
$stmt_payments->execute();
$payments = $stmt_payments->get_result();

// Fetch company settings
$sql_settings = "SELECT setting_key, setting_value FROM settings 
                 WHERE setting_key IN ('company_name', 'company_phone', 'company_email', 
                                       'company_address', 'company_city', 'company_logo',
                                       'receipt_footer', 'currency_symbol', 'company_tax_id')";
$result_settings = $conn->query($sql_settings);

$settings = [];
while ($row = $result_settings->fetch_assoc()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

// Helper function to get setting
function getSetting($key, $default = '') {
    global $settings;
    return $settings[$key] ?? $default;
}

// Generate or fetch receipt number
$receipt_number = '';
$existing_receipt = $conn->query("SELECT receipt_number FROM receipts WHERE order_id = $order_id LIMIT 1");
if ($existing_receipt && $existing_receipt->num_rows > 0) {
    $receipt_number = $existing_receipt->fetch_assoc()['receipt_number'];
} else {
    // Generate new receipt
    $receipt_sql = "INSERT INTO receipts (order_id, customer_id, receipt_type, total_amount, payment_method, issued_by) 
                   VALUES (?, ?, 'PAYMENT', ?, ?, ?)";
    $stmt_receipt = $conn->prepare($receipt_sql);
    $payment_method = $order['latest_payment_method'] ?? 'Cash';
    $stmt_receipt->bind_param("iidsi", $order_id, $order['customer_id'], $order['paid_amount'], $payment_method, $user_id);
    
    if ($stmt_receipt->execute()) {
        $receipt_id = $conn->insert_id;
        $receipt_result = $conn->query("SELECT receipt_number FROM receipts WHERE receipt_id = $receipt_id");
        $receipt_number = $receipt_result->fetch_assoc()['receipt_number'];
        
        // Update print count
        $conn->query("UPDATE receipts SET printed_count = printed_count + 1 WHERE receipt_id = $receipt_id");
    }
}

$conn->close();
?>

<!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_number; ?> - <?php echo getSetting('company_name', 'Amina Laundry'); ?></title>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Courier New', monospace;
            background: white;
            color: #000;
            line-height: 1.4;
        }
        
        .receipt-container {
            width: 80mm;
            margin: 0 auto;
            padding: 10px;
            background: white;
            min-height: 100vh;
        }
        
        .receipt-header {
            text-align: center;
            border-bottom: 2px solid #000;
            padding-bottom: 10px;
            margin-bottom: 15px;
        }
        
        .company-logo {
            max-width: 60px;
            max-height: 40px;
            margin-bottom: 5px;
        }
        
        .company-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 3px;
            text-transform: uppercase;
        }
        
        .company-details {
            font-size: 10px;
            margin-bottom: 2px;
        }
        
        .receipt-title {
            font-size: 14px;
            font-weight: bold;
            margin: 10px 0 5px 0;
            text-align: center;
            text-decoration: underline;
        }
        
        .receipt-info {
            margin-bottom: 15px;
            font-size: 11px;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 3px;
        }
        
        .customer-section {
            border-top: 1px dashed #000;
            border-bottom: 1px dashed #000;
            padding: 8px 0;
            margin: 10px 0;
        }
        
        .section-title {
            font-weight: bold;
            margin-bottom: 5px;
            text-decoration: underline;
        }
        
        .items-table {
            width: 100%;
            font-size: 10px;
            margin: 15px 0;
        }
        
        .items-table th {
            border-bottom: 1px solid #000;
            padding: 3px 2px;
            text-align: left;
            font-weight: bold;
        }
        
        .items-table td {
            padding: 3px 2px;
            border-bottom: 1px dotted #666;
        }
        
        .text-right {
            text-align: right;
        }
        
        .text-center {
            text-align: center;
        }
        
        .totals-section {
            border-top: 1px solid #000;
            padding-top: 8px;
            margin-top: 10px;
            font-size: 11px;
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 3px;
        }
        
        .total-row.grand-total {
            font-weight: bold;
            font-size: 13px;
            border-top: 1px solid #000;
            border-bottom: 1px solid #000;
            padding: 5px 0;
            margin-top: 5px;
        }
        
        .payment-section {
            margin: 15px 0;
            font-size: 11px;
        }
        
        .payment-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2px;
        }
        
        .receipt-footer {
            text-align: center;
            margin-top: 20px;
            border-top: 1px dashed #000;
            padding-top: 10px;
            font-size: 10px;
        }
        
        .thank-you {
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .footer-info {
            margin-bottom: 3px;
        }
        
        .barcode-section {
            text-align: center;
            margin: 15px 0;
        }
        
        .barcode-text {
            font-size: 8px;
            font-family: monospace;
            letter-spacing: 1px;
            margin-top: 5px;
        }
        
        .status-badge {
            display: inline-block;
            padding: 2px 6px;
            font-size: 8px;
            background: #000;
            color: #fff;
            text-transform: uppercase;
        }
        
        .no-print {
            display: block;
        }
        
        /* Print Styles */
        @media print {
            body {
                margin: 0;
                padding: 0;
            }
            
            .receipt-container {
                width: 100%;
                margin: 0;
                padding: 5px;
            }
            
            .no-print {
                display: none !important;
            }
            
            @page {
                margin: 0;
                size: 80mm auto;
            }
        }
        
        /* Mobile Styles */
        @media (max-width: 768px) {
            .receipt-container {
                width: 100%;
                max-width: 350px;
                padding: 15px;
            }
            
            .receipt-header {
                padding-bottom: 15px;
                margin-bottom: 20px;
            }
            
            .company-name {
                font-size: 18px;
            }
            
            .receipt-title {
                font-size: 16px;
            }
            
            .items-table {
                font-size: 12px;
            }
            
            .totals-section {
                font-size: 13px;
            }
            
            .total-row.grand-total {
                font-size: 15px;
            }
        }
        
        /* Action Buttons */
        .action-buttons {
            position: fixed;
            top: 20px;
            right: 20px;
            display: flex;
            gap: 10px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            font-weight: 600;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .btn-secondary {
            background: #64748b;
            color: white;
        }
        
        .btn:hover {
            opacity: 0.9;
        }
    </style>
</head>

<body>
    <!-- Action Buttons -->
    <div class="action-buttons no-print">
        <button onclick="window.print()" class="btn btn-primary">
            🖨️ Print Receipt
        </button>
        <a href="view_order.php?id=<?php echo $order_id; ?>" class="btn btn-secondary">
            ← Back to Order
        </a>
    </div>

    <div class="receipt-container">
        <!-- Header -->
        <div class="receipt-header">
            <?php if (getSetting('company_logo')): ?>
            <img src="<?php echo getSetting('company_logo'); ?>" alt="Logo" class="company-logo">
            <?php endif; ?>
            
            <div class="company-name"><?php echo getSetting('company_name', 'Amina Laundry'); ?></div>
            
            <?php if (getSetting('company_phone')): ?>
            <div class="company-details">Tel: <?php echo getSetting('company_phone'); ?></div>
            <?php endif; ?>
            
            <?php if (getSetting('company_email')): ?>
            <div class="company-details">Email: <?php echo getSetting('company_email'); ?></div>
            <?php endif; ?>
            
            <?php if (getSetting('company_address')): ?>
            <div class="company-details"><?php echo getSetting('company_address'); ?></div>
            <div class="company-details"><?php echo getSetting('company_city', 'Nairobi'); ?></div>
            <?php endif; ?>
            
            <?php if (getSetting('company_tax_id')): ?>
            <div class="company-details">Tax ID: <?php echo getSetting('company_tax_id'); ?></div>
            <?php endif; ?>
        </div>

        <!-- Receipt Title -->
        <div class="receipt-title">PAYMENT RECEIPT</div>

        <!-- Receipt Information -->
        <div class="receipt-info">
            <div class="info-row">
                <span>Receipt #:</span>
                <span><strong><?php echo $receipt_number; ?></strong></span>
            </div>
            <div class="info-row">
                <span>Order #:</span>
                <span><strong><?php echo $order['order_number']; ?></strong></span>
            </div>
            <div class="info-row">
                <span>Date:</span>
                <span><?php echo date('d/M/Y H:i', strtotime($order['order_date'])); ?></span>
            </div>
            <div class="info-row">
                <span>Cashier:</span>
                <span><?php echo $order['created_by_name']; ?></span>
            </div>
            <div class="info-row">
                <span>Status:</span>
                <span class="status-badge"><?php echo $order['status']; ?></span>
            </div>
        </div>

        <!-- Customer Information -->
        <div class="customer-section">
            <div class="section-title">CUSTOMER DETAILS</div>
            <div class="info-row">
                <span>Name:</span>
                <span><?php echo $order['first_name'] . ' ' . $order['last_name']; ?></span>
            </div>
            <div class="info-row">
                <span>Code:</span>
                <span><?php echo $order['customer_code']; ?></span>
            </div>
            <div class="info-row">
                <span>Phone:</span>
                <span><?php echo $order['phone']; ?></span>
            </div>
            <?php if ($order['email']): ?>
            <div class="info-row">
                <span>Email:</span>
                <span><?php echo $order['email']; ?></span>
            </div>
            <?php endif; ?>
        </div>

        <!-- Order Items -->
        <table class="items-table">
            <thead>
                <tr>
                    <th style="width: 50%;">Item</th>
                    <th style="width: 15%;" class="text-center">Qty</th>
                    <th style="width: 20%;" class="text-right">Rate</th>
                    <th style="width: 15%;" class="text-right">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($item = $order_items->fetch_assoc()): ?>
                <tr>
                    <td>
                        <strong><?php echo $item['service_name']; ?></strong>
                        <?php if ($item['item_description']): ?>
                        <br><small><?php echo $item['item_description']; ?></small>
                        <?php endif; ?>
                    </td>
                    <td class="text-center"><?php echo $item['quantity']; ?></td>
                    <td class="text-right"><?php echo number_format($item['unit_price'], 2); ?></td>
                    <td class="text-right"><?php echo number_format($item['total_price'], 2); ?></td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>

        <!-- Totals Section -->
        <div class="totals-section">
            <div class="total-row">
                <span>Subtotal:</span>
                <span><?php echo getSetting('currency_symbol', 'KSh'); ?> <?php echo number_format($order['subtotal'], 2); ?></span>
            </div>
            
            <?php if ($order['discount_amount'] > 0): ?>
            <div class="total-row">
                <span>Discount:</span>
                <span>-<?php echo getSetting('currency_symbol', 'KSh'); ?> <?php echo number_format($order['discount_amount'], 2); ?></span>
            </div>
            <?php endif; ?>
            
            <?php if ($order['tax_amount'] > 0): ?>
            <div class="total-row">
                <span>Tax:</span>
                <span><?php echo getSetting('currency_symbol', 'KSh'); ?> <?php echo number_format($order['tax_amount'], 2); ?></span>
            </div>
            <?php endif; ?>
            
            <div class="total-row grand-total">
                <span>TOTAL:</span>
                <span><?php echo getSetting('currency_symbol', 'KSh'); ?> <?php echo number_format($order['total_amount'], 2); ?></span>
            </div>
        </div>

        <!-- Payment Information -->
        <div class="payment-section">
            <div class="section-title">PAYMENT DETAILS</div>
            
            <?php if ($payments->num_rows > 0): ?>
                <?php while ($payment = $payments->fetch_assoc()): ?>
                <div class="payment-row">
                    <span><?php echo $payment['method_name']; ?>:</span>
                    <span><?php echo getSetting('currency_symbol', 'KSh'); ?> <?php echo number_format($payment['amount'], 2); ?></span>
                </div>
                <?php endwhile; ?>
            <?php endif; ?>
            
            <div class="payment-row" style="border-top: 1px dotted #000; padding-top: 5px; margin-top: 5px;">
                <span><strong>Amount Paid:</strong></span>
                <span><strong><?php echo getSetting('currency_symbol', 'KSh'); ?> <?php echo number_format($order['paid_amount'], 2); ?></strong></span>
            </div>
            
            <?php if ($order['balance_amount'] > 0): ?>
            <div class="payment-row">
                <span><strong>Balance Due:</strong></span>
                <span><strong><?php echo getSetting('currency_symbol', 'KSh'); ?> <?php echo number_format($order['balance_amount'], 2); ?></strong></span>
            </div>
            <?php else: ?>
            <div class="payment-row">
                <span><strong>Status:</strong></span>
                <span><strong>PAID IN FULL</strong></span>
            </div>
            <?php endif; ?>
        </div>

        <!-- Service Information -->
        <?php if ($order['pickup_date'] || $order['delivery_date']): ?>
        <div class="customer-section">
            <div class="section-title">SERVICE DETAILS</div>
            
            <?php if ($order['pickup_date']): ?>
            <div class="info-row">
                <span>Pickup Date:</span>
                <span><?php echo date('d/M/Y', strtotime($order['pickup_date'])); ?></span>
            </div>
            <?php endif; ?>
            
            <?php if ($order['delivery_date']): ?>
            <div class="info-row">
                <span>Delivery Date:</span>
                <span><?php echo date('d/M/Y', strtotime($order['delivery_date'])); ?></span>
            </div>
            <?php endif; ?>
            
            <?php if ($order['estimated_delivery']): ?>
            <div class="info-row">
                <span>Est. Ready:</span>
                <span><?php echo date('d/M/Y H:i', strtotime($order['estimated_delivery'])); ?></span>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <!-- Barcode Section -->
        <div class="barcode-section">
            <div style="border: 1px solid #000; padding: 5px; font-size: 8px; letter-spacing: 2px;">
                |||| || ||| |||| | ||| ||||| || |||||
            </div>
            <div class="barcode-text"><?php echo $order['order_number']; ?></div>
        </div>

        <!-- Footer -->
        <div class="receipt-footer">
            <div class="thank-you">THANK YOU FOR YOUR BUSINESS!</div>
            
            <?php if (getSetting('receipt_footer')): ?>
            <div class="footer-info"><?php echo getSetting('receipt_footer'); ?></div>
            <?php endif; ?>
            
            <div class="footer-info">Please keep this receipt for pickup</div>
            <div class="footer-info">Visit us: <?php echo getSetting('company_website', 'www.Amina.co.ke'); ?></div>
            
            <div style="margin-top: 10px; font-size: 8px; color: #666;">
                Generated: <?php echo date('d/M/Y H:i:s'); ?>
            </div>
        </div>
    </div>

    <script>
        // Auto print on load for direct print links
        if (window.location.search.includes('auto_print=1')) {
            window.onload = function() {
                setTimeout(function() {
                    window.print();
                }, 500);
            };
        }
        
        // Print function
        function printReceipt() {
            window.print();
        }
        
        // Keyboard shortcut for printing
        document.addEventListener('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                e.preventDefault();
                window.print();
            }
        });
        
        // Mobile-friendly print button
        if ('ontouchstart' in window || navigator.maxTouchPoints > 0) {
            document.querySelector('.action-buttons').style.position = 'relative';
            document.querySelector('.action-buttons').style.top = 'auto';
            document.querySelector('.action-buttons').style.right = 'auto';
            document.querySelector('.action-buttons').style.marginBottom = '20px';
            document.querySelector('.action-buttons').style.justifyContent = 'center';
        }
    </script>
</body>
</html>