// Custom JavaScript for Quotation System

document.addEventListener('DOMContentLoaded', function() {
    // Initialize tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // Auto-hide alerts after 5 seconds
    setTimeout(function() {
        var alerts = document.querySelectorAll('.alert');
        alerts.forEach(function(alert) {
            var bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 5000);

    // Form validation
    var forms = document.querySelectorAll('.needs-validation');
    Array.prototype.slice.call(forms).forEach(function(form) {
        form.addEventListener('submit', function(event) {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        }, false);
    });

    // Confirm delete actions
    var deleteButtons = document.querySelectorAll('[data-confirm-delete]');
    deleteButtons.forEach(function(button) {
        button.addEventListener('click', function(e) {
            var message = this.getAttribute('data-confirm-message') || 'Are you sure you want to delete this item?';
            if (!confirm(message)) {
                e.preventDefault();
            }
        });
    });

    // Auto-format phone numbers
    var phoneInputs = document.querySelectorAll('input[type="tel"], input[name*="phone"], input[name*="contact"]');
    phoneInputs.forEach(function(input) {
        input.addEventListener('input', function() {
            var value = this.value.replace(/\D/g, '');
            if (value.length >= 10) {
                value = value.substring(0, 10);
            }
            this.value = value;
        });
    });

    // Auto-format currency inputs
    var currencyInputs = document.querySelectorAll('input[name*="price"], input[name*="rate"], input[name*="amount"]');
    currencyInputs.forEach(function(input) {
        input.addEventListener('blur', function() {
            var value = parseFloat(this.value);
            if (!isNaN(value)) {
                this.value = value.toFixed(2);
            }
        });
    });

    // Search functionality
    var searchInputs = document.querySelectorAll('input[name="search"]');
    searchInputs.forEach(function(input) {
        var timeout;
        input.addEventListener('input', function() {
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                // Auto-submit search form after 500ms of no typing
                var form = input.closest('form');
                if (form) {
                    form.submit();
                }
            }, 500);
        });
    });

    // Table row selection
    var selectAllCheckboxes = document.querySelectorAll('input[type="checkbox"][data-select-all]');
    selectAllCheckboxes.forEach(function(checkbox) {
        checkbox.addEventListener('change', function() {
            var table = this.closest('table');
            var rowCheckboxes = table.querySelectorAll('tbody input[type="checkbox"]');
            rowCheckboxes.forEach(function(rowCheckbox) {
                rowCheckbox.checked = checkbox.checked;
            });
        });
    });

    // Dynamic form fields
    var addButtons = document.querySelectorAll('[data-add-field]');
    addButtons.forEach(function(button) {
        button.addEventListener('click', function() {
            var template = document.querySelector(this.getAttribute('data-template'));
            var container = document.querySelector(this.getAttribute('data-container'));
            
            if (template && container) {
                var clone = template.content.cloneNode(true);
                container.appendChild(clone);
                
                // Re-initialize any JavaScript for the new fields
                initializeNewFields(clone);
            }
        });
    });

    // Remove field buttons
    document.addEventListener('click', function(e) {
        if (e.target.matches('[data-remove-field]')) {
            var field = e.target.closest('[data-field]');
            if (field) {
                field.remove();
            }
        }
    });

    // Print functionality
    var printButtons = document.querySelectorAll('[data-print]');
    printButtons.forEach(function(button) {
        button.addEventListener('click', function() {
            window.print();
        });
    });

    // Copy to clipboard functionality
    var copyButtons = document.querySelectorAll('[data-copy]');
    copyButtons.forEach(function(button) {
        button.addEventListener('click', function() {
            var text = this.getAttribute('data-copy');
            navigator.clipboard.writeText(text).then(function() {
                showToast('Copied to clipboard!', 'success');
            });
        });
    });

    // Initialize date pickers
    var dateInputs = document.querySelectorAll('input[type="date"]');
    dateInputs.forEach(function(input) {
        if (!input.value) {
            // Set default date to today
            input.value = new Date().toISOString().split('T')[0];
        }
    });

    // Initialize number inputs with proper formatting
    var numberInputs = document.querySelectorAll('input[type="number"]');
    numberInputs.forEach(function(input) {
        input.addEventListener('blur', function() {
            if (this.value && !isNaN(this.value)) {
                var num = parseFloat(this.value);
                if (this.step && this.step.includes('.')) {
                    var decimals = this.step.split('.')[1].length;
                    this.value = num.toFixed(decimals);
                }
            }
        });
    });
});

// Utility functions
function showToast(message, type = 'info') {
    var toastContainer = document.querySelector('.toast-container') || createToastContainer();
    
    var toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type} border-0`;
    toast.setAttribute('role', 'alert');
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">${message}</div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    `;
    
    toastContainer.appendChild(toast);
    
    var bsToast = new bootstrap.Toast(toast);
    bsToast.show();
    
    // Remove toast element after it's hidden
    toast.addEventListener('hidden.bs.toast', function() {
        toast.remove();
    });
}

function createToastContainer() {
    var container = document.createElement('div');
    container.className = 'toast-container position-fixed top-0 end-0 p-3';
    container.style.zIndex = '9999';
    document.body.appendChild(container);
    return container;
}

function initializeNewFields(container) {
    // Re-initialize any JavaScript functionality for newly added fields
    var newInputs = container.querySelectorAll('input, select, textarea');
    newInputs.forEach(function(input) {
        // Add any specific initialization logic here
        if (input.type === 'number') {
            input.addEventListener('blur', function() {
                if (this.value && !isNaN(this.value)) {
                    var num = parseFloat(this.value);
                    if (this.step && this.step.includes('.')) {
                        var decimals = this.step.split('.')[1].length;
                        this.value = num.toFixed(decimals);
                    }
                }
            });
        }
    });
}

// Material calculation functions
function calculateRowTotal(row) {
    var quantity = parseFloat(row.querySelector('.quantity-input').value) || 0;
    var rate = parseFloat(row.querySelector('.rate-input').value) || 0;
    var total = quantity * rate;
    row.querySelector('.total-display').value = total.toFixed(2);
    calculateSubtotal();
}

function calculateSubtotal() {
    var subtotal = 0;
    document.querySelectorAll('.total-display').forEach(function(input) {
        subtotal += parseFloat(input.value) || 0;
    });
    
    var subtotalElement = document.getElementById('subtotal');
    if (subtotalElement) {
        subtotalElement.textContent = subtotal.toFixed(2);
    }
}

// Export functions
function exportToCSV(tableId, filename) {
    var table = document.getElementById(tableId);
    if (!table) return;
    
    var csv = [];
    var rows = table.querySelectorAll('tr');
    
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll('td, th');
        
        for (var j = 0; j < cols.length; j++) {
            var text = cols[j].innerText.replace(/"/g, '""');
            row.push('"' + text + '"');
        }
        
        csv.push(row.join(','));
    }
    
    var csvContent = csv.join('\n');
    var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    var link = document.createElement('a');
    
    if (link.download !== undefined) {
        var url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', filename);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}

// AJAX helper functions
function makeRequest(url, method = 'GET', data = null) {
    return fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: data ? JSON.stringify(data) : null
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    });
}

// Form submission with loading state
function submitFormWithLoading(form, callback) {
    var submitButton = form.querySelector('button[type="submit"]');
    var originalText = submitButton.innerHTML;
    
    submitButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processing...';
    submitButton.disabled = true;
    
    var formData = new FormData(form);
    
    fetch(form.action, {
        method: form.method,
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (callback) callback(data);
    })
    .catch(error => {
        showToast('An error occurred. Please try again.', 'danger');
        console.error('Error:', error);
    })
    .finally(() => {
        submitButton.innerHTML = originalText;
        submitButton.disabled = false;
    });
}
