<?php
// Define the path to the collaboration JSON file
$collabJsonFilePath = 'collab.json';

// Function to fetch collaboration data
function fetchCollabData($filePath)
{
    if (!file_exists($filePath)) {
        return null;
    }
    $jsonContent = file_get_contents($filePath);
    $data = json_decode($jsonContent, true);
    
    // Handle migration from single to multiple collaborations
    if (isset($data['bank_collaboration']) && !isset($data['collaborations'])) {
        // Migrate old single collaboration to new structure
        $data['collaborations'] = [
            'collab_' . uniqid() => $data['bank_collaboration']
        ];
        unset($data['bank_collaboration']);
        file_put_contents($filePath, json_encode($data, JSON_PRETTY_PRINT));
    }
    
    // Add default status if not set (for backward compatibility)
    if (isset($data['collaborations'])) {
        $updated = false;
        foreach ($data['collaborations'] as $id => $collab) {
            if (!isset($collab['status'])) {
                $data['collaborations'][$id]['status'] = 'inactive'; // Default to inactive for existing records
                $updated = true;
            }
        }
        if ($updated) {
            file_put_contents($filePath, json_encode($data, JSON_PRETTY_PRINT));
        }
    }
    
    return $data;
}

// Function to get active collaboration
function getActiveCollaboration($data)
{
    if (!isset($data['collaborations'])) {
        return null;
    }
    
    foreach ($data['collaborations'] as $id => $collab) {
        if (isset($collab['status']) && $collab['status'] === 'active') {
            return ['id' => $id, 'data' => $collab];
        }
    }
    
    return null;
}

// Fetch collaboration data for initial rendering
$collabData = fetchCollabData($collabJsonFilePath);
$activeCollab = getActiveCollaboration($collabData);
?>


<!DOCTYPE html>
<html lang="en" data-layout="topnav" data-menu-color="light" data-bs-theme="light" data-layout-mode="fluid"
    data-topbar-color="dark" data-layout-position="fixed" data-sidenav-size="condensed">

<head>
    <title>MEXC LIVE PANEL</title>
    <?php include 'layouts/title-meta.php'; ?>

    <!-- Plugin css -->
    <link href="assets/vendor/admin-resources/jquery.vectormap/jquery-jvectormap-1.2.2.css" rel="stylesheet"
        type="text/css" />

    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <!-- Begin page -->
    <div class="wrapper">

        <?php include 'layouts/topbar.php'; ?>


        <div class="content-page">
            <div class="content">

                <!-- Start Content-->
                <div class="container-fluid">

                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box">
                                <svg version="1.0" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="74px" height="74px" viewBox="0 0 64 64" enable-background="new 0 0 64 64" xml:space="preserve" fill="#000000" style="margin-top: 30px;height: 60px;"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <g> <rect x="18" y="25" fill="#506C7F" width="4" height="29"></rect> <rect x="30" y="25" fill="#506C7F" width="4" height="29"></rect> <rect x="42" y="25" fill="#506C7F" width="4" height="29"></rect> </g> <g> <rect x="48" y="25" fill="#B4CCB9" width="4" height="29"></rect> <rect x="24" y="25" fill="#B4CCB9" width="4" height="29"></rect> <rect x="36" y="25" fill="#B4CCB9" width="4" height="29"></rect> <rect x="12" y="25" fill="#B4CCB9" width="4" height="29"></rect> </g> <g> <path fill="#F9EBB2" d="M8,56c-1.104,0-2,0.896-2,2h52c0-1.104-0.895-2-2-2H8z"></path> <path fill="#F9EBB2" d="M60,60H4c-1.104,0-2,0.896-2,2h60C62,60.896,61.105,60,60,60z"></path> </g> <path fill="#F9EBB2" d="M4,23h56c0.893,0,1.684-0.601,1.926-1.461c0.24-0.86-0.125-1.785-0.889-2.248l-28-17 C32.725,2.1,32.365,2,32,2c-0.367,0-0.725,0.1-1.037,0.29L2.961,19.291c-0.764,0.463-1.129,1.388-0.888,2.247 C2.315,22.399,3.107,23,4,23z"></path> <g> <path fill="#394240" d="M60,58c0-2.209-1.791-4-4-4h-2V25h6c1.795,0,3.369-1.194,3.852-2.922c0.484-1.728-0.242-3.566-1.775-4.497 l-28-17C33.439,0.193,32.719,0,32,0s-1.438,0.193-2.076,0.581l-28,17c-1.533,0.931-2.26,2.77-1.775,4.497 C0.632,23.806,2.207,25,4,25h6v29H8c-2.209,0-4,1.791-4,4c-2.209,0-4,1.791-4,4v2h64v-2C64,59.791,62.209,58,60,58z M4,23 c-0.893,0-1.685-0.601-1.926-1.462c-0.241-0.859,0.124-1.784,0.888-2.247l28-17.001C31.275,2.1,31.635,2,32,2 c0.367,0,0.725,0.1,1.039,0.291l28,17c0.764,0.463,1.129,1.388,0.887,2.248C61.686,22.399,60.893,23,60,23H4z M52,25v29h-4V25H52z M46,25v29h-4V25H46z M40,25v29h-4V25H40z M34,25v29h-4V25H34z M28,25v29h-4V25H28z M22,25v29h-4V25H22z M16,25v29h-4V25H16z M8,56h48c1.105,0,2,0.896,2,2H6C6,56.896,6.896,56,8,56z M2,62c0-1.104,0.896-2,2-2h56c1.105,0,2,0.896,2,2H2z"></path> <path fill="#394240" d="M32,9c-2.762,0-5,2.238-5,5s2.238,5,5,5s5-2.238,5-5S34.762,9,32,9z M32,17c-1.656,0-3-1.343-3-3 s1.344-3,3-3c1.658,0,3,1.343,3,3S33.658,17,32,17z"></path> </g> <circle fill="#F76D57" cx="32" cy="14" r="3"></circle> </g> </g></svg>
                                <h4 class="page-title">BANK COLLABORATION MANAGEMENT</h4>

                                <button type="button" onclick="location.href='index.php'" class="btn btn-light" style="background: black;margin-bottom: 20px;color: white;"><i class="ri-arrow-left-line me-1"></i>
                                        Back to Home</button>
                            </div>
                        </div>
                    </div>


                    <div class="row">

                        <div class="col-xl-12">
                            <div class="card">
                                <div class="d-flex card-header justify-content-between align-items-center">
                                    <div>
                                        <h4 class="header-title">Bank Collaboration Records</h4>
                                        <p class="text-muted fs-14 mt-1">
                                            Manage and view all bank collaboration information including bank details, images, and descriptions.
                                        </p>
                                    </div>
                                    <div>
                                        <button type="button" class="btn btn-success" data-bs-toggle="modal"
                                            data-bs-target="#collab-modal"><i class="ri-edit-circle-fill"></i> Add Collaboration</button>
                                    </div>
                                </div>
                                <div class="card-body" style="padding-top: 0px;">
                                    
                                    <?php if ($activeCollab): ?>
                                        <!-- Active Collaboration Status Section -->
                                        <div class="alert alert-success mb-4">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <div>
                                                    <h5 class="alert-heading mb-1">
                                                        <i class="ri-bank-line me-2"></i>
                                                        Active Partnership: 
                                                        <span class="badge bg-success">
                                                            <?= htmlspecialchars($activeCollab['data']['bank_name']) ?>
                                                        </span>
                                                    </h5>
                                                    <p class="mb-0">
                                                        This partnership is currently active and visible to users.
                                                    </p>
                                                </div>
                                                <div>
                                                    <button type="button" class="btn btn-warning btn-sm" onclick="updateCollaborationStatus('<?= $activeCollab['id'] ?>', 'inactive')">
                                                        <i class="ri-pause-circle-line"></i> Deactivate
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                        <!-- No Active Collaboration -->
                                        <div class="alert alert-warning mb-4">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <div>
                                                    <h5 class="alert-heading mb-1">
                                                        <i class="ri-bank-line me-2"></i>
                                                        No Active Partnership
                                                    </h5>
                                                    <p class="mb-0">
                                                        No collaboration is currently active. Choose one from below to activate.
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>

                                    <div class="table-responsive-sm">
                                        <?php if ($collabData && isset($collabData['collaborations']) && !empty($collabData['collaborations'])): ?>
                                            <div class="row">
                                                <?php foreach ($collabData['collaborations'] as $collabId => $collaboration): ?>
                                                    <div class="col-12 mb-3">
                                                        <div class="card border <?= ($collaboration['status'] === 'active') ? 'border-success' : 'border-secondary' ?>">
                                                            <div class="card-body">
                                                                <!-- Status Badge -->
                                                                <div class="position-absolute" style="top: 15px; right: 15px;">
                                                                    <span class="badge <?= ($collaboration['status'] === 'active') ? 'bg-success' : 'bg-secondary' ?> px-3 py-2">
                                                                        <i class="<?= ($collaboration['status'] === 'active') ? 'ri-check-line' : 'ri-pause-line' ?> me-1"></i>
                                                                        <?= ucfirst($collaboration['status']) ?>
                                                                    </span>
                                                                </div>
                                                                
                                                                <div class="row align-items-center">
                                                                    <div class="col-lg-2 col-md-3 text-center">
                                                                        <?php if (!empty($collaboration['bank_image'])): ?>
                                                                            <img src="<?= htmlspecialchars($collaboration['bank_image']) ?>" 
                                                                                 alt="Bank Logo" 
                                                                                 class="img-fluid rounded <?= ($collaboration['status'] === 'inactive') ? 'opacity-50' : '' ?>" 
                                                                                 style="max-width: 80px; max-height: 80px; object-fit: cover;">
                                                                        <?php else: ?>
                                                                            <div class="bg-light rounded d-flex align-items-center justify-content-center <?= ($collaboration['status'] === 'inactive') ? 'opacity-50' : '' ?>" 
                                                                                 style="width: 80px; height: 80px;">
                                                                                <i class="ri-image-line fs-24 text-muted"></i>
                                                                            </div>
                                                                        <?php endif; ?>
                                                                    </div>
                                                                    <div class="col-lg-10 col-md-9">
                                                                        <div class="row">
                                                                            <div class="col-lg-4">
                                                                                <h5 class="mb-1 <?= ($collaboration['status'] === 'inactive') ? 'text-muted' : '' ?>">
                                                                                    <?= htmlspecialchars($collaboration['bank_name']) ?>
                                                                                </h5>
                                                                                <p class="text-muted mb-0">
                                                                                    <small><i class="ri-time-line"></i> Updated: <?= date('M d, Y H:i', strtotime($collaboration['updated_at'])) ?></small>
                                                                                </p>
                                                                            </div>
                                                                            <div class="col-lg-8">
                                                                                <div class="description-content">
                                                                                    <strong class="d-block mb-2 <?= ($collaboration['status'] === 'inactive') ? 'text-muted' : '' ?>">Description:</strong>
                                                                                    <p class="mb-0 <?= ($collaboration['status'] === 'inactive') ? 'text-muted' : '' ?>" style="max-height: 100px; overflow-y: auto;">
                                                                                        <?= nl2br(htmlspecialchars($collaboration['bank_content'])) ?>
                                                                                    </p>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="row mt-3">
                                                                            <div class="col-12">
                                                                                <div class="d-flex gap-2">
                                                                                    <?php if (!empty($collaboration['bank_image'])): ?>
                                                                                        <button type="button" class="btn btn-sm btn-outline-info" 
                                                                                                onclick="window.open('<?= htmlspecialchars($collaboration['bank_image']) ?>', '_blank')">
                                                                                            <i class="ri-eye-line"></i> View Image
                                                                                        </button>
                                                                                    <?php endif; ?>
                                                                                    <button type="button" class="btn btn-sm btn-outline-primary" 
                                                                                            onclick="editCollaboration('<?= $collabId ?>', '<?= htmlspecialchars($collaboration['bank_name']) ?>', `<?= htmlspecialchars($collaboration['bank_content']) ?>`, '<?= htmlspecialchars($collaboration['bank_image']) ?>')">
                                                                                        <i class="ri-edit-line"></i> Edit
                                                                                    </button>
                                                                                    <?php if ($collaboration['status'] === 'active'): ?>
                                                                                        <button type="button" class="btn btn-sm btn-outline-warning" 
                                                                                                onclick="updateCollaborationStatus('<?= $collabId ?>', 'inactive')">
                                                                                            <i class="ri-pause-circle-line"></i> Deactivate
                                                                                        </button>
                                                                                    <?php else: ?>
                                                                                        <button type="button" class="btn btn-sm btn-outline-success" 
                                                                                                onclick="updateCollaborationStatus('<?= $collabId ?>', 'active')">
                                                                                            <i class="ri-play-circle-line"></i> Activate
                                                                                        </button>
                                                                                    <?php endif; ?>
                                                                                    <button type="button" class="btn btn-sm btn-outline-danger" 
                                                                                            onclick="deleteCollaboration('<?= $collabId ?>')">
                                                                                        <i class="ri-delete-bin-line"></i> Delete
                                                                                    </button>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php else: ?>
                                            <div class="text-center py-5">
                                                <div class="mb-3">
                                                    <i class="ri-bank-line fs-48 text-muted"></i>
                                                </div>
                                                <h5 class="text-muted">No Bank Collaboration Found</h5>
                                                <p class="text-muted mb-3">Start by adding a new bank collaboration record.</p>
                                                <button type="button" class="btn btn-primary" data-bs-toggle="modal"
                                                        data-bs-target="#collab-modal">
                                                    <i class="ri-add-line"></i> Add First Collaboration
                                                </button>
                                            </div>
                                        <?php endif; ?>
                                    </div> <!-- end table-responsive-->

                                </div> <!-- end card body-->
                            </div>

                            <div class="modal fade" id="collab-modal" tabindex="-1">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form class="needs-validation" name="collab-form" id="form-collab" method="post"
                                            novalidate>
                                            <!-- Hidden fields for edit mode -->
                                            <input type="hidden" name="collaboration_id" id="collaboration_id" value="">
                                            <input type="hidden" name="edit_mode" id="edit_mode" value="0">
                                            <div class="modal-header py-3 px-4 border-bottom-0">
                                                <div>
                                                    <h3 class="modal-title" id="modal-title">Add New Bank Collaboration
                                                    </h3>
                                                    <p>Fill in below to create a new bank and MEXC collaboration.</p>
                                                </div>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"
                                                    aria-label="Close"></button>
                                            </div>
                                            <div class="modal-body px-4 pb-4 pt-0">
                                                <div class="row">
                                                    <div class="col-lg-6">
                                                        <div class="mb-3">
                                                            <label class="control-label form-label">Bank Name</label>
                                                            <input class="form-control" type="text" name="bank_name"
                                                                required />
                                                        </div>
                                                    </div>

                                    <div class="col-lg-6">
                                        <div class="mb-3">
                                            <label class="control-label form-label">Bank Image</label>
                                            <div class="d-flex align-items-center gap-2">
                                                <input class="form-control" type="file" name="bank_image" 
                                                    id="bank_image" accept="image/*" onchange="previewBankImage(this)" />
                                                <img id="bank_image_preview" src="" alt="Preview" 
                                                    style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px; border: 1px solid #ddd; display: none;" />
                                            </div>
                                        </div>
                                    </div>                                                    <hr style="margin-bottom: 13px;">
                                                    <strong style="padding-bottom: 5px;font-size: 17px;">Description</strong>

                                                    <div class="col-12">
                                                        <div class="mb-3">
                                                            <label class="control-label form-label">Content</label>
                                                            <textarea class="form-control" name="bank_content" rows="10" id=""></textarea>
                                                        </div>
                                                    </div>


                                                </div>
                                                <div id="form-messages"></div> <!-- For displaying messages -->
                                                <div class="row">
                                                    <div class="col-6">
                                                    </div>
                                                    <div class="col-6 text-end">
                                                        <button type="button" class="btn btn-light me-1"
                                                            data-bs-dismiss="modal">Close</button>
                                                        <button type="submit" class="btn btn-success"
                                                            id="btn-save-bank">Save</button>
                                                    </div>
                                                </div>
                                            </div>
                                        </form>
                                    </div> <!-- end modal-content-->
                                </div> <!-- end modal dialog-->
                            </div>
                        </div>
                    </div>
                    <!-- end row -->

                </div>
                <!-- container -->

            </div>
            <!-- content -->

            <?php include 'layouts/footer.php'; ?>

        </div>

        <!-- ============================================================== -->
        <!-- End Page content -->
        <!-- ============================================================== -->

    </div>
    <!-- END wrapper -->


    <script>
        function previewBankImage(input) {
            const preview = document.getElementById('bank_image_preview');
            
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                }
                
                reader.readAsDataURL(input.files[0]);
            } else {
                preview.style.display = 'none';
                preview.src = '';
            }
        }
        
        // Function to edit collaboration - pre-fill form with existing data
        function editCollaboration(collaborationId, bankName, bankContent, bankImage) {
            // Set form to edit mode
            document.getElementById('edit_mode').value = '1';
            document.getElementById('collaboration_id').value = collaborationId;
            
            // Pre-fill form fields
            document.querySelector('input[name="bank_name"]').value = bankName;
            document.querySelector('textarea[name="bank_content"]').value = bankContent;
            
            // Update modal title
            document.getElementById('modal-title').textContent = 'Edit Bank Collaboration';
            document.querySelector('#collab-modal .modal-header p').textContent = 'Modify the existing bank collaboration details.';
            
            // Show existing image if available
            const preview = document.getElementById('bank_image_preview');
            if (bankImage && bankImage.trim() !== '') {
                preview.src = bankImage;
                preview.style.display = 'block';
            } else {
                preview.style.display = 'none';
                preview.src = '';
            }
            
            // Show the modal
            const modal = new bootstrap.Modal(document.getElementById('collab-modal'));
            modal.show();
        }
        
        // Function to reset form to create mode when modal is closed
        function resetFormToCreateMode() {
            document.getElementById('edit_mode').value = '0';
            document.getElementById('collaboration_id').value = '';
            document.getElementById('modal-title').textContent = 'Add New Bank Collaboration';
            document.querySelector('#collab-modal .modal-header p').textContent = 'Fill in below to create a new bank and MEXC collaboration.';
            
            // Reset form
            document.getElementById('form-collab').reset();
            
            // Hide image preview
            const preview = document.getElementById('bank_image_preview');
            preview.style.display = 'none';
            preview.src = '';
        }
        
        // Function to delete collaboration
        function deleteCollaboration(collaborationId) {
            if (confirm('Are you sure you want to delete this bank collaboration? This action cannot be undone and will also delete the associated image.')) {
                // Send AJAX request to delete the collaboration
                fetch('actions/delete_bank_collaboration.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ collaboration_id: collaborationId })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Show success message briefly and reload page
                        location.reload();
                    } else {
                        alert('Error deleting collaboration: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred while deleting the collaboration.');
                });
            }
        }
        
        // Function to update collaboration status
        function updateCollaborationStatus(collaborationId, newStatus) {
            const statusText = newStatus === 'active' ? 'activate' : 'deactivate';
            
            if (confirm(`Are you sure you want to ${statusText} this collaboration?`)) {
                // Send AJAX request to update status
                fetch('actions/update_collaboration_status.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        collaboration_id: collaborationId,
                        status: newStatus 
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Reload page to show updated status
                        location.reload();
                    } else {
                        alert('Error updating status: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred while updating the collaboration status.');
                });
            }
        }
        
        document.getElementById('form-event').addEventListener('submit', function (e) {
            e.preventDefault();

            const form = this;
            const submitBtn = document.getElementById('btn-save-event');
            submitBtn.disabled = true;

            // Collect form data
            const formData = new FormData(form);

            // Send AJAX request
            fetch('actions/add_user.php', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Show success message
                        const successHtml = `
                            <div class="alert alert-success" role="alert">
                                ${data.message} (ID: ${data.userId})
                            </div>
                        `;

                        // Insert success message at the top of the modal body
                        const modalBody = document.querySelector('.modal-body');
                        modalBody.insertAdjacentHTML('afterbegin', successHtml);

                        // Clear form
                        form.reset();

                        // Get the modal instance and hide it
                        const modal = bootstrap.Modal.getInstance(document.querySelector('#event-modal')); // Replace with your modal ID
                        modal.hide();

                        // Remove the success message (optional)
                        const alert = document.querySelector('.alert-success');
                        if (alert) {
                            alert.remove();
                        }

                        // Refresh the page or update table
                        location.reload(); // Or use your existing updateTableData() function
                    } else {
                        alert('Error: ' + data.message);
                        submitBtn.disabled = false;
                    }
                })
                .catch(error => {
                    alert('Error: ' + error);
                    submitBtn.disabled = false;
                });
        });
    </script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // Add click event to all delete buttons
            document.querySelectorAll('#deleteUser').forEach(button => {
                button.addEventListener('click', function () {
                    // Get the user_id from the hidden column in the same row
                    const userId = this.closest('tr').querySelector('td[style="display:none;"]').textContent;

                    // Confirm deletion
                    if (confirm('Are you sure you want to delete this user?')) {
                        // Send AJAX request to delete the user
                        fetch('actions/delete_user.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ user_id: userId })
                        })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    this.closest('tr').remove();
                                } else {
                                    alert('Error deleting user: ' + data.message);
                                }
                            })
                            .catch(error => {
                                alert('Error: ' + error);
                            });
                    }
                });
            });
        });
    </script>
    
    <script>
        // Handle Bank Collaboration Form Submission
        document.addEventListener('DOMContentLoaded', function() {
            const collabForm = document.querySelector('#collab-modal form');
            const saveBankBtn = document.getElementById('btn-save-bank');
            const collabModal = document.getElementById('collab-modal');
            
            // Reset form to create mode when modal is closed
            collabModal.addEventListener('hidden.bs.modal', function () {
                resetFormToCreateMode();
            });
            
            if (collabForm && saveBankBtn) {
                collabForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    saveBankBtn.disabled = true;
                    saveBankBtn.innerHTML = 'Saving...';
                    
                    // Create FormData object to handle file upload
                    const formData = new FormData(this);
                    
                    // Send AJAX request
                    fetch('actions/save_bank_collaboration.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Show success message
                            const successHtml = `
                                <div class="alert alert-success" role="alert">
                                    ${data.message}
                                </div>
                            `;
                            
                            // Insert success message at the top of the modal body
                            const modalBody = collabForm.querySelector('.modal-body');
                            modalBody.insertAdjacentHTML('afterbegin', successHtml);
                            
                            // Reset form
                            collabForm.reset();
                            
                            // Hide image preview
                            const preview = document.getElementById('bank_image_preview');
                            if (preview) {
                                preview.style.display = 'none';
                                preview.src = '';
                            }
                            
                            // Close modal immediately
                            const modal = bootstrap.Modal.getInstance(document.querySelector('#collab-modal'));
                            if (modal) {
                                modal.hide();
                            }
                            
                            // Refresh page to show updated data
                            location.reload();
                            
                        } else {
                            // Show error message
                            const errorHtml = `
                                <div class="alert alert-danger" role="alert">
                                    ${data.message}
                                </div>
                            `;
                            
                            const modalBody = collabForm.querySelector('.modal-body');
                            modalBody.insertAdjacentHTML('afterbegin', errorHtml);
                            
                            // Remove error message after delay
                            setTimeout(() => {
                                const alert = document.querySelector('.alert-danger');
                                if (alert) {
                                    alert.remove();
                                }
                            }, 5000);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('An error occurred while saving the bank collaboration.');
                    })
                    .finally(() => {
                        saveBankBtn.disabled = false;
                        saveBankBtn.innerHTML = 'Save';
                    });
                });
            }
        });
    </script>
    
    <?php include 'layouts/right-sidebar.php'; ?>

    <?php include 'layouts/footer-scripts.php'; ?>

    <!-- Dashboard App js -->
    <script src="assets/js/pages/demo.dashboard.js"></script>

    <!-- App js -->
    <script src="assets/js/app.min.js"></script>

    <!-- SEE js for ajax page refresh -->
    <script src="assets/js/sse.js"></script>


</body>

</html>