<?= $this->extend('v2/layout/main_layout') ?>

<?= $this->section('css') ?>
<!-- Gijgo Datepicker CSS -->
<link href="https://unpkg.com/gijgo@1.9.14/css/gijgo.min.css" rel="stylesheet" type="text/css" />
<style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
        background: #f5f7fa;
    }

    .container {
        max-width: 1400px;
        margin: 0 auto;
    }

    .header {
        background: white;
        padding: 24px;
        border-radius: 8px;
        margin-bottom: 24px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }

    h1 {
        color: #1a1a1a;
        font-size: 28px;
        margin-bottom: 8px;
    }

    .subtitle {
        color: #666;
        font-size: 14px;
    }

    .filters {
        background: white;
        padding: 24px;
        border-radius: 8px;
        margin-bottom: 24px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }

    .filter-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 16px;
        margin-bottom: 16px;
    }

    .filter-group {
        display: flex;
        flex-direction: column;
    }

    label {
        font-size: 13px;
        font-weight: 500;
        color: #333;
        margin-bottom: 6px;
    }

    input, select {
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 6px;
        font-size: 14px;
        transition: border-color 0.2s;
    }

    input:focus, select:focus {
        outline: none;
        border-color: #4a90e2;
    }

    .button-group {
        display: flex;
        gap: 12px;
    }

    button {
        padding: 10px 20px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s;
    }

    .btn-primary {
        background: #4a90e2;
        color: white;
    }

    .btn-primary:hover {
        background: #357abd;
    }

    .btn-secondary {
        background: #f0f0f0;
        color: #333;
    }

    .btn-secondary:hover {
        background: #e0e0e0;
    }

    .loading {
        text-align: center;
        padding: 40px;
        color: #666;
    }

    .spinner {
        border: 3px solid #f3f3f3;
        border-top: 3px solid #4a90e2;
        border-radius: 50%;
        width: 40px;
        height: 40px;
        animation: spin 1s linear infinite;
        margin: 0 auto 16px;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .envelopes-container {
        background: white;
        border-radius: 8px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        overflow: hidden;
    }

    .envelope-card {
        padding: 20px 24px;
        border-bottom: 1px solid #eee;
        transition: background 0.2s;
    }
    
    .envelope-card-with-buttons {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
    }
    
    .envelope-card-content {
        flex: 1;
    }
    
    .envelope-card-buttons {
        display: flex;
        flex-direction: column;
        gap: 8px;
        margin-left: 16px;
        padding-left: 16px;
        border-left: 1px solid #ddd;
        min-width: 200px;
    }
    
    .envelope-card-buttons .btn-small {
        white-space: nowrap;
    }

    .envelope-card:hover {
        background: #f9fafb;
    }

    .envelope-card:last-child {
        border-bottom: none;
    }

    .envelope-header {
        display: flex;
        justify-content: space-between;
        align-items: start;
        margin-bottom: 12px;
    }

    .envelope-title {
        font-size: 16px;
        font-weight: 600;
        color: #1a1a1a;
        margin-bottom: 4px;
    }

    .envelope-id {
        font-size: 12px;
        color: #999;
        font-family: monospace;
    }

    .status-badge {
        padding: 4px 12px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
    }

    .status-sent {
        background: #e3f2fd;
        color: #1976d2;
    }

    .status-delivered {
        background: #fff3e0;
        color: #f57c00;
    }

    .status-completed {
        background: #e8f5e9;
        color: #388e3c;
    }

    .status-declined {
        background: #ffebee;
        color: #d32f2f;
    }

    .status-voided {
        background: #f5f5f5;
        color: #757575;
    }

    .envelope-meta {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 12px;
        color: #666;
        font-size: 13px;
    }

    .meta-item {
        display: flex;
        align-items: center;
        gap: 6px;
    }

    .meta-label {
        color: #999;
    }

    .envelope-actions {
        margin-top: 12px;
        display: flex;
        gap: 8px;
    }

    .btn-small {
        padding: 6px 12px;
        font-size: 13px;
        border-radius: 4px;
    }

    .btn-link {
        background: transparent;
        color: #4a90e2;
        border: 1px solid #4a90e2;
    }

    .btn-link:hover {
        background: #4a90e2;
        color: white;
    }

    .btn-link .spinner-small {
        display: inline-block;
        width: 12px;
        height: 12px;
        border: 2px solid rgba(255,255,255,0.3);
        border-top-color: white;
        border-radius: 50%;
        animation: spin 0.6s linear infinite;
        margin-right: 6px;
        vertical-align: middle;
    }

    .btn-link:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }

    .pagination {
        padding: 20px 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid #eee;
        flex-wrap: wrap;
        gap: 12px;
    }

    .pagination-info {
        color: #666;
        font-size: 14px;
    }

    .pagination-controls {
        display: flex;
        gap: 8px;
        align-items: center;
        flex-wrap: wrap;
    }

    .pagination-page {
        padding: 6px 12px;
        font-size: 13px;
        border-radius: 4px;
        cursor: pointer;
        border: 1px solid #ddd;
        background: white;
        color: #333;
        transition: all 0.2s;
    }

    .pagination-page:hover:not(.disabled):not(.active) {
        background: #f0f0f0;
        border-color: #4a90e2;
    }

    .pagination-page.active {
        background: #4a90e2;
        color: white;
        border-color: #4a90e2;
        cursor: default;
    }

    .pagination-page.disabled {
        opacity: 0.5;
        cursor: not-allowed;
        background: #f5f5f5;
    }

    .pagination-ellipsis {
        padding: 6px 4px;
        color: #999;
    }

    /* Align registration preview to /customer-register styling */
    .customer-register-panel {
        max-width: 1200px;
        padding-left: 40px;
        padding-right: 40px;
    }
    .customer-reg-info .card-header {
        font-weight: bold;
    }
    .customer-reg-info .card-body {
        font-size: 100%;
    }
    .customer-reg-info .card-body ul {
        padding-left: 0;
        list-style: none;
        margin: 0;
    }
    #registrationFormModal label {
        font-size: 12px;
        font-weight: 600;
    }
    #registrationFormModal .form-control,
    #registrationFormModal .form-select {
        font-size: 14px;
    }
    #registrationFormModal .card {
        border-radius: 6px;
    }

    .btn-view-registration {
        transition: all 0.2s;
    }

    .btn-view-registration:hover {
        color: #357abd !important;
        transform: scale(1.1);
    }

    #registrationFormModal .form-control[readonly],
    #registrationFormModal .form-select[readonly] {
        background-color: white;
        cursor: not-allowed;
        opacity: 0.9;
        border-color: #0cbc87cc;
    }

    #registrationFormModal .form-control,
    #registrationFormModal .form-select {
        border-color: #0cbc87cc;
    }

    #registrationFormModal .form-check-input[disabled] {
        cursor: not-allowed;
    }

    #registrationFormModal .form-check-input {
        padding-top: 3px;
    }

    #registrationFormModal .modal-header {
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
    }

    #registrationFormModal .modal-title {
        text-align: center;
        flex: 1;
    }

    #registrationFormModal .btn-close {
        position: absolute;
        right: 1rem;
    }

    .error {
        background: #ffebee;
        color: #c62828;
        padding: 16px;
        border-radius: 6px;
        margin-bottom: 24px;
    }

    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #999;
    }

    .empty-state-icon {
        font-size: 48px;
        margin-bottom: 16px;
    }

    @media (max-width: 768px) {
        .filter-grid {
            grid-template-columns: 1fr;
        }

        .envelope-header {
            flex-direction: column;
            gap: 12px;
        }

        .envelope-meta {
            grid-template-columns: 1fr;
        }
        
        .envelope-card-with-buttons {
            flex-direction: column !important;
        }
        
        .envelope-card-content {
            width: 100%;
            order: 1;
        }
        
        .envelope-card-buttons {
            margin-left: 0 !important;
            margin-top: 16px !important;
            padding-left: 0 !important;
            padding-top: 16px !important;
            border-left: none !important;
            border-top: 1px solid #ddd !important;
            width: 100% !important;
            min-width: unset !important;
            order: 2;
        }
        
        .envelope-card-buttons .btn-small {
            width: 100%;
            white-space: normal;
        }
    }
</style>
<?= $this->endSection() ?>

<?= $this->section('content') ?>
<section class="p-4">
<div class="container">
    <?php if (isset($unsent_email_count) && $unsent_email_count > 0): ?>
        <div class="alert alert-warning alert-dismissible fade show" role="alert">
            <strong>Notice:</strong> There <?= $unsent_email_count == 1 ? 'is' : 'are' ?> <strong><?= $unsent_email_count ?></strong> customer registration<?= $unsent_email_count == 1 ? '' : 's' ?> where  copies of form details have not been sent to internal teams. 
            <a href="#" id="send-unsent-emails-link" class="alert-link">Click here to complete it</a>.
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

        <div class="header">
            <h1>📧 DocuSign Envelope Manager</h1>
            <p class="subtitle">View and manage your DocuSign envelopes</p>
            
            <div class="filter-grid" style="margin-top: 20px;">
                <div class="filter-group">
                    <label for="status">Status</label>
                    <select id="status">
                        <option value="">All Statuses</option>
                        <option value="sent">Sent</option>
                        <option value="delivered">Delivered</option>
                        <option value="completed">Completed</option>
                        <option value="declined">Declined</option>
                        <option value="voided">Voided</option>
                    </select>
                </div>

                <div class="filter-group">
                    <label for="fromDate">From Date</label>
                    <input type="text" id="fromDate" class="datepicker-input" readonly>
                </div>

                <div class="filter-group">
                    <label for="toDate">To Date</label>
                    <input type="text" id="toDate" class="datepicker-input" readonly>
                </div>

                <div class="filter-group">
                    <label for="searchText">Search</label>
                    <input type="text" id="searchText" placeholder="Search subject...">
                </div>

                <div class="filter-group">
                    <label for="count">Results per page</label>
                    <select id="count">
                        <option value="10">10</option>
                        <option value="25">25</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                    </select>
                </div>
            </div>
        </div>

        <div id="errorContainer"></div>
        <div id="loadingContainer"></div>
        <div id="envelopesContainer"></div>
    </div>

    <!-- Registration Form View Modal -->
    <div class="modal fade" id="registrationFormModal" tabindex="-1" aria-labelledby="registrationFormModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="registrationFormModalLabel">Customer Registration Form</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="registrationFormModalBody">
                    <!-- Form will be populated here -->
                </div>
                <div class="modal-footer" style="justify-content: center;">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

</section>
<?= $this->endSection() ?>

<?= $this->section('javascript') ?>
<!-- Gijgo Datepicker JS -->
<script src="https://unpkg.com/gijgo@1.9.14/js/gijgo.min.js" type="text/javascript"></script>

<script>
    // Global state variables
    var currentPage = 0;
    var totalResults = 0;
    var registrationsCache = {}; // Cache registration data by ID

    // Initialize on page load
    (function() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', init);
        } else {
            init();
        }
    })();

    function init() {
        // Initialize datepickers with dd/mm/yyyy format (selector only, no manual input)
        $('#fromDate').datepicker({
            uiLibrary: 'bootstrap5',
            iconsLibrary: 'fontawesome',
            format: 'dd/mm/yyyy',
            autoclose: true,
            todayHighlight: true
        });
        
        $('#toDate').datepicker({
            uiLibrary: 'bootstrap5',
            iconsLibrary: 'fontawesome',
            format: 'dd/mm/yyyy',
            autoclose: true,
            todayHighlight: true
        });
        
        // Set default from date to 30 days ago
        const today = new Date();
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(today.getDate() - 30);
        const day = String(thirtyDaysAgo.getDate()).padStart(2, '0');
        const month = String(thirtyDaysAgo.getMonth() + 1).padStart(2, '0');
        const year = thirtyDaysAgo.getFullYear();
        $('#fromDate').val(`${day}/${month}/${year}`);
        
        // Trigger search on Enter in text inputs
        document.getElementById('searchText').addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                currentPage = 0;
                loadEnvelopes(0);
            }
        });

        // Trigger search on change for select/date inputs
        document.getElementById('status').addEventListener('change', function() {
            currentPage = 0;
            loadEnvelopes(0);
        });
        document.getElementById('count').addEventListener('change', function() {
            currentPage = 0;
            loadEnvelopes(0);
        });
        document.getElementById('fromDate').addEventListener('change', function() {
            currentPage = 0;
            loadEnvelopes(0);
        });
        document.getElementById('toDate').addEventListener('change', function() {
            currentPage = 0;
            loadEnvelopes(0);
        });
        
        loadEnvelopes();
    }

    function resetFilters() {
        document.getElementById('status').value = '';
        document.getElementById('searchText').value = '';
        document.getElementById('count').value = '10';
        const today = new Date();
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(today.getDate() - 30);
        const day = String(thirtyDaysAgo.getDate()).padStart(2, '0');
        const month = String(thirtyDaysAgo.getMonth() + 1).padStart(2, '0');
        const year = thirtyDaysAgo.getFullYear();
        $('#fromDate').val(`${day}/${month}/${year}`);
        $('#toDate').val('');
        currentPage = 0;
        totalResults = 0;
        loadEnvelopes(0);
    }

    async function loadEnvelopes(startPosition = 0) {
        const loadingContainer = document.getElementById('loadingContainer');
        const envelopesContainer = document.getElementById('envelopesContainer');
        const errorContainer = document.getElementById('errorContainer');

        // Show loading
        loadingContainer.innerHTML = `
            <div class="loading">
                <p>Loading envelopes...</p>
            </div>
        `;
        envelopesContainer.innerHTML = '';
        errorContainer.innerHTML = '';

        // Build query parameters
        const params = new URLSearchParams();
        
        const status = document.getElementById('status').value;
        if (status) params.append('status', status);
        
        const fromDate = document.getElementById('fromDate').value;
        if (fromDate) {
            // Convert dd/mm/yyyy to yyyy-mm-dd for API
            const parts = fromDate.split('/');
            if (parts.length === 3) {
                params.append('from_date', `${parts[2]}-${parts[1]}-${parts[0]}`);
            }
        }
        
        const toDate = document.getElementById('toDate').value;
        if (toDate) {
            // Convert dd/mm/yyyy to yyyy-mm-dd for API
            const parts = toDate.split('/');
            if (parts.length === 3) {
                params.append('to_date', `${parts[2]}-${parts[1]}-${parts[0]}`);
            }
        }
        
        const searchText = document.getElementById('searchText').value;
        if (searchText) params.append('search_text', searchText);
        
        const count = document.getElementById('count').value;
        params.append('count', count);
        params.append('start_position', startPosition);

        try {
            const response = await fetch(`/customer/register-list?${params.toString()}`);
            const data = await response.json();

            loadingContainer.innerHTML = '';

            if (!response.ok) {
                throw new Error(data.messages?.error || 'Failed to load envelopes');
            }

            if (!data.success) {
                throw new Error(data.message || 'Failed to load envelopes');
            }

            currentPage = startPosition;
            totalResults = data.total_count;

            displayEnvelopes(data);

        } catch (error) {
            loadingContainer.innerHTML = '';
            errorContainer.innerHTML = `
                <div class="error">
                    <strong>Error:</strong> ${error.message}
                </div>
            `;
            console.error('Error loading envelopes:', error);
        }
    }

    function displayEnvelopes(data) {
        const container = document.getElementById('envelopesContainer');
        
        if (!data.registrations || data.registrations.length === 0) {
            container.innerHTML = `
                <div class="envelopes-container">
                    <div class="empty-state">
                        <div class="empty-state-icon">📭</div>
                        <h3>No envelopes found</h3>
                        <p>Try adjusting your filters or date range</p>
                    </div>
                </div>
            `;
            return;
        }

        // const envelopesHtml = data.registrations.map(registration => `
        //     <div class="envelope-card">
        //         <div class="envelope-header">
        //             <div>
        //                 <div class="envelope-title">${escapeHtml(registration.envelope_status.email_subject)}</div>
        //                 <div class="envelope-id">ID: ${registration.envelope_status.envelope_id}</div>
        //             </div>
        //             <span class="status-badge status-${registration.envelope_status.status}">${registration.envelope_status.status.toUpperCase()}</span>
        //         </div>
                
        //         <div class="envelope-meta">
        //             <div class="meta-item">
        //                 <span class="meta-label">From:</span>
        //                 ${escapeHtml(registration.envelope_status.sender_name)} (${escapeHtml(registration.envelope_status.sender_email)})
        //             </div>
        //             <div class="meta-item">
        //                 <span class="meta-label">Created:</span>
        //                 ${format_date(registration.envelope_status.created_date_time)}
        //             </div>
        //             ${registration.envelope_status.sent_date_time ? `
        //             <div class="meta-item">
        //                 <span class="meta-label">Sent:</span>
        //                 ${format_date(registration.envelope_status.sent_date_time)}
        //             </div>
        //             ` : ''}
        //             ${registration.envelope_status.completed_date_time ? `
        //             <div class="meta-item">
        //                 <span class="meta-label">Completed:</span>
        //                 ${format_date(registration.envelope_status.completed_date_time)}
        //             </div>
        //             ` : ''}
        //         </div>

        //         <div class="envelope-actions">
        //             <button class="btn-small btn-link" onclick="viewDetails('${registration.envelope_status.envelope_id}')">
        //                 View Details
        //             </button>
        //             <button class="btn-small btn-link" onclick="downloadDocument('${registration.envelope_status.envelope_id}')">
        //                 Download PDF
        //             </button>
        //         </div>
        //     </div>
        // `).join('');

        // Cache registration data for quick access
        data.registrations.forEach(registration => {
            registrationsCache[registration.id] = registration;
        });

        const envelopesHtml = data.registrations.map(registration => {
            let records = `
            <div class="envelope-card envelope-card-with-buttons">
                <div class="envelope-card-content">
                <div class="envelope-header">
                    <div>
                        <span class="envelope-title">${escapeHtml(registration.business_legal_name)}</span>
                        <span style="color: gray">(${registration.contact_email})</span>
                    </div>
                    <div class="envelope-meta-item" style="font-size:12px; display: flex; align-items: center; gap: 8px;">
                        <span class="meta-label">Created:</span>
                        ${format_date(registration.date_created)}
                        ${registration.mms_creator_id && registration.mms_creator_username ? 
                            `<span style="color: #666; margin-left: 8px;">
                                (${(registration.mms_creator_sop == 1 || registration.mms_creator_sop === true) ? 'MMS Account Created by' : "'7' MMS Account Created by"} ${escapeHtml(registration.mms_creator_username)}${registration.mms_creator_email ? ' - ' + escapeHtml(registration.mms_creator_email) : ''})
                            </span>` : ''}
                        <button class="btn-view-registration" onclick="viewRegistrationForm(${registration.id})" 
                                style="background: none; border: none; padding: 4px 8px; cursor: pointer; color: #4a90e2;" 
                                title="View Registration Form">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                                <path d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8zM1.173 8a13.133 13.133 0 0 1 1.66-2.043C4.12 4.668 5.88 3.5 8 3.5c2.12 0 3.879 1.168 5.168 2.457A13.133 13.133 0 0 1 14.828 8c-.058.087-.122.183-.195.288-.335.48-.83 1.12-1.465 1.755C11.879 11.332 10.119 12.5 8 12.5c-2.12 0-3.879-1.168-5.168-2.457A13.134 13.134 0 0 1 1.172 8z"/>
                                <path d="M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5zM4.5 8a3.5 3.5 0 1 1 7 0 3.5 3.5 0 0 1-7 0z"/>
                            </svg>
                        </button>
                    </div>
                </div>`;

                // Email Sent Status
                const emailSentStatus = registration.email_sended == 1 ? 'Completed' : 'Not Sent';
                const emailSentStatusClass = registration.email_sended == 1 ? 'status-completed' : 'status-declined';
                const showResendButton = registration.email_sended != 1;
                
                records += `
                <div class="envelope-meta">
                    <div style="margin-bottom: 10px; display: flex; align-items: center; gap: 3px;">
                        <span>EmailSent Status:</span>
                        <span class="status-badge ${emailSentStatusClass}">${emailSentStatus.toUpperCase()}</span>
                        ${showResendButton ? `
                        <button class="btn-small btn-link" onclick="resendEmail(${registration.id}, this)" id="btn-resend-email-${registration.id}" style="margin-left: 4px;">
                            Resend Email
                        </button>
                        ` : ''}
                    </div>
                </div>`;

                if (!registration.envelope_status) {
                    let none_status = 'Error';
                    records += `
                <div class="envelope-meta">
                    <div class="" style="display: flex; align-items: center; gap: 8px;">
                        <span>DocuSign Status:</span>
                        <span class="status-badge status-declined">${none_status.toUpperCase()}</span>
                        <button class="btn-small btn-link" onclick="resendDocuSignEnvelope(${registration.id}, this)" id="btn-resend-docusign-${registration.id}" style="margin-left: 4px;">
                            Resend DocuSign
                        </button>
                    </div>
                </div>
                </div>
                <div class="envelope-card-buttons">
                    <button class="btn-small btn-link" onclick="create_standard_mms_account(${registration.id}, true)" data-registration-id="${registration.id}" id="btn-create-standard-mms-${registration.id}">
                        Create Standard MMS Account
                    </button>
                    <button class="btn-small btn-link" onclick="create_standard_mms_account(${registration.id}, false)" data-registration-id="${registration.id}" id="btn-create-standard-plus7-mms-${registration.id}">
                        Create Standard + '7' MMS Account
                    </button>
                </div>
            </div>`
                } else {
                    const isNotCompleted = registration.envelope_status.status !== 'completed';
                    records += `
                <div class="envelope-meta">
                    <div class="">
                        <span>DocuSign Status:</span>
                        <span class="status-badge status-${registration.envelope_status.status}">${registration.envelope_status.status.toUpperCase()}</span>
                    </div>
                    <div class="">
                        <span>Signer1:</span>
                        <span class="status-badge status-${registration.envelope_status.recipients[0].status}">${registration.envelope_status.recipients[0].status.toUpperCase()}</span>
                    </div>
                    <div class="" style="display: flex; align-items: center; justify-content: space-between;">
                        <div style="display: flex; align-items: center; gap: 8px;">
                            <span>Signer2:</span>
                            <span class="status-badge status-${registration.envelope_status.recipients[1].status}">${registration.envelope_status.recipients[1].status.toUpperCase()}</span>
                        </div>
                        ${isNotCompleted ? `
                        <button class="btn-small btn-link" onclick="resendDocuSignEnvelope(${registration.id}, this)" id="btn-resend-docusign-signer2-${registration.id}">
                            Resend DocuSign
                        </button>
                        ` : ''}
                    </div>
                </div>
                <div class="envelope-meta">
                    <div class="meta-item" style="font-size:12px">
                        <span class="meta-label">Created:</span>
                        ${format_date(registration.envelope_status.created_date_time)}
                    </div>
                    ${registration.envelope_status.sent_date_time ? `
                    <div class="meta-item" style="font-size:12px">
                        <span class="meta-label">Sent:</span>
                        ${format_date(registration.envelope_status.sent_date_time)}
                    </div>
                    ` : '<div>&nbsp;</div>'}
                    ${registration.envelope_status.completed_date_time ? `
                    <div class="meta-item" style="font-size:12px">
                        <span class="meta-label">Completed:</span>
                        ${format_date(registration.envelope_status.completed_date_time)}
                    </div>
                    ` : '<div>&nbsp;</div>'}
                </div>
                <div class="envelope-actions">
                    <button class="btn-small btn-link" id="btn-view-details-${registration.envelope_status.envelope_id}" onclick="viewDetails('${registration.envelope_status.envelope_id}', this)">
                        View Details
                    </button>
                    <button class="btn-small btn-link" id="btn-download-pdf-${registration.envelope_status.envelope_id}" onclick="downloadDocument('${registration.envelope_status.envelope_id}', this)">
                        Download PDF
                    </button>
                    <button class="btn-small btn-link" id="btn-download-csv-${registration.id}" onclick="downloadCsv('${registration.id}', this)">
                        Download CSV
                    </button>
                </div>
                </div>
                <div class="envelope-card-buttons">
                    <button class="btn-small btn-link" onclick="create_standard_mms_account(${registration.id}, true)" data-registration-id="${registration.id}" id="btn-create-standard-mms-${registration.id}">
                        Create Standard MMS Account
                    </button>
                    <button class="btn-small btn-link" onclick="create_standard_mms_account(${registration.id}, false)" data-registration-id="${registration.id}" id="btn-create-standard-plus7-mms-${registration.id}">
                        Create Standard + '7' MMS Account
                    </button>
                </div>
            </div>
        `};
        return records;}).join('');

        // Build pagination HTML with page numbers
        const itemsPerPage = parseInt(document.getElementById('count').value);
        const totalPages = Math.ceil(data.total_count / itemsPerPage);
        const currentPageNum = Math.floor(currentPage / itemsPerPage) + 1;
        
        let paginationControls = '';
        
        // Previous button
        paginationControls += `<button class="pagination-page ${currentPage === 0 ? 'disabled' : ''}" 
            onclick="${currentPage === 0 ? '' : `loadEnvelopes(${currentPage - itemsPerPage})`}"
            ${currentPage === 0 ? 'disabled' : ''}>
            ← Previous
        </button>`;
        
        // Page numbers
        const maxVisiblePages = 7;
        let startPage = Math.max(1, currentPageNum - Math.floor(maxVisiblePages / 2));
        let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
        
        // Adjust start page if we're near the end
        if (endPage - startPage < maxVisiblePages - 1) {
            startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }
        
        // First page and ellipsis
        if (startPage > 1) {
            paginationControls += `<button class="pagination-page" onclick="loadEnvelopes(0)">1</button>`;
            if (startPage > 2) {
                paginationControls += `<span class="pagination-ellipsis">...</span>`;
            }
        }
        
        // Page number buttons
        for (let i = startPage; i <= endPage; i++) {
            const isActive = i === currentPageNum;
            paginationControls += `<button class="pagination-page ${isActive ? 'active' : ''}" 
                onclick="${isActive ? '' : `loadEnvelopes(${(i - 1) * itemsPerPage})`}"
                ${isActive ? 'disabled' : ''}>
                ${i}
            </button>`;
        }
        
        // Last page and ellipsis
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                paginationControls += `<span class="pagination-ellipsis">...</span>`;
            }
            paginationControls += `<button class="pagination-page" onclick="loadEnvelopes(${(totalPages - 1) * itemsPerPage})">${totalPages}</button>`;
        }
        
        // Next button
        paginationControls += `<button class="pagination-page ${data.end_position >= data.total_count ? 'disabled' : ''}" 
            onclick="${data.end_position >= data.total_count ? '' : `loadEnvelopes(${currentPage + itemsPerPage})`}"
            ${data.end_position >= data.total_count ? 'disabled' : ''}>
            Next →
        </button>`;
        
        const paginationHtml = `
            <div class="pagination">
                <div class="pagination-info">
                    Showing ${data.start_position + 1} - ${Math.min(data.end_position, data.total_count)} of ${data.total_count}
                </div>
                <div class="pagination-controls">
                    ${paginationControls}
                </div>
            </div>
        `;

        container.innerHTML = `
            <div class="envelopes-container">
                ${envelopesHtml}
                ${paginationHtml}
            </div>
        `;
    }

    async function viewDetails(envelopeId, buttonElement) {
        if (!buttonElement) {
            buttonElement = document.getElementById(`btn-view-details-${envelopeId}`);
        }
        
        const originalText = buttonElement.innerHTML;
        buttonElement.disabled = true;
        buttonElement.innerHTML = '<span class="spinner-small"></span> Loading...';
        
        try {
            const response = await fetch(`/docusign-api/envelope-details/${envelopeId}`);

            const data = await response.json();

            if (!response.ok || !data.success) {
                throw new Error(data.message || 'Failed to load details');
            }

            // Display details using alert_message function
            const details = data.envelope;
            let detailsText = `Envelope Details:\n\n`;
            detailsText += `ID: ${details.envelope_id}\n`;
            detailsText += `Status: ${details.status}\n`;
            detailsText += `Subject: ${details.email_subject}\n`;
            detailsText += `Created: ${format_date(details.created_date_time)}\n`;
            
            if (details.recipients) {
                detailsText += `\nRecipients (${details.recipients_count}):\n`;
                details.recipients.forEach((r, i) => {
                    detailsText += `  ${i + 1}. ${r.name} (${r.email}) - ${r.status}\n`;
                });
            }

            alert_message(detailsText, 'Envelope Details');
        } catch (error) {
            alert_message(`Error: ${error.message}`, 'Error');
        } finally {
            buttonElement.disabled = false;
            buttonElement.innerHTML = originalText;
        }
    }

    function downloadDocument(envelopeId, buttonElement) {
        if (!buttonElement) {
            buttonElement = document.getElementById(`btn-download-pdf-${envelopeId}`);
        }
        
        const originalText = buttonElement.innerHTML;
        buttonElement.disabled = true;
        buttonElement.innerHTML = '<span class="spinner-small"></span> Downloading...';
        
        // Open download in new window
        const downloadUrl = `/docusign-api/envelope-document/${envelopeId}/combined`;
        window.open(downloadUrl, '_blank');
        
        // Reset button after a delay (download may take time)
        setTimeout(() => {
            buttonElement.disabled = false;
            buttonElement.innerHTML = originalText;
        }, 2000);
    }

    async function resendDocuSignEnvelope(registrationId, buttonElement) {
        if (!buttonElement) {
            buttonElement = document.getElementById(`btn-resend-docusign-${registrationId}`) || 
                           document.getElementById(`btn-resend-docusign-signer2-${registrationId}`);
        }
        
        // Show confirmation dialog first
        question_message(
            'Are you sure you want to resend the DocuSign envelope? This will create a new envelope.',
            'Confirm Resend DocuSign',
            'resend-docusign-confirm-modal',
            async function() {
                // This callback runs when user clicks OK
                const originalText = buttonElement.innerHTML;
                buttonElement.disabled = true;
                buttonElement.innerHTML = '<span class="spinner-small"></span> Creating...';
                
                try {
                    const response = await fetch(`/docusign-api/resend-envelope/${registrationId}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    const data = await response.json();

                    if (data.result) {
                        console.log(data.result);
                    }
                    
                    if (data.success) {
                        alert_message('DocuSign envelope created successfully', 'Success');
                        // Reload current page to update the statusap
                        window.location.reload();
                    } else {
                        console.log(data.result);
                        alert_message(data.msg || 'Failed to create DocuSign envelope', 'Error');
                        buttonElement.disabled = false;
                        buttonElement.innerHTML = originalText;
                    }
                } catch (error) {
                    console.error('Error:', error);
                    alert_message('An error occurred while creating DocuSign envelope', 'Error');
                    buttonElement.disabled = false;
                    buttonElement.innerHTML = originalText;
                }
            }
        );
    }

    async function create_standard_mms_account(customerId, sop) {
        // Get button element from event context
        const buttonElement = event.target;
        
        if (!customerId) {
            alert_message('Customer ID not found', 'Error');
            return;
        }
        
        const originalText = buttonElement.innerHTML;
        buttonElement.disabled = true;
        buttonElement.innerHTML = '<span class="spinner-small"></span> Creating...';
        
        try {
            // Fetch customer information and config values
            const infoResponse = await fetch(`/docusign-api/customer-info-config/${customerId}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            const infoData = await infoResponse.json();
            
            if (!infoData.success) {
                throw new Error(infoData.msg || 'Failed to fetch customer information');
            }
            
            // Store the fetched data for use
            const customerInfo = infoData.customer_info;
            const accountCreateApiUrl = infoData.account_create_api_url;
            const accountCreateApiKey = infoData.account_create_api_key;
            
            // Validate that we have the required data
            if (!accountCreateApiUrl) {
                throw new Error('Account creation API URL not configured');
            }
            
            if (!accountCreateApiKey) {
                throw new Error('Account creation API key not configured');
            }
            
            // Send POST request to external API server
            const externalResponse = await fetch(accountCreateApiUrl, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${accountCreateApiKey}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    ...customerInfo,
                    sop: sop
                })
            });
            
            const externalData = await externalResponse.json();
            
            if (externalResponse.ok) {
                // Update mms_creator_id and mms_creator_sop in backend
                const updateResponse = await fetch(`/docusign-api/update-mms-creator/${customerId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        sop: sop
                    })
                });
                
                const updateData = await updateResponse.json();
                
                if (!updateData.success) {
                    console.warn('Failed to update MMS creator ID:', updateData.msg);
                }
                
                alert_message('MMS account created successfully', 'Success');
                // Reload current page to update the status
                window.location.reload();
            } else {
                const errorMsg = externalData.message || externalData.error || 'Failed to create MMS account';
                alert_message(errorMsg, 'Error');
                buttonElement.disabled = false;
                buttonElement.innerHTML = originalText;
            }
            
            // const data = await response.json();
            
            // if (data.success) {
            //     alert_message(data.msg || 'MMS account created successfully', 'Success');
            // } else {
            //     alert_message(data.msg || 'Failed to create MMS account', 'Error');
            //     buttonElement.disabled = false;
            //     buttonElement.innerHTML = originalText;
            // }
        } catch (error) {
            console.error('Error:', error);
            alert_message('An error occurred while creating MMS account', 'Error');
            buttonElement.disabled = false;
            buttonElement.innerHTML = originalText;
        }
    }

    async function resendEmail(registrationId, buttonElement) {
        if (!buttonElement) {
            buttonElement = document.getElementById(`btn-resend-email-${registrationId}`);
        }
        
        const originalText = buttonElement.innerHTML;
        buttonElement.disabled = true;
        buttonElement.innerHTML = '<span class="spinner-small"></span> Sending...';
        
        try {
            const response = await fetch(`/customer/resend-email/${registrationId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            const data = await response.json();
            
            if (data.success == 1) {
                alert_message(data.msg || 'Email sent successfully', 'Success');
                // Reload current page to update the status
                window.location.reload();
            } else {
                alert_message(data.msg || 'Failed to send email', 'Error');
                buttonElement.disabled = false;
                buttonElement.innerHTML = originalText;
            }
        } catch (error) {
            console.error('Error:', error);
            alert_message('An error occurred while sending email', 'Error');
            buttonElement.disabled = false;
            buttonElement.innerHTML = originalText;
        }
    }

    function downloadCsv(registrationId, buttonElement) {
        if (!buttonElement) {
            buttonElement = document.getElementById(`btn-download-csv-${registrationId}`);
        }
        
        const originalText = buttonElement.innerHTML;
        buttonElement.disabled = true;
        buttonElement.innerHTML = '<span class="spinner-small"></span> Downloading...';
        
        // Download CSV file using registration ID; envelope data included only if available
        const downloadUrl = `/docusign-api/envelope-csv/${registrationId}`;
        // window.location.href = downloadUrl;
        window.open(downloadUrl, '_blank');

        
        // Reset button after a delay (download may take time)
        setTimeout(() => {
            buttonElement.disabled = false;
            buttonElement.innerHTML = originalText;
            // window.location.reload();
        }, 2000);
    }

    function viewRegistrationForm(registrationId) {
        // Check cache first
        if (registrationsCache[registrationId]) {
            displayRegistrationFormModal(registrationsCache[registrationId]);
            return;
        }

        // If not in cache, fetch it
        fetch(`/customer/register-list`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.registrations) {
                    const registration = data.registrations.find(r => r.id == registrationId);
                    if (registration) {
                        registrationsCache[registrationId] = registration;
                        displayRegistrationFormModal(registration);
                    } else {
                        alert_message('Registration data not found', 'Error');
                    }
                } else {
                    alert_message('Failed to load registration data', 'Error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert_message('An error occurred while loading registration data', 'Error');
            });
    }

    function displayRegistrationFormModal(registration) {
        const modalBody = document.getElementById('registrationFormModalBody');
        const modalTitle = document.getElementById('registrationFormModalLabel');
        
        // Update modal title with customer name
        const customerName = registration.business_legal_name || registration.business_trading_name || 'Customer';
        modalTitle.textContent = customerName + ' Registration Form';
        
        // Format date from YYYY-MM-DD to DD/MM/YYYY
        const formatDateForDisplay = (dateStr) => {
            if (!dateStr) return '';
            const date = new Date(dateStr);
            const day = String(date.getDate()).padStart(2, '0');
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const year = date.getFullYear();
            return `${day}/${month}/${year}`;
        };

        // Format payment method
        const formatPaymentMethod = (method) => {
            const methods = {
                'cash': 'Cash',
                'bank_transfer': 'Bank Transfer',
                'echo_pay': 'EchoPay',
                'card': 'Card',
                'credit_facility': 'Credit Facility'
            };
            return methods[method] || method || '';
        };

        const boolToYesNo = (value) => {
            return (value == 1 || value === true || value === '1') ? 'Yes' : 'No';
        };

        // Build marketing-options block (shown only when offers_and_info is on),
        // mirroring the registration form's "with:" sub-list.
        let marketingHtml = '';
        if (registration.offers_and_info == 1 && registration.marketing_options) {
            const availableMarketingOptions = ['post', 'email', 'sms', 'messaging', 'telephone'];
            const arrayMarketingOptions = (registration.marketing_options || '').split(',').map(s => s.trim().toLowerCase());
            marketingHtml = '<div id="marketing-options-container" class="ps-4 mb-3"><div style="display: flex"><div style="margin-left: 15px;padding-right: 10px">with:</div>';
            availableMarketingOptions.forEach((item, idx) => {
                const checked = arrayMarketingOptions.includes(item.toLowerCase());
                const labels = { post: 'Post', email: 'eMail', sms: 'SMS', messaging: 'Messaging Platforms', telephone: 'Telephone' };
                const label = labels[item] || item;
                marketingHtml += '<div class="form-check form-switch mb-3 d-flex" style="padding-left:20px"><input class="form-check-input" type="checkbox" ' + (checked ? 'checked ' : '') + 'disabled /><label class="form-check-label ps-2">' + label + '</label></div>';
                if (idx === 3) {
                    marketingHtml += '</div><div style="display: flex">';
                }
            });
            marketingHtml += '</div></div>';
        }

        // Layout mirrors customer_register.php: 3 rows of 2 cards each —
        // Business + Owner/Director, Company + Store, Sell + Payment & Offer.
        let html = `
            <div class="customer-register-panel" style="max-width: 100%; padding: 0;">
                <div class="employee-edit">
                    <form class="needs-validation" style="display: flex; flex-direction: column; gap: 10px;">

                        <!-- Row 1: Business + Owner/Director -->
                        <div class="d-flex2 justify-content-between" style="gap: 10px">
                            <div class="customer-reg-info card full-width-on-mobile" style="flex: 1">
                                <div class="card-header p-2"><div class='m-0'>Business</div></div>
                                <div class="card-body p-3">
                                    <div class="mb-3">
                                        <label class="required">Business Legal Name:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.business_legal_name || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">Business Trading Name:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.business_trading_name || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">Business Start Date:</label>
                                        <input type="text" class="form-control" value="${formatDateForDisplay(registration.business_start_date)}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label for="prefered_branch">Preferred Branch:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.prefered_branch || '')}" readonly />
                                    </div>
                                    <div class="form-check form-switch form-check mb-3">
                                        <input class="form-check-input confirm_legal_owner_director" style="position: absolute" type="checkbox" ${registration.confirm_legal_owner_director == 1 ? 'checked' : ''} disabled />
                                        <label class="form-check-label ps-2 break-over-word" style="margin-left: 32px !important;">I confirm I am the Legal Owner or Director</label>
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">Address Line 1:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.address_line1 || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="">Address Line 2:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.address_line2 || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">County:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.county || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">City:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.city || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">Country:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.country || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">Post Code:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.post_code || '')}" readonly />
                                    </div>
                                </div>
                            </div>
                            <div class="customer-reg-info card full-width-on-mobile" style="flex: 1">
                                <div class="card-header p-2"><div class='m-0'>Owner/Director</div></div>
                                <div class="card-body p-3">
                                    <div class="mb-3">
                                        <label class="required">Contact Name:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.contact_name || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="">Contact Telephone Landline:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.contact_telephone_landline || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">Contact Telephone Mobile:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.contact_telephone_mobile || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">Contact email adresss:</label>
                                        <input type="email" class="form-control" value="${escapeHtml(registration.contact_email || '')}" readonly />
                                    </div>
                                    <div class="d-flex mb-3" style="gap: 10px;">
                                        <div style="flex: 0 0 35%;">
                                            <label class="required">House Number:</label>
                                            <input type="text" class="form-control" value="${escapeHtml(registration.contact_addr_house_number || '')}" readonly />
                                        </div>
                                        <div style="flex: 1;">
                                            <label>House Name/Flat:</label>
                                            <input type="text" class="form-control" value="${escapeHtml(registration.contact_addr_house_name_flat || '')}" readonly />
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">Street:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.contact_addr_street || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">Village/Town:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.contact_addr_vill_town || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">City:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.contact_addr_city || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">Country:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.contact_addr_country || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">Post Code:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.contact_addr_postcode || '')}" readonly />
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Row 2: Company + Store -->
                        <div class="d-flex2 justify-content-between" style="gap: 10px">
                            <div class="customer-reg-info card full-width-on-mobile" style="flex: 1">
                                <div class="card-header p-2"><div class='m-0'>Company</div></div>
                                <div class="card-body p-3">
                                    <div class="mb-3">
                                        <label class="required break-over-word">For how many years has the business been trading?</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.business_trading_years || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="">VAT Number:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.vat_number || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="">Company Number:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.company_number || '')}" readonly />
                                    </div>
                                </div>
                            </div>
                            <div class="customer-reg-info card full-width-on-mobile" style="flex: 1">
                                <div class="card-header p-2"><div class='m-0'>Store</div></div>
                                <div class="card-body p-3">
                                    <div class="mb-3">
                                        <label class="required">Store size in square feet?</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.store_size || '')}" readonly />
                                    </div>
                                    <div class="mb-3">
                                        <label class="required">Store average turnover weekly?</label>
                                        <input type="text" class="form-control" value="${escapeHtml(registration.store_average || '')}" readonly />
                                    </div>
                                    <div class="form-check form-switch mb-3 d-flex">
                                        <input class="form-check-input" type="checkbox" ${registration.self_service == 1 ? 'checked' : ''} disabled />
                                        <label class="form-check-label ps-2">I will visit the depot to purchase goods</label>
                                    </div>
                                    <div class="form-check form-switch mb-3 d-flex">
                                        <input class="form-check-input" type="checkbox" ${registration.click_and_collect == 1 ? 'checked' : ''} disabled />
                                        <label class="form-check-label ps-2">I will order online then come in to collect goods</label>
                                    </div>
                                    <div class="form-check form-switch mb-3 d-flex">
                                        <input class="form-check-input" type="checkbox" ${registration.delivered == 1 ? 'checked' : ''} disabled />
                                        <label class="form-check-label ps-2">I will order online and require a delivery of goods</label>
                                    </div>
                                    <div class="form-check form-switch mb-3 d-flex">
                                        <input class="form-check-input" type="checkbox" ${registration.offers_and_info == 1 ? 'checked' : ''} disabled />
                                        <label class="form-check-label ps-2">Do you wish to receive marketing offers and info?</label>
                                    </div>
                                    ${marketingHtml}
                                </div>
                            </div>
                        </div>

                        <!-- Row 3: Sell + Payment & Offer -->
                        <div class="d-flex2 justify-content-between" style="gap: 10px">
                            <div class="customer-reg-info card full-width-on-mobile" style="flex: 1">
                                <div class="card-header p-2"><div class='m-0'>Sell</div></div>
                                <div class="card-body p-3">
                                    <ul style="list-style: none; padding-left: 0;">
                                        <li class="form-check form-switch form-check mb-3">
                                            <input class="form-check-input" type="checkbox" ${registration.sell_alcohol == 1 ? 'checked' : ''} disabled />
                                            <label class="form-check-label ps-2">Do you sell Alcohol?</label>
                                        </li>
                                        <li class="mb-3" ${registration.premises_licence ? '' : 'style="display: none;"'}>
                                            <label class="form-label">Premises Licence:</label>
                                            <input type="text" class="form-control" value="${escapeHtml(registration.premises_licence || '')}" readonly />
                                        </li>
                                        <li class="form-check form-switch form-check mb-3">
                                            <input class="form-check-input" type="checkbox" ${registration.sell_tobacco == 1 ? 'checked' : ''} disabled />
                                            <label class="form-check-label ps-2">Do you sell Tobacco?</label>
                                        </li>
                                        <li class="mb-3" ${registration.eoid ? '' : 'style="display: none;"'}>
                                            <label class="form-label">Your EOID:</label>
                                            <input type="text" class="form-control" value="${escapeHtml(registration.eoid || '')}" readonly />
                                        </li>
                                        <li class="mb-3" ${registration.fid ? '' : 'style="display: none;"'}>
                                            <label class="form-label">Your FID:</label>
                                            <input type="text" class="form-control" value="${escapeHtml(registration.fid || '')}" readonly />
                                        </li>
                                        <li class="form-check form-switch form-check mb-3">
                                            <input class="form-check-input" type="checkbox" ${registration.sell_vapes == 1 ? 'checked' : ''} disabled />
                                            <label class="form-check-label ps-2">Do you sell Vapes?</label>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <div class="customer-reg-info card full-width-on-mobile" style="flex: 1">
                                <div class="card-header p-2"><div class='m-0'>Payment & Offer</div></div>
                                <div class="card-body p-3">
                                    <div class="mb-3">
                                        <label class="break-over-word">What is your prefered payment method?</label>
                                        <input type="text" class="form-control" value="${formatPaymentMethod(registration.prefered_payment_method)}" readonly />
                                    </div>
                                    <div class="form-check form-switch mb-3 d-flex">
                                        <input class="form-check-input" type="checkbox" ${registration.credit_account_facility == 1 ? 'checked' : ''} disabled />
                                        <label class="form-check-label ps-2">Do you require a credit account facility?</label>
                                    </div>
                                    ${registration.credit_account_facility == 1 ? `
                                    <div class="mb-3">
                                        <label class="required">Required Credit Limit £'s:</label>
                                        <input type="text" class="form-control" value="${escapeHtml(String(registration.requested_credit_limit ?? ''))}" readonly />
                                    </div>
                                    ` : ''}
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        `;

        modalBody.innerHTML = html;
        
        // Show the modal
        const modal = new bootstrap.Modal(document.getElementById('registrationFormModal'));
        modal.show();
    }

    function format_date(dateString) {
        if (!dateString) return 'N/A';
        const date = new Date(dateString);
        // Format as dd/mm/yy
        const day = String(date.getDate()).padStart(2, '0');
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const year = String(date.getFullYear()).slice(-2);
        return `${day}/${month}/${year}`;
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Handle click on "send unsent emails" link
    $(document).on('click', '#send-unsent-emails-link', function(e) {
        e.preventDefault();

        // Show loading state
        const $link = $(this);
        const originalText = $link.text();
        $link.text('Processing...').prop('disabled', true);

        $.ajax({
            type: "POST",
            async: true,
            url: "/customer/send-unsent-emails",
            dataType: "json",
            timeout: 60000,
            cache: false,
            error: function (xhr, status, error) {
                if (xhr.status == 401) {
                    window.location.href = '/login';
                    return;
                } else {
                    console.log("An error occurred: " + xhr.status + " " + xhr.statusText);
                    alert_message('An error occurred while sending emails. Please try again.', 'Error', 'customer-register-form-modal');
                }
                $link.text(originalText).prop('disabled', false);
            },
            success: function (response, status, request) {
                if (response.success == 1) {
                    alert_message(response.msg || 'Emails have been sent successfully.', 'Success', 'customer-register-form-modal', function(e){
                        location.reload();
                    });
                } else {
                    alert_message(response.msg || 'An error occurred while sending emails.', 'Error', 'customer-register-form-modal');
                    $link.text(originalText).prop('disabled', false);
                }
            },
            complete: function() {
                // Reset link state if not already handled
                if ($link.text() === 'Processing...') {
                    $link.text(originalText).prop('disabled', false);
                }
            }
        });
    });
</script>
<?= $this->endSection() ?>