/**
 * KSO Chandigarh Print System
 * Enhanced printing functionality for reports, member data, and documents
 */

// Global functions for easier access to print functionality
// These will be available in the global scope for direct use

/**
 * Print a table with enhanced formatting
 * @param {string|Element} tableSelector - Table element or selector to print
 * @param {string} title - Optional title for the printed page
 */
function printTable(tableSelector, title) {
    if (!window.ksoPrint) {
        console.error('KSO Print System not initialized');
        return;
    }
    
    const table = typeof tableSelector === 'string' ? 
        document.querySelector(tableSelector) : tableSelector;
    
    if (!table) {
        console.error('Table element not found:', tableSelector);
        return;
    }
    
    window.ksoPrint.printTable(table, { 
        title: title || 'KUKI STUDENTS\' ORGANISATION - Table Data',
        includeHeader: true,
        includeFooter: true,
        includeWatermark: true
    });
}

/**
 * Print member cards
 * @param {Array|string} members - Member data or selector for member elements
 */
function printMemberCards(members) {
    if (!window.ksoPrint) {
        console.error('KSO Print System not initialized');
        return;
    }
    
    window.ksoPrint.printMemberCards({
        includeHeader: true,
        includeFooter: true,
        includeWatermark: true,
        includeQR: true,
        title: 'KUKI STUDENTS\' ORGANISATION - Member Cards'
    });
}

/**
 * Print a financial report
 * @param {Object|string} data - Report data or selector for report element
 */
function printFinancialReport(data) {
    if (!window.ksoPrint) {
        console.error('KSO Print System not initialized');
        return;
    }
    
    window.ksoPrint.printFinancialReport({
        includeHeader: true,
        includeFooter: true,
        includeWatermark: true,
        title: 'KUKI STUDENTS\' ORGANISATION - Financial Report'
    });
}

class KSOPrintSystem {
    constructor() {
        this.printStyles = '';
        this.init();
    }

    init() {
        this.addPrintStyles();
        this.createPrintButtons();
    }

    addPrintStyles() {
        const style = document.createElement('style');
        style.textContent = `
            /* Print Styles */
            @media print {
                * {
                    -webkit-print-color-adjust: exact !important;
                    color-adjust: exact !important;
                }

                body {
                    margin: 0;
                    padding: 0;
                    font-family: Arial, sans-serif;
                    font-size: 12px;
                    line-height: 1.4;
                }

                .no-print {
                    display: none !important;
                }

                .print-only {
                    display: block !important;
                }

                .main-header,
                .main-sidebar,
                .main-footer,
                .content-header,
                .breadcrumb,
                .btn,
                .form-control,
                .pagination,
                .modal,
                .toast-container,
                .preloader {
                    display: none !important;
                }

                .content-wrapper {
                    margin-left: 0 !important;
                    padding: 0 !important;
                }

                .kso-print-header {
                    text-align: center;
                    margin-bottom: 30px;
                    padding-bottom: 20px;
                    border-bottom: 2px solid #333;
                }

                .kso-print-logo {
                    max-width: 100px;
                    height: auto;
                    margin-bottom: 10px;
                }

                .kso-print-title {
                    font-size: 24px;
                    font-weight: bold;
                    color: #333;
                    margin: 10px 0;
                }

                .kso-print-subtitle {
                    font-size: 16px;
                    color: #666;
                    margin: 5px 0;
                }

                .kso-print-date {
                    font-size: 12px;
                    color: #999;
                    margin-top: 10px;
                }

                .kso-print-footer {
                    position: fixed;
                    bottom: 0;
                    left: 0;
                    right: 0;
                    text-align: center;
                    font-size: 10px;
                    color: #666;
                    padding: 10px;
                    border-top: 1px solid #ddd;
                }

                .kso-print-table {
                    width: 100%;
                    border-collapse: collapse;
                    margin-bottom: 20px;
                }

                .kso-print-table th,
                .kso-print-table td {
                    border: 1px solid #ddd;
                    padding: 8px;
                    text-align: left;
                    font-size: 11px;
                }

                .kso-print-table th {
                    background-color: #f8f9fa;
                    font-weight: bold;
                }

                .kso-print-section {
                    margin-bottom: 25px;
                    page-break-inside: avoid;
                }

                .kso-print-section-title {
                    font-size: 16px;
                    font-weight: bold;
                    margin-bottom: 10px;
                    color: #333;
                    border-bottom: 1px solid #ddd;
                    padding-bottom: 5px;
                }

                .kso-print-member-card {
                    border: 1px solid #ddd;
                    padding: 15px;
                    margin-bottom: 15px;
                    page-break-inside: avoid;
                }

                .kso-print-member-photo {
                    float: right;
                    width: 80px;
                    height: 80px;
                    border: 1px solid #ddd;
                    margin-left: 15px;
                }

                .kso-print-qr-code {
                    text-align: center;
                    margin-top: 15px;
                }

                .kso-print-qr-code img {
                    max-width: 100px;
                    height: auto;
                }

                .page-break {
                    page-break-after: always;
                }

                .kso-print-watermark {
                    position: fixed;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%) rotate(-45deg);
                    font-size: 72px;
                    color: rgba(0, 0, 0, 0.05);
                    z-index: -1;
                    font-weight: bold;
                }
            }

            /* Print Button Styles */
            .kso-print-btn {
                background: #007bff;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
                margin: 5px;
                display: inline-flex;
                align-items: center;
                gap: 5px;
                transition: background-color 0.2s ease;
            }

            .kso-print-btn:hover {
                background: #0056b3;
            }

            .kso-print-btn i {
                font-size: 16px;
            }

            .kso-print-options {
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: white;
                border: 1px solid #ddd;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                padding: 20px;
                z-index: 9999;
                min-width: 300px;
                display: none;
            }

            .kso-print-options.show {
                display: block;
            }

            .kso-print-options-overlay {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.5);
                z-index: 9998;
                display: none;
            }

            .kso-print-options-overlay.show {
                display: block;
            }

            .kso-print-options-title {
                font-size: 18px;
                font-weight: bold;
                margin-bottom: 15px;
                color: #333;
            }

            .kso-print-options-form {
                display: flex;
                flex-direction: column;
                gap: 15px;
            }

            .kso-print-options-group {
                display: flex;
                flex-direction: column;
                gap: 5px;
            }

            .kso-print-options-label {
                font-size: 14px;
                font-weight: 500;
                color: #333;
            }

            .kso-print-options-input {
                padding: 8px;
                border: 1px solid #ddd;
                border-radius: 4px;
                font-size: 14px;
            }

            .kso-print-options-checkbox {
                display: flex;
                align-items: center;
                gap: 8px;
            }

            .kso-print-options-actions {
                display: flex;
                gap: 10px;
                justify-content: flex-end;
                margin-top: 15px;
            }

            .kso-print-options-btn {
                padding: 8px 16px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
                transition: background-color 0.2s ease;
            }

            .kso-print-options-btn.primary {
                background: #007bff;
                color: white;
            }

            .kso-print-options-btn.primary:hover {
                background: #0056b3;
            }

            .kso-print-options-btn.secondary {
                background: #6c757d;
                color: white;
            }

            .kso-print-options-btn.secondary:hover {
                background: #545b62;
            }
        `;
        document.head.appendChild(style);
    }

    createPrintButtons() {
        // Add print buttons to existing tables and sections
        const tables = document.querySelectorAll('table');
        tables.forEach(table => {
            const parent = table.closest('.card, .kso-widget');
            if (parent && !parent.querySelector('.kso-print-btn')) {
                const header = parent.querySelector('.card-header, .kso-widget-header');
                if (header) {
                    const printBtn = document.createElement('button');
                    printBtn.className = 'kso-print-btn no-print';
                    printBtn.innerHTML = '<i class="fas fa-print"></i> Print';
                    printBtn.onclick = () => this.showPrintOptions(table);
                    
                    const tools = header.querySelector('.card-tools, .kso-widget-actions');
                    if (tools) {
                        tools.appendChild(printBtn);
                    } else {
                        header.appendChild(printBtn);
                    }
                }
            }
        });
    }

    showPrintOptions(element) {
        const overlay = document.createElement('div');
        overlay.className = 'kso-print-options-overlay';
        overlay.onclick = () => this.closePrintOptions();

        const modal = document.createElement('div');
        modal.className = 'kso-print-options';
        modal.innerHTML = `
            <div class="kso-print-options-title">Print Options</div>
            <div class="kso-print-options-form">
                <div class="kso-print-options-group">
                    <label class="kso-print-options-label">Document Title</label>
                    <input type="text" class="kso-print-options-input" id="print-title" value="KSO Chandigarh Report">
                </div>
                <div class="kso-print-options-group">
                    <label class="kso-print-options-label">Report Type</label>
                    <select class="kso-print-options-input" id="print-type">
                        <option value="table">Table Report</option>
                        <option value="member-cards">Member Cards</option>
                        <option value="financial">Financial Report</option>
                        <option value="activity">Activity Report</option>
                    </select>
                </div>
                <div class="kso-print-options-group">
                    <div class="kso-print-options-checkbox">
                        <input type="checkbox" id="print-header" checked>
                        <label for="print-header">Include Header</label>
                    </div>
                </div>
                <div class="kso-print-options-group">
                    <div class="kso-print-options-checkbox">
                        <input type="checkbox" id="print-footer" checked>
                        <label for="print-footer">Include Footer</label>
                    </div>
                </div>
                <div class="kso-print-options-group">
                    <div class="kso-print-options-checkbox">
                        <input type="checkbox" id="print-watermark">
                        <label for="print-watermark">Add Watermark</label>
                    </div>
                </div>
                <div class="kso-print-options-group">
                    <div class="kso-print-options-checkbox">
                        <input type="checkbox" id="print-qr" checked>
                        <label for="print-qr">Include QR Codes (Member Cards)</label>
                    </div>
                </div>
            </div>
            <div class="kso-print-options-actions">
                <button class="kso-print-options-btn secondary" onclick="window.ksoPrint.closePrintOptions()">Cancel</button>
                <button class="kso-print-options-btn primary" onclick="window.ksoPrint.executePrint()">Print</button>
            </div>
        `;

        document.body.appendChild(overlay);
        document.body.appendChild(modal);
        
        overlay.classList.add('show');
        modal.classList.add('show');
        
        this.currentElement = element;
    }

    closePrintOptions() {
        const overlay = document.querySelector('.kso-print-options-overlay');
        const modal = document.querySelector('.kso-print-options');
        
        if (overlay) overlay.remove();
        if (modal) modal.remove();
    }

    executePrint() {
        const title = document.getElementById('print-title').value;
        const type = document.getElementById('print-type').value;
        const includeHeader = document.getElementById('print-header').checked;
        const includeFooter = document.getElementById('print-footer').checked;
        const includeWatermark = document.getElementById('print-watermark').checked;
        const includeQR = document.getElementById('print-qr').checked;

        this.closePrintOptions();

        switch (type) {
            case 'table':
                this.printTable(this.currentElement, { title, includeHeader, includeFooter, includeWatermark });
                break;
            case 'member-cards':
                this.printMemberCards({ title, includeHeader, includeFooter, includeWatermark, includeQR });
                break;
            case 'financial':
                this.printFinancialReport({ title, includeHeader, includeFooter, includeWatermark });
                break;
            case 'activity':
                this.printActivityReport({ title, includeHeader, includeFooter, includeWatermark });
                break;
        }
    }

    printTable(table, options = {}) {
        // First check if this is a DataTable
        let tableData = null;
        let tableHtml = '';
        
        if ($.fn.DataTable.isDataTable(table)) {
            const dataTable = $(table).DataTable();
            tableData = dataTable.data().toArray();
            
            // Build HTML table from scratch with clean data
            const columnHeaders = [];
            dataTable.columns().every(function(index) {
                // Skip action columns (typically the last column)
                if (index < dataTable.columns().nodes().length - 1) {
                    columnHeaders.push($(dataTable.column(index).header()).text());
                }
            });
            
            tableHtml = '<table class="kso-print-table">';
            tableHtml += '<thead><tr>';
            
            // Add headers
            columnHeaders.forEach(header => {
                tableHtml += `<th>${header}</th>`;
            });
            
            tableHtml += '</tr></thead><tbody>';
            
            // Add data rows
            tableData.forEach(row => {
                tableHtml += '<tr>';
                // Loop through each cell excluding last column (actions)
                for (let i = 0; i < columnHeaders.length; i++) {
                    if (typeof row[i] === 'object' && row[i] !== null) {
                        // Handle objects (e.g., formatted data)
                        tableHtml += `<td>${row[i].display || JSON.stringify(row[i])}</td>`;
                    } else {
                        tableHtml += `<td>${row[i] || ''}</td>`;
                    }
                }
                tableHtml += '</tr>';
            });
            
            tableHtml += '</tbody></table>';
        } else {
            // If not a DataTable, clone the regular table
            const tableClone = table.cloneNode(true);
            
            // Clean up table for printing
            tableClone.className = 'kso-print-table';
            const actionColumns = tableClone.querySelectorAll('th:last-child, td:last-child');
            actionColumns.forEach(col => {
                if (col.textContent.includes('Actions') || col.querySelector('button')) {
                    col.style.display = 'none';
                }
            });
            
            tableHtml = tableClone.outerHTML;
        }
        
        const printContent = this.generatePrintDocument(tableHtml, options);
        
        const printWindow = window.open('', '_blank');
        printWindow.document.write(printContent);
        printWindow.document.close();
        
        // Wait for resources to load before printing
        setTimeout(() => {
            printWindow.print();
        }, 500);
    }

    printMemberCards(options = {}) {
        // Show loading indicator
        const loadingToast = showToast('Fetching member data...', 'info', { timeOut: 0 });
        
        // Fetch actual member data from API
        $.ajax({
            url: 'api/members/list.php',
            method: 'GET',
            dataType: 'json',
            success: (response) => {
                if (response.success && response.data) {
                    // Hide loading toast
                    toastr.clear(loadingToast);
                    
                    const memberCards = this.generateMemberCards(response.data, options);
                    const printContent = this.generatePrintDocument(memberCards, options);
                    
                    const printWindow = window.open('', '_blank');
                    printWindow.document.write(printContent);
                    printWindow.document.close();
                    
                    // Wait for resources to load before printing
                    setTimeout(() => {
                        printWindow.print();
                    }, 500);
                } else {
                    toastr.clear(loadingToast);
                    showToast('Failed to fetch member data', 'error');
                }
            },
            error: () => {
                toastr.clear(loadingToast);
                showToast('Error connecting to server', 'error');
            }
        });
    }

    printFinancialReport(options = {}) {
        // Try to fetch real financial data if available
        try {
            $.ajax({
                url: 'api/finance/summary.php',
                method: 'GET',
                dataType: 'json',
                success: (response) => {
                    const financialData = this.generateFinancialReport(options);
                    const printContent = this.generatePrintDocument(financialData, options);
                    
                    const printWindow = window.open('', '_blank');
                    printWindow.document.write(printContent);
                    printWindow.document.close();
                    
                    // Wait for resources to load before printing
                    setTimeout(() => {
                        printWindow.print();
                    }, 500);
                },
                error: () => {
                    // Fall back to static data in case of error
                    const financialData = this.generateFinancialReport(options);
                    const printContent = this.generatePrintDocument(financialData, options);
                    
                    const printWindow = window.open('', '_blank');
                    printWindow.document.write(printContent);
                    printWindow.document.close();
                    
                    setTimeout(() => {
                        printWindow.print();
                    }, 500);
                }
            });
        } catch (e) {
            // Handle any exceptions
            const financialData = this.generateFinancialReport(options);
            const printContent = this.generatePrintDocument(financialData, options);
            
            const printWindow = window.open('', '_blank');
            printWindow.document.write(printContent);
            printWindow.document.close();
            
            setTimeout(() => {
                printWindow.print();
            }, 500);
        }
    }

    printActivityReport(options = {}) {
        // Try to fetch real activity data if available
        try {
            $.ajax({
                url: 'api/logs/activity-log.php',
                method: 'GET',
                dataType: 'json',
                success: (response) => {
                    let activityData = '';
                    
                    if (response.success && response.data && response.data.length > 0) {
                        activityData = `
                            <div class="kso-print-section">
                                <div class="kso-print-section-title">Recent Activities</div>
                                ${response.data.map(activity => `
                                    <div class="kso-print-activity-item">
                                        <strong>${activity.timestamp || ''}</strong> - ${activity.description || ''}
                                    </div>
                                `).join('')}
                            </div>
                        `;
                    } else {
                        activityData = this.generateActivityReport(options);
                    }
                    
                    const printContent = this.generatePrintDocument(activityData, options);
                    
                    const printWindow = window.open('', '_blank');
                    printWindow.document.write(printContent);
                    printWindow.document.close();
                    
                    // Wait for resources to load before printing
                    setTimeout(() => {
                        printWindow.print();
                    }, 500);
                },
                error: () => {
                    // Fall back to static data in case of error
                    const activityData = this.generateActivityReport(options);
                    const printContent = this.generatePrintDocument(activityData, options);
                    
                    const printWindow = window.open('', '_blank');
                    printWindow.document.write(printContent);
                    printWindow.document.close();
                    
                    setTimeout(() => {
                        printWindow.print();
                    }, 500);
                }
            });
        } catch (e) {
            // Handle any exceptions
            const activityData = this.generateActivityReport(options);
            const printContent = this.generatePrintDocument(activityData, options);
            
            const printWindow = window.open('', '_blank');
            printWindow.document.write(printContent);
            printWindow.document.close();
            
            setTimeout(() => {
                printWindow.print();
            }, 500);
        }
    }

    generatePrintDocument(content, options = {}) {
        const header = options.includeHeader ? `
            <div class="kso-print-header">
                <img src="public/KSO LOGO.png" alt="KSO Logo" class="kso-print-logo">
                <div class="kso-print-title">KUKI STUDENTS' ORGANISATION</div>
                <div class="kso-print-subtitle">Chandigarh</div>
                <div class="kso-print-subtitle">${options.title || 'Report'}</div>
                <div class="kso-print-date">Generated on: ${new Date().toLocaleDateString()}</div>
            </div>
        ` : '';

        const footer = options.includeFooter ? `
            <div class="kso-print-footer">
                <div>© ${new Date().getFullYear()} KUKI STUDENTS' ORGANISATION Chandigarh. All rights reserved.</div>
                <div>This document is computer generated and does not require signature.</div>
            </div>
        ` : '';

        const watermark = options.includeWatermark !== false ? `
            <div class="kso-print-watermark">
                <img src="public/KSO LOGO.png" alt="KSO Logo" class="kso-print-watermark-image">
            </div>
        ` : '';

        return `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <title>${options.title || 'KSO Chandigarh Report'}</title>
                <style>
                    ${this.getPrintStyles()}
                </style>
            </head>
            <body>
                ${watermark}
                ${header}
                <div class="kso-print-content">
                    ${content}
                </div>
                ${footer}
            </body>
            </html>
        `;
    }

    generateMemberCards(members, options = {}) {
        if (!Array.isArray(members) || members.length === 0) {
            // Fallback to sample data if no members provided
            members = [
                {
                    kso_id: 'KSO001',
                    first_name: 'John',
                    last_name: 'Doe',
                    email: 'john@example.com',
                    phone: '+91 98765 43210',
                    college: 'DAV College',
                    course: 'B.Tech CSE',
                    membership_type: 'Individual',
                    photo: 'uploads/members/default.png'
                }
            ];
        }

        return members.map(member => `
            <div class="kso-print-member-card">
                <img src="${member.photo || 'uploads/members/default.png'}" alt="${member.first_name} ${member.last_name}" class="kso-print-member-photo">
                <div>
                    <strong>Member ID:</strong> ${member.kso_id || 'N/A'}<br>
                    <strong>Name:</strong> ${member.first_name} ${member.last_name}<br>
                    <strong>Email:</strong> ${member.email || 'N/A'}<br>
                    <strong>Phone:</strong> ${member.phone || 'N/A'}<br>
                    <strong>College:</strong> ${member.college || 'N/A'}<br>
                    <strong>Course:</strong> ${member.course || 'N/A'}<br>
                    <strong>Membership:</strong> ${member.membership_type || 'Regular'}
                </div>
                ${options.includeQR ? `
                    <div class="kso-print-qr-code">
                        <img src="https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=${member.kso_id || ''}" alt="QR Code">
                    </div>
                ` : ''}
            </div>
        `).join('');
    }

    generateFinancialReport(options = {}) {
        return `
            <div class="kso-print-section">
                <div class="kso-print-section-title">Financial Summary</div>
                <table class="kso-print-table">
                    <tr>
                        <th>Category</th>
                        <th>Amount (₹)</th>
                        <th>Status</th>
                    </tr>
                    <tr>
                        <td>Membership Fees</td>
                        <td>₹50,000</td>
                        <td>Collected</td>
                    </tr>
                    <tr>
                        <td>Event Revenue</td>
                        <td>₹25,000</td>
                        <td>Collected</td>
                    </tr>
                    <tr>
                        <td>Operational Expenses</td>
                        <td>₹15,000</td>
                        <td>Paid</td>
                    </tr>
                    <tr>
                        <td>Event Expenses</td>
                        <td>₹20,000</td>
                        <td>Paid</td>
                    </tr>
                    <tr>
                        <td><strong>Net Balance</strong></td>
                        <td><strong>₹40,000</strong></td>
                        <td><strong>Available</strong></td>
                    </tr>
                </table>
            </div>
        `;
    }

    generateActivityReport(options = {}) {
        return `
            <div class="kso-print-section">
                <div class="kso-print-section-title">Recent Activities</div>
                <div class="kso-print-activity-item">
                    <strong>2024-01-15 10:30 AM</strong> - New member registration: John Doe
                </div>
                <div class="kso-print-activity-item">
                    <strong>2024-01-14 03:45 PM</strong> - Event "Cultural Night" created
                </div>
                <div class="kso-print-activity-item">
                    <strong>2024-01-14 11:20 AM</strong> - Membership fee payment received: ₹1,000
                </div>
                <div class="kso-print-activity-item">
                    <strong>2024-01-13 09:15 AM</strong> - System backup completed successfully
                </div>
            </div>
        `;
    }

    getPrintStyles() {
        return `
            @media print {
                * { -webkit-print-color-adjust: exact !important; color-adjust: exact !important; }
                body { margin: 0; padding: 20px; font-family: Arial, sans-serif; font-size: 12px; line-height: 1.4; }
                .kso-print-header { text-align: center; margin-bottom: 30px; padding-bottom: 20px; border-bottom: 2px solid #333; }
                .kso-print-logo { max-width: 100px; height: auto; margin-bottom: 10px; }
                .kso-print-title { font-size: 24px; font-weight: bold; color: #333; margin: 10px 0; }
                .kso-print-subtitle { font-size: 16px; color: #666; margin: 5px 0; }
                .kso-print-date { font-size: 12px; color: #999; margin-top: 10px; }
                .kso-print-footer { position: fixed; bottom: 20px; left: 0; right: 0; text-align: center; font-size: 10px; color: #666; padding: 10px; border-top: 1px solid #ddd; }
                .kso-print-table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
                .kso-print-table th, .kso-print-table td { border: 1px solid #ddd; padding: 8px; text-align: left; font-size: 11px; }
                .kso-print-table th { background-color: #f8f9fa !important; font-weight: bold; }
                .kso-print-section { margin-bottom: 25px; page-break-inside: avoid; }
                .kso-print-section-title { font-size: 16px; font-weight: bold; margin-bottom: 10px; color: #333; border-bottom: 1px solid #ddd; padding-bottom: 5px; }
                .kso-print-member-card { border: 1px solid #ddd; padding: 15px; margin-bottom: 15px; page-break-inside: avoid; }
                .kso-print-member-photo { float: right; width: 80px; height: 80px; border: 1px solid #ddd; margin-left: 15px; object-fit: cover; }
                .kso-print-qr-code { text-align: center; margin-top: 15px; }
                .kso-print-qr-code img { max-width: 100px; height: auto; }
                .kso-print-watermark { position: fixed; top: 0; left: 0; right: 0; bottom: 0; display: flex; justify-content: center; align-items: center; z-index: -1; pointer-events: none; }
                .kso-print-watermark-image { opacity: 0.08; width: 50%; max-width: 400px; transform: rotate(-30deg); }
                .kso-print-activity-item { margin-bottom: 10px; padding: 5px 0; border-bottom: 1px solid #eee; }
                
                /* Ensure page breaks don't split important content */
                tr, td, th { page-break-inside: avoid; }
                h1, h2, h3, h4, h5, h6 { page-break-after: avoid; }
                img, svg { page-break-inside: avoid; }
                
                /* Ensure URLs and table rows print properly */
                a[href^="http"]:after { content: " (" attr(href) ")"; font-size: 90%; }
                
                /* Print grid layouts correctly */
                .row { display: flex; flex-wrap: wrap; }
                .col, .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, 
                .col-7, .col-8, .col-9, .col-10, .col-11, .col-12 { position: relative; width: 100%; }
                
                /* Adjust column widths for print */
                .col-print-1 { flex: 0 0 8.333333%; max-width: 8.333333%; }
                .col-print-2 { flex: 0 0 16.666667%; max-width: 16.666667%; }
                .col-print-3 { flex: 0 0 25%; max-width: 25%; }
                .col-print-4 { flex: 0 0 33.333333%; max-width: 33.333333%; }
                .col-print-5 { flex: 0 0 41.666667%; max-width: 41.666667%; }
                .col-print-6 { flex: 0 0 50%; max-width: 50%; }
                .col-print-7 { flex: 0 0 58.333333%; max-width: 58.333333%; }
                .col-print-8 { flex: 0 0 66.666667%; max-width: 66.666667%; }
                .col-print-9 { flex: 0 0 75%; max-width: 75%; }
                .col-print-10 { flex: 0 0 83.333333%; max-width: 83.333333%; }
                .col-print-11 { flex: 0 0 91.666667%; max-width: 91.666667%; }
                .col-print-12 { flex: 0 0 100%; max-width: 100%; }
            }
        `;
    }

    // Quick print methods
    quickPrint(selector) {
        const element = document.querySelector(selector);
        if (element) {
            this.printTable(element, { title: 'Quick Print', includeHeader: true, includeFooter: true });
        }
    }

    printPage() {
        window.print();
    }

    exportToPDF(element, filename = 'kso-report.pdf') {
        // This would require a PDF library like jsPDF or html2pdf
        console.log('PDF export functionality would go here');
    }
}

// Initialize print system
document.addEventListener('DOMContentLoaded', () => {
    window.ksoPrint = new KSOPrintSystem();
});

// Utility function for showing toast notifications
function showToast(message, type = 'info', options = {}) {
    if (typeof toastr !== 'undefined') {
        return toastr[type](message, '', options);
    } else {
        console.log(`${type.toUpperCase()}: ${message}`);
        return null;
    }
}
