<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Print Selected QR Labels -- no waste!</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        /* Avery 5160 Label Sheet Styles - Exact Specifications */
        .label-sheet {
            width: 8.5in;
            height: 11in;
            margin: 0 auto;
            background: white;
            border: 2px solid #333;
            padding-top: 0.5in;
            padding-bottom: 0.5in;
            padding-left: 0.1875in;  /* 3/16" left margin */
            padding-right: 0.1875in; /* 3/16" right margin */
            display: grid;
            grid-template-columns: repeat(3, 2.625in); /* Fixed column width */
            grid-template-rows: repeat(10, 1in); /* Fixed row height */
            column-gap: 0.125in; /* 1/8" between columns */
            row-gap: 0in; /* No gap between rows */
            box-sizing: border-box;
        }
        
        .label {
            width: 2.625in;
            height: 1in;
            border: 1px solid #ccc;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 10px;
            text-align: center;
            background: #f8f9fa;
            position: relative;
        }
        
        .label:hover {
            background: #e9ecef;
            border-color: #007bff;
        }
        
        .label.selected {
            background: #007bff;
            color: white;
            border-color: #0056b3;
        }
        
        .label.selected::after {
            content: '✓';
            position: absolute;
            top: 2px;
            right: 4px;
            font-weight: bold;
            font-size: 12px;
        }
        
        .label-preview {
            width: 100%;
            height: 100%;
            display: none;
            padding: 4px;
            box-sizing: border-box;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
        }
        
        .label.selected .label-preview {
            display: flex;
        }
        
        .qr-section {
            width: 50%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .qr-mini {
            width: 64px;
            height: 64px;
            background: #333;
            flex-shrink: 0;
        }
        
        .info-section {
            width: 50%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .item-info {
            font-size: 7px;
            line-height: 1.2;
            text-align: center;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }
        
        .label-number {
            position: absolute;
            top: 2px;
            left: 2px;
            font-size: 8px;
            font-weight: bold;
            color: #666;
            z-index: 1;
        }
        
        .controls {
            margin-bottom: 20px;
        }
        
        .print-area {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
        }
        
        .selected-count {
            font-weight: bold;
            color: #007bff;
        }
        
        @media print {
            @page {
                size: 8.5in 11in;
                margin: 0;
            }
            
            body { 
                margin: 0; 
                padding: 0;
                background: white;
            }
            
            .controls, .navbar, .breadcrumb, .no-print { 
                display: none !important; 
            }
            
            .label-sheet { 
                margin: 0; 
                border: none; 
                width: 8.5in; 
                height: 11in; 
                padding-top: 0.5in;
                padding-bottom: 0.5in;
                padding-left: 0.1875in;
                padding-right: 0.1875in;
                page-break-after: avoid;
                grid-template-columns: repeat(3, 2.625in);
                grid-template-rows: repeat(10, 1in);
                column-gap: 0.125in;
                row-gap: 0in;
            }
            
            .label { 
                border: none; 
                background: white !important;
                color: black !important;
                width: 2.625in;
                height: 1in;
                padding: 0.05in;
            }
            
            .label:not(.selected) { 
                visibility: hidden; 
            }
            
            .label.selected .label-preview { 
                display: flex; 
            }
            
            .label.selected::after {
                display: none !important;
            }
            
            .qr-section {
                width: 50% !important;
                display: flex !important;
                align-items: center !important;
                justify-content: center !important;
            }
            
            .info-section {
                width: 50% !important;
                display: flex !important;
                align-items: center !important;
                justify-content: center !important;
            }
            
            .qr-mini, .qr-mini img {
                width: 64px !important;
                height: 64px !important;
                margin: 0 !important;
                display: block !important;
                print-color-adjust: exact !important;
                -webkit-print-color-adjust: exact !important;
            }
            
            .item-info {
                font-size: 6px !important;
                line-height: 1.1 !important;
            }
            
            .label-number {
                color: white !important;
                background: rgba(0,0,0,0.7) !important;
                padding: 1px 3px !important;
                border-radius: 2px !important;
                print-color-adjust: exact !important;
                -webkit-print-color-adjust: exact !important;
            }
        }
    </style>
</head>
<body>
    
    <div class="container-fluid no-print">
        <div class="row">
            <div class="col-12">
                <!-- Breadcrumbs -->
                <nav aria-label="breadcrumb" class="mt-3">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="/dashboard">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="/item/{{ item.id }}">{{ item.name }}</a></li>
                        <li class="breadcrumb-item active">Print Labels</li>
                    </ol>
                </nav>
                
                <!-- Header -->
                <div class="d-flex align-items-center mb-4">
                    <i class="fas fa-qrcode me-3" style="font-size: 2rem; color: #007bff;"></i>
                    <div>
                        <h1 class="h3 mb-1">Print QR Labels</h1>
                        <p class="text-muted mb-0">{{ item.name }} - Avery 5160 Label Sheet</p>
                    </div>
                </div>
                
                <!-- Controls -->
                <div class="controls">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">
                                        <i class="fas fa-mouse-pointer me-2"></i>Label Selection
                                    </h5>
                                    <p class="card-text">Click on labels below to select which positions to print on your Avery 5160 sheet.</p>
                                    <div class="d-flex gap-2 mb-3">
                                        <button class="btn btn-outline-primary btn-sm" onclick="selectAll()">
                                            <i class="fas fa-check-square me-1"></i>Select All
                                        </button>
                                        <button class="btn btn-outline-secondary btn-sm" onclick="clearAll()">
                                            <i class="fas fa-square me-1"></i>Clear All
                                        </button>
                                        <button class="btn btn-outline-info btn-sm" onclick="selectRange()">
                                            <i class="fas fa-list me-1"></i>Select Range
                                        </button>
                                    </div>
                                    <p class="mb-0">
                                        Selected: <span class="selected-count" id="selectedCount">0</span> of 30 labels
                                    </p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">
                                        <i class="fas fa-print me-2"></i>Print Settings
                                    </h5>
                                    <p class="card-text">Each label has QR code on left, item name, owner name, and contact info on right.</p>
                                    <button class="btn btn-success" onclick="printLabels()" disabled id="printBtn">
                                        <i class="fas fa-print me-2"></i>Print Selected Labels
                                    </button>
                                    <div class="mt-2">
                                        <small class="text-muted">
                                            <i class="fas fa-info-circle me-1"></i>
                                            Make sure to load Avery 5160 labels in your printer
                                        </small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Label Sheet -->
    <div class="print-area no-print">
        <div class="text-center mb-3">
            <h4>Avery 5160 Label Sheet Preview</h4>
            <p class="text-muted">30 labels (3 columns × 10 rows) - Click to select positions</p>
        </div>
    </div>
    
    <div class="label-sheet" id="labelSheet">
        <!-- Generate 30 labels (3 columns × 10 rows) -->
        {% for i in 1..30 %}
        <div class="label" data-position="{{ i }}" onclick="toggleLabel({{ i }})">
            <div class="label-number">{{ i }}</div>
            <div class="label-preview">
                <div class="qr-section">
                    <div class="qr-mini" id="qr-{{ i }}"></div>
                </div>
                <div class="info-section">
                    <div class="item-info">
                        <div style="font-weight: bold; font-size: 7px; margin-bottom: 1px; line-height: 1.1;">{{ item.name }}</div>
                        <div style="font-size: 7px; margin-bottom: 1px;">locallendables.com</div>
                        <div style="font-size: 6px; margin-bottom: 1px;">{{ owner.firstName }} {{ owner.lastName }}</div>
                        <div style="font-size: 6px;">{{ ownerPhone ?: 'No phone' }}</div>
                    </div>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    
    <!-- Range Selection Modal -->
    <div class="modal fade" id="rangeModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Select Label Range</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <label for="rangeStart" class="form-label">From Position:</label>
                            <input type="number" class="form-control" id="rangeStart" min="1" max="30" value="1">
                        </div>
                        <div class="col-md-6">
                            <label for="rangeEnd" class="form-label">To Position:</label>
                            <input type="number" class="form-control" id="rangeEnd" min="1" max="30" value="30">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="applyRange()">Select Range</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Toast Container -->
    <div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 9999;">
        <div id="successToast" class="toast align-items-center text-white bg-success border-0" role="alert">
            <div class="d-flex">
                <div class="toast-body" id="toastMessage"></div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js"></script>
    <script>
        let selectedLabels = new Set();
        const itemData = {
            id: {{ item.id }},
            name: "{{ item.name | e('js') }}",
            url: "{{ qrUrl | e('js') }}",
            phone: "{{ ownerPhone | e('js') }}"
        };
        
        // Generate QR codes for all labels using server-side API
        function generateQRCodes() {
            console.log('Generating QR codes for URL:', itemData.url);
            
            for (let i = 1; i <= 30; i++) {
                const qrElement = document.getElementById(`qr-${i}`);
                if (qrElement) {
                    // Use server-side QR generation API for more reliable results (64px with 4px border = 72px total)
                    const qrImageUrl = `/api/generate-qr-image?text=${encodeURIComponent(itemData.url)}&size=72`;
                    qrElement.innerHTML = `<img src="${qrImageUrl}" style="width: 64px; height: 64px; display: block;" alt="QR Code" onerror="console.error('QR image failed to load:', this.src)">`;
                }
            }
        }
        
        function toggleLabel(position) {
            const label = document.querySelector(`[data-position="${position}"]`);
            const printBtn = document.getElementById('printBtn');
            
            if (selectedLabels.has(position)) {
                selectedLabels.delete(position);
                label.classList.remove('selected');
            } else {
                selectedLabels.add(position);
                label.classList.add('selected');
            }
            
            updateSelectedCount();
            printBtn.disabled = selectedLabels.size === 0;
        }
        
        function selectAll() {
            for (let i = 1; i <= 30; i++) {
                selectedLabels.add(i);
                document.querySelector(`[data-position="${i}"]`).classList.add('selected');
            }
            updateSelectedCount();
            document.getElementById('printBtn').disabled = false;
        }
        
        function clearAll() {
            selectedLabels.clear();
            document.querySelectorAll('.label').forEach(label => {
                label.classList.remove('selected');
            });
            updateSelectedCount();
            document.getElementById('printBtn').disabled = true;
        }
        
        function selectRange() {
            const modal = new bootstrap.Modal(document.getElementById('rangeModal'));
            modal.show();
        }
        
        function applyRange() {
            const start = parseInt(document.getElementById('rangeStart').value);
            const end = parseInt(document.getElementById('rangeEnd').value);
            
            if (start <= end && start >= 1 && end <= 30) {
                clearAll();
                for (let i = start; i <= end; i++) {
                    selectedLabels.add(i);
                    document.querySelector(`[data-position="${i}"]`).classList.add('selected');
                }
                updateSelectedCount();
                document.getElementById('printBtn').disabled = false;
                
                const modal = bootstrap.Modal.getInstance(document.getElementById('rangeModal'));
                modal.hide();
                
                showToast(`Selected labels ${start} to ${end}`);
            } else {
                alert('Please enter a valid range (1-30)');
            }
        }
        
        function updateSelectedCount() {
            document.getElementById('selectedCount').textContent = selectedLabels.size;
        }
        
        function printLabels() {
            if (selectedLabels.size === 0) {
                alert('Please select at least one label position');
                return;
            }
            
            // Hide non-selected labels for printing (visibility instead of display to preserve grid layout)
            document.querySelectorAll('.label').forEach(label => {
                const position = parseInt(label.getAttribute('data-position'));
                if (!selectedLabels.has(position)) {
                    label.style.visibility = 'hidden';
                } else {
                    label.style.visibility = 'visible';
                }
            });
            
            // Print
            window.print();
            
            // Show all labels again after printing
            setTimeout(() => {
                document.querySelectorAll('.label').forEach(label => {
                    label.style.visibility = 'visible';
                });
            }, 1000);
            
            // Note: Removed automatic success message to avoid showing success for cancelled prints
            // Users will know if their print succeeded by checking their printer
        }
        
        function showToast(message) {
            document.getElementById('toastMessage').textContent = message;
            const toast = new bootstrap.Toast(document.getElementById('successToast'));
            toast.show();
        }
        
        // Initialize QR codes when page loads
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM loaded, starting QR generation...');
            generateQRCodes();
            
            // Debug: Check if QR codes loaded after a short delay
            setTimeout(() => {
                const firstQR = document.querySelector('#qr-1 img');
                if (firstQR) {
                    console.log('QR image loaded successfully:', firstQR.src);
                } else {
                    console.error('QR image not found - generation may have failed');
                }
            }, 2000);
        });
    </script>
</body>
</html>