<?php
require_once '../../includes/auth.php';
requireLogin();
require_once '../../config/database.php';

$order_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$format = isset($_GET['format']) ? $_GET['format'] : 'thermal'; // thermal or a4

if ($order_id <= 0) {
    header('Location: index.php?error=invalid_order');
    exit;
}

$db = new Database();
$conn = $db->getConnection();

// Fetch order details
$order_sql = "SELECT o.*, c.name as customer_name, c.mobile as customer_mobile, 
              c.email as customer_email, c.address as customer_address,
              w.name as worker_name
              FROM orders o
              LEFT JOIN customers c ON o.customer_id = c.id
              LEFT JOIN workers w ON o.assigned_worker_id = w.id
              WHERE o.id = ?";
$stmt = $conn->prepare($order_sql);
$stmt->bind_param("i", $order_id);
$stmt->execute();
$order = $stmt->get_result()->fetch_assoc();


if (!$order) {
    header('Location: index.php?error=order_not_found');
    exit;
}

// Fetch order items
$items_sql = "SELECT oi.*, c.name as category_name 
              FROM order_items oi 
              LEFT JOIN categories c ON oi.category_id = c.id 
              WHERE oi.order_id = ?";
$stmt = $conn->prepare($items_sql);
$stmt->bind_param("i", $order_id);
$stmt->execute();
$order_items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Fetch payment details
$payment_sql = "SELECT SUM(amount) as total_paid FROM payments WHERE order_id = ?";
$stmt = $conn->prepare($payment_sql);
$stmt->bind_param("i", $order_id);
$stmt->execute();
$payment_data = $stmt->get_result()->fetch_assoc();
$total_paid = $payment_data['total_paid'] ?? 0;
$balance = $order['total_amount'] - $total_paid;

// Fetch company details
$company_sql = "SELECT * FROM company WHERE id = 1";
$company_result = $conn->query($company_sql);
$company = $company_result->fetch_assoc();

// If no company data, use defaults
if (!$company) {
    $company = [
        'name' => 'UCLEAN',
        'logo' => null,
        'email' => 'support@uclean.com',
        'phone' => '+91 1234567890',
        'address' => '123 Main Street, City - 400001',
        'gstin' => '27ABCDE1234F1Z5'
    ];
}

$conn->close();

// Set content type and disable caching for print
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Slip - <?php echo $order['order_number']; ?></title>
    <style>
        /* Global Print Settings */
        @media print {
            body {
                margin: 0;
                padding: 0;
                background: white;
            }
            .no-print {
                display: none !important;
            }
            @page {
                size: <?php echo $format == 'thermal' ? '80mm auto' : 'A4'; ?>;
                margin: <?php echo $format == 'thermal' ? '5mm' : '15mm'; ?>;
            }
        }
        
        /* Common Styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: <?php echo $format == 'thermal' ? "'Courier New', 'Monaco', monospace" : "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif"; ?>;
            background: #f0f0f0;
            padding: 20px;
        }
        
        .print-container {
            max-width: <?php echo $format == 'thermal' ? '80mm' : '210mm'; ?>;
            margin: 0 auto;
            background: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        
        /* Thermal Format Styles (3-inch) */
        <?php if ($format == 'thermal'): ?>
        .thermal-format {
            padding: 8px;
            font-size: 10px;
            line-height: 1.3;
        }
        
        .thermal-format .business-name {
            font-size: 14px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 5px;
        }
        
        .thermal-format .business-details {
            font-size: 8px;
            text-align: center;
            color: #666;
            margin-bottom: 8px;
        }
        
        .thermal-format .order-title {
            text-align: center;
            font-size: 11px;
            font-weight: bold;
            border: 1px solid #000;
            padding: 3px;
            margin: 8px 0;
            background: #f8f8f8;
        }
        
        .thermal-format .info-row {
            display: flex;
            justify-content: space-between;
            padding: 3px 0;
            border-bottom: 1px dotted #ddd;
            font-size: 9px;
        }
        
        .thermal-format .info-label {
            font-weight: bold;
        }
        
        .thermal-format .items-table {
            width: 100%;
            margin: 8px 0;
            border-collapse: collapse;
            font-size: 9px;
        }
        
        .thermal-format .items-table th,
        .thermal-format .items-table td {
            border-bottom: 1px dotted #ddd;
            padding: 4px 0;
            text-align: left;
        }
        
        .thermal-format .items-table th {
            border-bottom: 1px solid #000;
            font-weight: bold;
        }
        
        .thermal-format .text-right {
            text-align: right;
        }
        
        .thermal-format .total-line {
            display: flex;
            justify-content: space-between;
            padding: 3px 0;
            font-size: 9px;
        }
        
        .thermal-format .grand-total {
            font-size: 11px;
            font-weight: bold;
            text-align: center;
            padding: 5px;
            margin: 8px 0;
            background: #f0f0f0;
        }
        
        .thermal-format .footer {
            text-align: center;
            font-size: 7px;
            margin-top: 10px;
            padding-top: 8px;
            border-top: 1px dashed #000;
        }
        
        .thermal-format .signature {
            display: flex;
            justify-content: space-between;
            margin-top: 12px;
            font-size: 8px;
        }
        
        .thermal-format .signature-line {
            text-align: center;
            width: 45%;
        }
        
        .thermal-format .signature-text {
            border-top: 1px solid #000;
            margin-top: 5px;
            padding-top: 3px;
        }
        
        .thermal-format .barcode {
            text-align: center;
            margin: 8px 0;
            font-family: monospace;
            font-size: 12px;
            letter-spacing: 2px;
        }
        <?php endif; ?>
        
        /* A4 Format Styles */
        <?php if ($format == 'a4'): ?>
        .a4-format {
            padding: 20px;
            font-size: 12px;
            line-height: 1.5;
        }
        
        .a4-format .business-name {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 10px;
            color: #4e73df;
        }
        
        .a4-format .business-details {
            text-align: center;
            color: #666;
            margin-bottom: 20px;
            border-bottom: 2px solid #4e73df;
            padding-bottom: 15px;
        }
        
        .a4-format .order-title {
            text-align: center;
            font-size: 18px;
            font-weight: bold;
            margin: 20px 0;
            padding: 10px;
            background: #f8f9fc;
            border-left: 4px solid #4e73df;
        }
        
        .a4-format .info-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin: 20px 0;
        }
        
        .a4-format .info-card {
            background: #f8f9fc;
            padding: 15px;
            border-radius: 8px;
        }
        
        .a4-format .info-card h6 {
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #4e73df;
            border-bottom: 2px solid #4e73df;
            padding-bottom: 5px;
        }
        
        .a4-format .info-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #e3e6f0;
        }
        
        .a4-format .info-label {
            font-weight: bold;
            color: #5a5c69;
        }
        
        .a4-format .items-table {
            width: 100%;
            margin: 20px 0;
            border-collapse: collapse;
        }
        
        .a4-format .items-table th,
        .a4-format .items-table td {
            border: 1px solid #e3e6f0;
            padding: 10px;
            text-align: left;
        }
        
        .a4-format .items-table th {
            background: #f8f9fc;
            font-weight: bold;
            color: #4e73df;
        }
        
        .a4-format .text-right {
            text-align: right;
        }
        
        .a4-format .total-section {
            margin: 20px 0;
            background: #f8f9fc;
            padding: 15px;
            border-radius: 8px;
        }
        
        .a4-format .total-line {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
        }
        
        .a4-format .grand-total {
            font-size: 18px;
            font-weight: bold;
            text-align: right;
            padding: 10px;
            margin-top: 10px;
            border-top: 2px solid #4e73df;
            color: #4e73df;
        }
        
        .a4-format .footer {
            text-align: center;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e3e6f0;
            color: #858796;
        }
        
        .a4-format .signature {
            display: flex;
            justify-content: space-between;
            margin-top: 40px;
        }
        
        .a4-format .signature-line {
            text-align: center;
            width: 45%;
        }
        
        .a4-format .signature-text {
            border-top: 1px solid #000;
            margin-top: 10px;
            padding-top: 8px;
        }
        
        .a4-format .status-badge {
            display: inline-block;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .a4-format .status-pending { background: #f6c23e; color: #000; }
        .a4-format .status-processing { background: #36b9cc; color: #fff; }
        .a4-format .status-ready { background: #4e73df; color: #fff; }
        .a4-format .status-delivered { background: #1cc88a; color: #fff; }
        .a4-format .status-cancelled { background: #e74a3b; color: #fff; }
        <?php endif; ?>
        
        /* Common Button Styles */
        .button-group {
            text-align: center;
            margin-top: 20px;
            padding: 15px;
            position: sticky;
            bottom: 0;
            background: white;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
            z-index: 1000;
        }
        
        .btn {
            display: inline-block;
            padding: 10px 20px;
            margin: 0 5px;
            background: #4e73df;
            color: white;
            text-decoration: none;
            border-radius: 5px;
            font-size: 14px;
            font-family: Arial, sans-serif;
            cursor: pointer;
            border: none;
        }
        
        .btn-secondary {
            background: #6c757d;
        }
        
        .btn-success {
            background: #1cc88a;
        }
        
        .btn-info {
            background: #36b9cc;
        }
        
        .format-switch {
            display: inline-block;
            margin: 0 10px;
            padding: 8px 15px;
            background: #f8f9fc;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 12px;
        }
        
        .format-switch a {
            text-decoration: none;
            color: #4e73df;
            margin: 0 5px;
        }
        
        .format-switch .active {
            font-weight: bold;
            color: #1cc88a;
        }
    </style>
</head>
<body>
    <div class="print-container <?php echo $format == 'thermal' ? 'thermal-format' : 'a4-format'; ?>">
        <!-- Thermal Format Content -->
        <?php if ($format == 'thermal'): ?>
        <div class="thermal-format">
            <!-- Header -->
            <div class="business-name"><img src="../../<?php echo $company['logo']; ?>" alt-text="company_logo" style="width:25%;"></div>
            <div class="business-details">
                <?php echo htmlspecialchars($company['name']); ?><br>
                📞 +91 <?php echo htmlspecialchars($company['phone']); ?>
            </div>
            
            <div class="order-title">ORDER SLIP</div>
            
            <!-- Order Info -->
            <div class="info-row">
                <span class="info-label">Order #:</span>
                <span><?php echo $order['order_number']; ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Date:</span>
                <span><?php echo date('d-m-Y H:i', strtotime($order['created_at'])); ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Delivery:</span>
                <span><?php echo date('d-m-Y', strtotime($order['expected_delivery_date'])); ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Type:</span>
                <span><?php echo ucfirst(str_replace('_', ' ', $order['order_type'])); ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Status:</span>
                <span><?php echo ucfirst($order['status']); ?></span>
            </div>
            
            <!-- Customer Info -->
            <div class="info-row" style="margin-top: 5px;">
                <span class="info-label">Customer:</span>
                <span><?php echo htmlspecialchars($order['customer_name']); ?></span>
            </div>
            <div class="info-row">
                <span class="info-label">Mobile:</span>
                <span><?php echo htmlspecialchars($order['customer_mobile']); ?></span>
            </div>
            
            <!-- 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">Amt</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($order_items as $item): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($item['category_name']); ?></td>
                        <td class="text-right"><?php echo $item['quantity'] . ' ' . $item['uom']; ?></td>
                        <td class="text-right">₹<?php echo number_format($item['unit_price'], 2); ?></td>
                        <td class="text-right">₹<?php echo number_format($item['amount'], 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            
            <!-- Totals -->
            <div class="total-line">
                <span>Subtotal:</span>
                <span>₹<?php echo number_format($order['total_amount'], 2); ?></span>
            </div>
            <?php if ($total_paid > 0): ?>
            <div class="total-line">
                <span>Paid:</span>
                <span>₹<?php echo number_format($total_paid, 2); ?></span>
            </div>
            <div class="total-line">
                <span>Balance:</span>
                <span>₹<?php echo number_format($balance, 2); ?></span>
            </div>
            <?php endif; ?>
            
            <div class="grand-total">
                TOTAL: ₹<?php echo number_format($order['total_amount'], 2); ?>
            </div>
            
            <!-- Barcode -->
            <div class="barcode">
                <?php echo $order['order_number']; ?>
            </div>
            
            <!-- Footer -->
            <div class="footer">
                Thank you!<br>
                For queries: +91 1234567890
            </div>
            
            <!-- Signature -->
            <div class="signature">
                <div class="signature-line">
                    <div class="signature-text">Customer Signature</div>
                </div>
                <div class="signature-line">
                    <div class="signature-text">Staff Signature</div>
                </div>
            </div>
        </div>
        
        <?php else: ?>
        <!-- A4 Format Content -->
        <div class="a4-format">
            <!-- Header -->
            <div class="business-name"><img src="../../<?php echo $company['logo']; ?>" alt-text="company_logo" style="width:25%;"></div>
            <div class="business-details">
                <strong><?php echo htmlspecialchars($company['name']); ?></strong><br>
                <?php echo htmlspecialchars($company['address']); ?> | 📞 +91 <?php echo htmlspecialchars($company['phone']); ?> | ✉ <?php echo htmlspecialchars($company['email']); ?><br>
                GST: <?php echo htmlspecialchars($company['gstin']); ?>
            </div>
            
            <div class="order-title">
                <i class="bi bi-receipt"></i> ORDER SLIP
            </div>
            
            <!-- Information Section -->
            <div class="info-section">
                <div class="info-card">
                    <h6>📋 ORDER DETAILS</h6>
                    <div class="info-row">
                        <span class="info-label">Order Number:</span>
                        <span><strong><?php echo $order['order_number']; ?></strong></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Order Date:</span>
                        <span><?php echo date('F d, Y h:i A', strtotime($order['created_at'])); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Order Type:</span>
                        <span><?php echo ucfirst(str_replace('_', ' ', $order['order_type'])); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Expected Delivery:</span>
                        <span><?php echo date('F d, Y', strtotime($order['expected_delivery_date'])); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Status:</span>
                        <span>
                            <span class="status-badge status-<?php echo $order['status']; ?>">
                                <?php echo ucfirst($order['status']); ?>
                            </span>
                        </span>
                    </div>
                </div>
                
                <div class="info-card">
                    <h6>👤 CUSTOMER INFORMATION</h6>
                    <div class="info-row">
                        <span class="info-label">Name:</span>
                        <span><strong><?php echo htmlspecialchars($order['customer_name']); ?></strong></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Mobile:</span>
                        <span><?php echo htmlspecialchars($order['customer_mobile']); ?></span>
                    </div>
                    <?php if (!empty($order['customer_email'])): ?>
                    <div class="info-row">
                        <span class="info-label">Email:</span>
                        <span><?php echo htmlspecialchars($order['customer_email']); ?></span>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($order['customer_address'])): ?>
                    <div class="info-row">
                        <span class="info-label">Address:</span>
                        <span><?php echo htmlspecialchars($order['customer_address']); ?></span>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($order['worker_name'])): ?>
                    <div class="info-row">
                        <span class="info-label">Assigned Worker:</span>
                        <span><?php echo htmlspecialchars($order['worker_name']); ?></span>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Items Table -->
            <h6 style="margin: 20px 0 10px 0;">📦 ORDER ITEMS</h6>
            <table class="items-table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Service Item</th>
                        <th class="text-right">Quantity</th>
                        <th class="text-right">Unit Price (₹)</th>
                        <th class="text-right">Amount (₹)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $counter = 1; foreach ($order_items as $item): ?>
                    <tr>
                        <td><?php echo $counter++; ?></td>
                        <td><?php echo htmlspecialchars($item['category_name']); ?></td>
                        <td class="text-right"><?php echo $item['quantity'] . ' ' . $item['uom']; ?></td>
                        <td class="text-right">₹<?php echo number_format($item['unit_price'], 2); ?></td>
                        <td class="text-right">₹<?php echo number_format($item['amount'], 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            
            <!-- Totals Section -->
            <div class="total-section">
                <div class="total-line">
                    <span><strong>Subtotal:</strong></span>
                    <span>₹<?php echo number_format($order['total_amount'], 2); ?></span>
                </div>
                <div class="total-line">
                    <span><strong>Discount:</strong></span>
                    <span>₹0.00</span>
                </div>
                <?php if ($total_paid > 0): ?>
                <div class="total-line">
                    <span><strong>Amount Paid:</strong></span>
                    <span>₹<?php echo number_format($total_paid, 2); ?></span>
                </div>
                <div class="total-line">
                    <span><strong>Balance Due:</strong></span>
                    <span>₹<?php echo number_format($balance, 2); ?></span>
                </div>
                <?php endif; ?>
                <div class="grand-total">
                    Grand Total: ₹<?php echo number_format($order['total_amount'], 2); ?>
                </div>
            </div>
            
            <!-- Payment Status -->
            <div class="info-card" style="margin: 20px 0;">
                <h6>💳 PAYMENT STATUS</h6>
                <div class="info-row">
                    <span class="info-label">Payment Status:</span>
                    <span>
                        <?php
                        $status_badge = [
                            'paid' => 'success',
                            'partial' => 'warning',
                            'pending' => 'danger',
                            'cancelled' => 'secondary'
                        ];
                        $payment_status = $order['payment_status'] ?? 'pending';
                        ?>
                        <strong style="color: <?php echo $payment_status == 'paid' ? '#1cc88a' : ($payment_status == 'partial' ? '#f6c23e' : '#e74a3b'); ?>">
                            <?php echo ucfirst($payment_status); ?>
                        </strong>
                        <?php if ($payment_status == 'partial'): ?>
                            (₹<?php echo number_format($balance, 2); ?> remaining)
                        <?php endif; ?>
                    </span>
                </div>
            </div>
            
            <!-- Notes Section -->
            <?php 
            $has_notes = false;
            foreach ($order_items as $item) {
                if (!empty($item['notes'])) {
                    $has_notes = true;
                    break;
                }
            }
            if ($has_notes): 
            ?>
            <div class="info-card" style="margin: 20px 0;">
                <h6>📝 SPECIAL INSTRUCTIONS</h6>
                <?php foreach ($order_items as $item): ?>
                    <?php if (!empty($item['notes'])): ?>
                    <div class="info-row">
                        <span><strong><?php echo htmlspecialchars($item['category_name']); ?>:</strong></span>
                        <span><?php echo htmlspecialchars($item['notes']); ?></span>
                    </div>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
            
            <!-- Footer -->
            <div class="footer">
                <p><strong>Terms & Conditions:</strong> This is a computer generated slip. Valid without signature.</p>
                <p>Please check items at the time of delivery. No claims will be entertained after 24 hours.</p>
                <p>Thank you for choosing our service! We appreciate your business.</p>
                <p style="margin-top: 15px;">Generated on: <?php echo date('F d, Y h:i A'); ?></p>
            </div>
            
            <!-- Signature -->
            <div class="signature">
                <div class="signature-line">
                    <div class="signature-text">Customer Signature</div>
                    <div style="font-size: 10px; margin-top: 5px;">Date: ___________</div>
                </div>
                <div class="signature-line">
                    <div class="signature-text">Authorized Signatory</div>
                    <div style="font-size: 10px; margin-top: 5px;">Date: ___________</div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <div class="button-group no-print">
        <button onclick="window.print();" class="btn">
            🖨️ Print
        </button>
        <div class="format-switch">
            Switch Format:
            <a href="?id=<?php echo $order_id; ?>&format=thermal" class="<?php echo $format == 'thermal' ? 'active' : ''; ?>">Thermal (3-inch)</a> |
            <a href="?id=<?php echo $order_id; ?>&format=a4" class="<?php echo $format == 'a4' ? 'active' : ''; ?>">A4 Sheet</a>
        </div>
        <button onclick="window.close();" class="btn btn-secondary">
            ✖ Close
        </button>
    </div>
    
    <script>
        // Auto print when page loads
        window.onload = function() {
            setTimeout(function() {
                // Ask user if they want to print
                if (confirm('Do you want to print this order slip?')) {
                    window.print();
                }
            }, 500);
        };
        
        // Handle format switching without losing print dialog
        document.querySelectorAll('.format-switch a').forEach(link => {
            link.addEventListener('click', function(e) {
                if (confirm('Changing format will reload the page. Continue?')) {
                    return true;
                }
                e.preventDefault();
                return false;
            });
        });
    </script>
</body>
</html>