<?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
$sql_order = "SELECT o.*, 
                     c.first_name, c.last_name, c.phone, c.email, c.customer_code,
                     creator.full_name as created_by_name,
                     assignee.full_name as assigned_to_name
              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 users assignee ON o.assigned_to = assignee.user_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 with categories
$sql_items = "SELECT oi.*, s.service_name, s.unit, sc.category_name,
                     CASE 
                         WHEN sc.category_name = 'Dry Cleaning' THEN 'DRY'
                         WHEN sc.category_name = 'Washing' THEN 'WASH'
                         WHEN sc.category_name = 'Ironing' THEN 'IRON'
                         WHEN sc.category_name = 'Special Care' THEN 'SPEC'
                         ELSE 'GEN'
                     END as category_code
              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 sc.category_name, 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();

// Group items by category for processing
$items_by_category = [];
$total_pieces = 0;
while ($item = $order_items->fetch_assoc()) {
    $category = $item['category_name'] ?? 'General';
    if (!isset($items_by_category[$category])) {
        $items_by_category[$category] = [];
    }
    $items_by_category[$category][] = $item;
    $total_pieces += $item['quantity'];
}

// Fetch delivery information if applicable
$sql_delivery = "SELECT od.*, dr.route_name
                 FROM order_deliveries od
                 LEFT JOIN delivery_routes dr ON od.route_id = dr.route_id
                 WHERE od.order_id = ?";
$stmt_delivery = $conn->prepare($sql_delivery);
$stmt_delivery->bind_param("i", $order_id);
$stmt_delivery->execute();
$delivery_info = $stmt_delivery->get_result()->fetch_assoc();

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

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

function getSetting($key, $default = '') {
    global $settings;
    return $settings[$key] ?? $default;
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Ticket #<?php echo $order['order_number']; ?> - <?php echo getSetting('company_name', 'Amina Laundry'); ?></title>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: Arial, sans-serif;
            background: white;
            color: #000;
            line-height: 1.3;
        }
        
        .ticket-container {
            width: 100mm;
            margin: 0 auto;
            padding: 8px;
            background: white;
            border: 2px dashed #000;
            position: relative;
        }
        
        /* Perforation line */
        .ticket-container::before {
            content: '';
            position: absolute;
            top: 50%;
            left: -5px;
            right: -5px;
            height: 1px;
            background: repeating-linear-gradient(
                to right,
                #000,
                #000 5px,
                transparent 5px,
                transparent 10px
            );
            z-index: 10;
        }
        
        .ticket-section {
            margin-bottom: 15px;
        }
        
        /* Top Section - Customer Copy */
        .customer-copy {
            padding-bottom: 15px;
            border-bottom: 1px dashed #000;
        }
        
        /* Bottom Section - Service Copy */
        .service-copy {
            padding-top: 15px;
        }
        
        .ticket-header {
            text-align: center;
            margin-bottom: 10px;
            border-bottom: 2px solid #000;
            padding-bottom: 8px;
        }
        
        .company-logo {
            max-width: 40px;
            max-height: 30px;
            margin-bottom: 5px;
        }
        
        .company-name {
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 2px;
        }
        
        .company-contact {
            font-size: 10px;
            margin-bottom: 1px;
        }
        
        .ticket-title {
            font-size: 12px;
            font-weight: bold;
            text-align: center;
            background: #000;
            color: #fff;
            padding: 4px;
            margin: 8px 0;
        }
        
        .order-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 10px;
        }
        
        .info-box {
            border: 1px solid #000;
            padding: 4px;
            margin: 2px 0;
            background: #f5f5f5;
        }
        
        .customer-info {
            font-size: 11px;
            margin-bottom: 8px;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2px;
        }
        
        .items-summary {
            font-size: 10px;
            margin: 8px 0;
        }
        
        .category-group {
            border: 1px solid #ccc;
            margin: 4px 0;
            padding: 4px;
        }
        
        .category-header {
            font-weight: bold;
            background: #eee;
            padding: 2px;
            margin-bottom: 3px;
            font-size: 9px;
        }
        
        .item-row {
            display: flex;
            justify-content: space-between;
            font-size: 8px;
            margin-bottom: 1px;
        }
        
        .special-instructions {
            background: #fffacd;
            border: 1px solid #000;
            padding: 4px;
            margin: 6px 0;
            font-size: 9px;
        }
        
        .processing-checklist {
            border: 1px solid #000;
            padding: 4px;
            margin: 6px 0;
            font-size: 9px;
        }
        
        .checkbox-item {
            display: flex;
            align-items: center;
            margin: 2px 0;
        }
        
        .checkbox {
            width: 12px;
            height: 12px;
            border: 1px solid #000;
            margin-right: 5px;
            display: inline-block;
        }
        
        .status-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 4px;
            font-size: 9px;
            margin: 6px 0;
        }
        
        .status-box {
            border: 1px solid #000;
            padding: 3px;
            text-align: center;
        }
        
        .priority-urgent {
            background: #ffebee;
            border-color: #f44336;
        }
        
        .priority-high {
            background: #fff3e0;
            border-color: #ff9800;
        }
        
        .priority-normal {
            background: #f5f5f5;
            border-color: #666;
        }
        
        .signatures-section {
            display: flex;
            justify-content: space-between;
            margin-top: 10px;
            font-size: 9px;
        }
        
        .signature-box {
            border: 1px solid #000;
            width: 45%;
            height: 25px;
            text-align: center;
            display: flex;
            align-items: end;
            justify-content: center;
            padding: 2px;
        }
        
        .barcode-section {
            text-align: center;
            margin: 8px 0;
            padding: 4px;
            border: 1px dashed #000;
        }
        
        .barcode {
            font-family: 'Courier New', monospace;
            font-size: 8px;
            letter-spacing: 1px;
            margin: 2px 0;
        }
        
        .qr-placeholder {
            width: 30px;
            height: 30px;
            border: 1px solid #000;
            margin: 0 auto;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 6px;
        }
        
        .tear-here {
            text-align: center;
            font-size: 8px;
            color: #666;
            margin: 8px 0;
            position: relative;
        }
        
        .tear-here::before,
        .tear-here::after {
            content: '✂';
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
        }
        
        .tear-here::before {
            left: 0;
        }
        
        .tear-here::after {
            right: 0;
        }
        
        .no-print {
            display: block;
        }
        
        /* Print Styles */
        @media print {
            body {
                margin: 0;
                padding: 0;
            }
            
            .ticket-container {
                width: 100%;
                margin: 0;
                padding: 5px;
                border: 2px dashed #000;
            }
            
            .no-print {
                display: none !important;
            }
            
            @page {
                margin: 0;
                size: 100mm auto;
            }
        }
        
        /* 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;
        }
        
        /* Mobile Responsive */
        @media (max-width: 768px) {
            .ticket-container {
                width: 100%;
                max-width: 400px;
                padding: 12px;
            }
            
            .action-buttons {
                position: relative;
                top: auto;
                right: auto;
                justify-content: center;
                margin-bottom: 20px;
            }
        }
    </style>
</head>

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

    <div class="ticket-container">
        
        <!-- CUSTOMER COPY -->
        <div class="customer-copy">
            <!-- Header -->
            <div class="ticket-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>
                <div class="company-contact"><?php echo getSetting('company_phone'); ?> | <?php echo getSetting('company_address'); ?></div>
            </div>

            <div class="ticket-title">CUSTOMER COPY - KEEP FOR PICKUP</div>

            <!-- Order Information -->
            <div class="info-box">
                <div class="order-info">
                    <span><strong>Order #: <?php echo $order['order_number']; ?></strong></span>
                    <span><strong>Date: <?php echo date('d/M/Y H:i', strtotime($order['order_date'])); ?></strong></span>
                </div>
            </div>

            <!-- Customer Information -->
            <div class="customer-info">
                <div class="info-row">
                    <span><strong><?php echo $order['first_name'] . ' ' . $order['last_name']; ?></strong></span>
                    <span><?php echo $order['customer_code']; ?></span>
                </div>
                <div class="info-row">
                    <span>Phone: <?php echo $order['phone']; ?></span>
                    <span>Pieces: <?php echo $total_pieces; ?></span>
                </div>
            </div>

            <!-- Service Summary -->
            <div class="items-summary">
                <div style="font-weight: bold; margin-bottom: 4px;">Services:</div>
                <?php foreach ($items_by_category as $category => $items): ?>
                    <div style="margin-bottom: 2px;">
                        <strong><?php echo $category; ?>:</strong>
                        <?php 
                        $category_total = 0;
                        $service_names = [];
                        foreach ($items as $item) {
                            $category_total += $item['quantity'];
                            $service_names[] = $item['service_name'];
                        }
                        echo $category_total . ' pcs (' . implode(', ', array_unique($service_names)) . ')';
                        ?>
                    </div>
                <?php endforeach; ?>
            </div>

            <!-- Status and Dates -->
            <div class="status-section">
                <div class="status-box priority-<?php echo strtolower($order['priority']); ?>">
                    <strong><?php echo $order['priority']; ?> PRIORITY</strong>
                </div>
                <div class="status-box">
                    <strong>Status: <?php echo $order['status']; ?></strong>
                </div>
            </div>

            <?php if ($order['estimated_delivery']): ?>
            <div class="info-box">
                <div style="text-align: center;">
                    <strong>ESTIMATED READY: <?php echo date('d/M/Y H:i', strtotime($order['estimated_delivery'])); ?></strong>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($delivery_info): ?>
            <div class="info-box">
                <div style="text-align: center;">
                    <strong>DELIVERY: <?php echo $delivery_info['route_name']; ?> - <?php echo date('d/M/Y', strtotime($delivery_info['delivery_date'])); ?></strong>
                </div>
            </div>
            <?php endif; ?>

            <!-- Total Amount -->
            <div class="info-box" style="text-align: center; font-size: 12px;">
                <strong>TOTAL AMOUNT: KSh <?php echo number_format($order['total_amount'], 2); ?></strong>
                <?php if ($order['balance_amount'] > 0): ?>
                <br><span style="color: red;">BALANCE: KSh <?php echo number_format($order['balance_amount'], 2); ?></span>
                <?php endif; ?>
            </div>

            <!-- Barcode Section -->
            <div class="barcode-section">
                <div class="qr-placeholder">QR</div>
                <div class="barcode"><?php echo $order['order_number']; ?></div>
            </div>

            <!-- Footer -->
            <div style="text-align: center; font-size: 8px; margin-top: 8px;">
                Present this ticket when collecting your items<br>
                Generated: <?php echo date('d/M/Y H:i'); ?>
            </div>
        </div>

        <!-- Tear Line -->
        <div class="tear-here">✂ TEAR HERE ✂</div>

        <!-- SERVICE COPY -->
        <div class="service-copy">
            <!-- Header -->
            <div class="ticket-header" style="font-size: 10px;">
                <div class="company-name">SERVICE PROCESSING COPY</div>
                <div>Order #<?php echo $order['order_number']; ?> | <?php echo date('d/M/Y H:i', strtotime($order['order_date'])); ?></div>
            </div>

            <!-- Customer Info -->
            <div style="display: flex; justify-content: space-between; font-size: 10px; margin-bottom: 8px;">
                <span><strong><?php echo $order['first_name'] . ' ' . $order['last_name']; ?></strong></span>
                <span><?php echo $order['phone']; ?></span>
                <span>Pcs: <?php echo $total_pieces; ?></span>
            </div>

            <!-- Detailed Items List -->
            <div class="items-summary">
                <?php foreach ($items_by_category as $category => $items): ?>
                <div class="category-group">
                    <div class="category-header">
                        <?php echo strtoupper($category); ?>
                        <?php 
                        $category_code = $items[0]['category_code'] ?? 'GEN';
                        echo ' [' . $category_code . ']';
                        ?>
                    </div>
                    <?php foreach ($items as $item): ?>
                    <div class="item-row">
                        <span><?php echo $item['service_name']; ?></span>
                        <span><?php echo $item['quantity']; ?> pcs</span>
                        <span>KSh <?php echo number_format($item['total_price'], 2); ?></span>
                    </div>
                    <?php if ($item['item_description']): ?>
                    <div style="font-size: 7px; color: #666; margin-left: 5px;">
                        Note: <?php echo $item['item_description']; ?>
                    </div>
                    <?php endif; ?>
                    <?php endforeach; ?>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- Special Instructions -->
            <?php if ($order['special_instructions'] || $order['customer_notes']): ?>
            <div class="special-instructions">
                <strong>SPECIAL INSTRUCTIONS:</strong><br>
                <?php if ($order['special_instructions']): ?>
                <?php echo nl2br(htmlspecialchars($order['special_instructions'])); ?><br>
                <?php endif; ?>
                <?php if ($order['customer_notes']): ?>
                <strong>Customer Notes:</strong> <?php echo nl2br(htmlspecialchars($order['customer_notes'])); ?>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- Processing Checklist -->
            <div class="processing-checklist">
                <strong>PROCESSING CHECKLIST:</strong><br>
                <div class="checkbox-item">
                    <span class="checkbox"></span> Items Sorted & Counted
                </div>
                <div class="checkbox-item">
                    <span class="checkbox"></span> Pre-treatment Applied
                </div>
                <div class="checkbox-item">
                    <span class="checkbox"></span> Washing/Cleaning Complete
                </div>
                <div class="checkbox-item">
                    <span class="checkbox"></span> Drying/Pressing Complete
                </div>
                <div class="checkbox-item">
                    <span class="checkbox"></span> Quality Check Done
                </div>
                <div class="checkbox-item">
                    <span class="checkbox"></span> Packaging Complete
                </div>
                <div class="checkbox-item">
                    <span class="checkbox"></span> Ready for Pickup/Delivery
                </div>
            </div>

            <!-- Processing Info -->
            <div style="display: flex; justify-content: space-between; font-size: 9px; margin: 6px 0;">
                <div>
                    <strong>Created By:</strong><br>
                    <?php echo $order['created_by_name']; ?>
                </div>
                <?php if ($order['assigned_to_name']): ?>
                <div>
                    <strong>Assigned To:</strong><br>
                    <?php echo $order['assigned_to_name']; ?>
                </div>
                <?php endif; ?>
                <div>
                    <strong>Priority:</strong><br>
                    <?php echo $order['priority']; ?>
                </div>
            </div>

            <!-- Status Tracking -->
            <div style="font-size: 9px; border: 1px solid #000; padding: 4px; margin: 6px 0;">
                <strong>STATUS TRACKING:</strong><br>
                <div style="display: flex; justify-content: space-between; margin-top: 3px;">
                    <span>RECEIVED: ___/___</span>
                    <span>IN-PROCESS: ___/___</span>
                    <span>READY: ___/___</span>
                    <span>DELIVERED: ___/___</span>
                </div>
            </div>

            <!-- Signatures -->
            <div class="signatures-section">
                <div class="signature-box">
                    PROCESSED BY
                </div>
                <div class="signature-box">
                    QUALITY CHECK
                </div>
            </div>

            <!-- Service Notes -->
            <div style="border: 1px solid #000; padding: 4px; margin: 6px 0; min-height: 20px;">
                <strong style="font-size: 9px;">SERVICE NOTES:</strong>
            </div>

            <!-- Total -->
            <div style="text-align: center; font-weight: bold; font-size: 10px; border: 2px solid #000; padding: 4px;">
                TOTAL: KSh <?php echo number_format($order['total_amount'], 2); ?>
                <?php if ($order['balance_amount'] > 0): ?>
                | BALANCE: KSh <?php echo number_format($order['balance_amount'], 2); ?>
                <?php else: ?>
                | PAID IN FULL
                <?php endif; ?>
            </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);
            };
        }
        
        // Keyboard shortcut for printing
        document.addEventListener('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                e.preventDefault();
                window.print();
            }
        });
        
        // Mobile adjustments
        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';
        }
        
        // Add click handlers for checkboxes (for interactive version)
        document.querySelectorAll('.checkbox').forEach(checkbox => {
            checkbox.addEventListener('click', function() {
                this.style.background = this.style.background === 'black' ? '' : 'black';
                this.innerHTML = this.style.background === 'black' ? '✓' : '';
                this.style.color = 'white';
            });
        });
    </script>
</body>
</html>