/**
 * Admin Page Scripts - Signed Agreements List
 * Handles filtering, CSV export, and agreement details modal
 */
jQuery(document).ready(function($) {
    'use strict';
    
    // Check if we're on the admin page with export data
    if (typeof swpdfAdminPage === 'undefined') {
        return;
    }
    
    // ========================================
    // Filter & Export Buttons
    // ========================================
    
    // Filter button
    $('#btn_filter').on('click', function() {
        var url = new URL(window.location.href);
        url.searchParams.set('date_from', $('#filter_date_from').val());
        url.searchParams.set('date_to', $('#filter_date_to').val());
        url.searchParams.set('agreement_type', $('#filter_agreement_type').val());
        url.searchParams.delete('paged');
        window.location.href = url.toString();
    });
    
    // Clear filter
    $('#btn_clear_filter').on('click', function() {
        var url = new URL(window.location.href);
        url.searchParams.delete('date_from');
        url.searchParams.delete('date_to');
        url.searchParams.delete('agreement_type');
        url.searchParams.delete('paged');
        window.location.href = url.toString();
    });
    
    // Export CSV
    $('#btn_export_csv').on('click', function() {
        var exportUrl = swpdfAdminPage.ajaxUrl;
        exportUrl += '?action=swpdf_export_csv';
        exportUrl += '&nonce=' + swpdfAdminPage.exportNonce;
        exportUrl += '&date_from=' + encodeURIComponent($('#filter_date_from').val());
        exportUrl += '&date_to=' + encodeURIComponent($('#filter_date_to').val());
        exportUrl += '&agreement_type=' + encodeURIComponent($('#filter_agreement_type').val());
        window.location.href = exportUrl;
    });
    
    // ========================================
    // Agreement Details Modal
    // ========================================
    
    // Helper function to escape HTML
    function escapeHtml(text) {
        if (text === null || text === undefined) return '';
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(String(text)));
        return div.innerHTML;
    }
    
    // View form details (captured fields) - using secure AJAX endpoint
    $('.view-details').on('click', function(e) {
        e.preventDefault();
        
        var agreementId = $(this).data('id');
        var $button = $(this);
        
        // If no agreement ID, fall back to inline data (for backward compatibility)
        if (!agreementId) {
            var details = $(this).data('details');
            showDetailsFromData(details);
            return;
        }
        
        // Show loading state
        $button.addClass('disabled').text('...');
        
        // Fetch via secure AJAX
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'swpdf_get_agreement_details',
                nonce: swpdfAdminPage.adminNonce,
                agreement_id: agreementId
            },
            success: function(response) {
                $button.removeClass('disabled').html('📋');
                
                if (response.success) {
                    showDetailsFromData({
                        fields: response.data.fields,
                        metadata: response.data.metadata
                    }, response.data.field_count, response.data.metadata_count);
                } else {
                    alert('Error: ' + (response.data.message || 'Unknown error'));
                }
            },
            error: function() {
                $button.removeClass('disabled').html('📋');
                alert('Failed to load agreement details');
            }
        });
    });
    
    function showDetailsFromData(details, fieldCount, metaCount) {
        if (typeof details === 'string') {
            try {
                details = JSON.parse(details);
            } catch (e) {
                console.error('Error parsing details:', e);
                details = {};
            }
        }
        
        if (!details || Object.keys(details).length === 0) {
            $('#modal-title').html('📋 Captured Fields');
            $('#agreement-details-body').html('<p class="notice notice-warning" style="margin: 0;">No captured field data available for this agreement.</p>');
            $('#agreement-details-modal').show();
            return;
        }
        
        var html = '';
        
        // Form fields section
        if (details.fields && Object.keys(details.fields).length > 0) {
            var fCount = (fieldCount !== undefined) ? fieldCount : Object.keys(details.fields).length;
            html += '<div class="captured-fields-section">';
            html += '<h3 style="margin-top: 0; color: #1d4ed8; border-bottom: 1px solid #ddd; padding-bottom: 10px;">📝 Form Fields (' + fCount + ')</h3>';
            for (var key in details.fields) {
                if (details.fields.hasOwnProperty(key)) {
                    var value = details.fields[key];
                    var displayKey = key.replace(/_/g, ' ').replace(/\b\w/g, function(l) { return l.toUpperCase(); });
                    // Check if it's likely a signature (base64 data)
                    if (typeof value === 'string' && value.indexOf('data:image') === 0) {
                        html += '<p><strong>' + escapeHtml(displayKey) + ':</strong> <em>[Signature Image]</em></p>';
                    } else {
                        html += '<p><strong>' + escapeHtml(displayKey) + ':</strong> ' + escapeHtml(value || 'N/A') + '</p>';
                    }
                }
            }
            html += '</div>';
        }
        
        // Metadata section  
        if (details.metadata && Object.keys(details.metadata).length > 0) {
            var mCount = (metaCount !== undefined) ? metaCount : Object.keys(details.metadata).length;
            html += '<div class="audit-trail-section">';
            html += '<h3>🔐 Submission Metadata <span class="audit-badge">' + mCount + ' records</span></h3>';
            for (var mkey in details.metadata) {
                if (details.metadata.hasOwnProperty(mkey)) {
                    var mvalue = details.metadata[mkey];
                    var displayMKey = mkey.replace(/_/g, ' ').replace(/\b\w/g, function(l) { return l.toUpperCase(); });
                    html += '<p><strong>' + escapeHtml(displayMKey) + ':</strong> ' + escapeHtml(mvalue || 'N/A') + '</p>';
                }
            }
            html += '</div>';
        }
        
        if (!html) {
            html = '<p class="notice notice-warning" style="margin: 0;">No captured field data available for this agreement.</p>';
        }
        
        $('#modal-title').html('📋 Captured Fields');
        $('#agreement-details-body').html(html);
        $('#agreement-details-modal').show();
    }
    
    // Close modal handlers
    $('.close-modal, .agreement-details-overlay').on('click', function() {
        $('#agreement-details-modal').hide();
    });
    
    // ESC key to close
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape') {
            $('#agreement-details-modal').hide();
        }
    });
    
    // ========================================
    // View Audit Trail
    // ========================================
    
    $('.view-audit').on('click', function(e) {
        e.preventDefault();
        
        var audit = $(this).data('audit');
        if (typeof audit === 'string') {
            try {
                audit = JSON.parse(audit);
            } catch (error) {
                console.error('Error parsing audit:', error);
                return;
            }
        }
        
        var html = '<div class="audit-certificate">';
        html += '<p><strong>Document ID:</strong> #' + escapeHtml(audit.id) + ' <span class="audit-badge">✓ Verified</span></p>';
        html += '<p><strong>Signer:</strong> ' + escapeHtml(audit.customer_name) + '</p>';
        html += '<p><strong>Email:</strong> ' + escapeHtml(audit.customer_email) + '</p>';
        html += '</div>';
        
        html += '<div class="audit-trail-section">';
        html += '<h3>🔒 Audit Trail</h3>';
        html += '<p><strong>Signed At:</strong> ' + escapeHtml(audit.signed_at) + '</p>';
        html += '<p><strong>IP Address:</strong> <code>' + escapeHtml(audit.ip_address) + '</code></p>';
        html += '<p><strong>User Agent:</strong> <small>' + escapeHtml(audit.user_agent) + '</small></p>';
        html += '</div>';
        
        $('#modal-title').html('🔒 Audit Certificate');
        $('#agreement-details-body').html(html);
        $('#agreement-details-modal').show();
    });
    
    // ========================================
    // Delete Agreement
    // ========================================
    
    $('.delete-agreement').on('click', function(e) {
        e.preventDefault();
        
        if (!confirm('Are you sure you want to permanently delete this agreement? This action cannot be undone.')) {
            return;
        }
        
        var $button = $(this);
        var $row = $button.closest('tr');
        var agreementId = $button.data('id');
        
        $button.addClass('disabled').text('...');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'swpdf_delete_agreement',
                nonce: swpdfAdminPage.adminNonce,
                agreement_id: agreementId
            },
            success: function(response) {
                if (response.success) {
                    $row.fadeOut(300, function() {
                        $(this).remove();
                    });
                } else {
                    alert('Error: ' + (response.data.message || 'Failed to delete'));
                    $button.removeClass('disabled').html('🗑️');
                }
            },
            error: function() {
                alert('Failed to delete agreement');
                $button.removeClass('disabled').html('🗑️');
            }
        });
    });
});
