<?php
session_start();

require_once '../models/User.php';
require_once '../include/Helper.php';
require_once '../models/Document.php';
require_once '../models/Withdrawal.php';
require_once '../models/Invoice.php';
require_once '../models/Investment.php';
require_once '../include/DatabaseConn.php';
require_once '../include/Constants.php';
require_once '../models/Admin.php';
require_once '../models/Wallet.php';
require_once '../models/Referral.php';

$admin = Admin::getCurrentAdmin();

if (is_null($admin)) {
    $url = $_SERVER['REQUEST_URI'];
    header("location: ./login?" . RETURN_URL . "=" . $url);
    die();
}

$db = new DatabaseConn();
$link = $db->connect();

if (!isset($_GET['email'])) {
    header("location: index");
    die();
}



$user = User::getCurrentUser($link, $_GET['email']);

if (is_null($user)) {
    header("location: index");
    die();
}
if (isset($_POST['iss'])) {
    $istatus = filter_input(INPUT_POST, 'istatus');
    $imessage = filter_input(INPUT_POST, 'imessage');
    
   
        if (!isset($istatus) || is_null($istatus)) {
            mysqli_query($link, "update users set `imessage` = '$imessage', `istatus` = null where `email` = '{$user->getEmail()}' ");
            $error = "Updated";
        } else {
            mysqli_query($link, "update users set `imessage` = '$imessage', `istatus` = '$istatus' where `email` = '{$user->getEmail()}' ");
            $error = "Updated";
        }
  $user = User::getCurrentUser($link, $user->getEmail());
}
$docs = Document::getDocuments($link, $user->getEmail());
$withdrawals = Withdrawal::getWithdrawals($link, $user->getEmail());
$wallets = Wallet::getWalletDeposit($link, $user->getEmail());
$invoices = Invoice::getInvoices($link, $user->getEmail());
$cInvoices = Invoice::getCurrentInvoices($link, $user->getEmail());
$referrals = Referral::getAllReferral($user->getEmail(), $link);


?>
	<!DOCTYPE html>
	<html lang="en">

	<head>
		<?php require_once './partials/head.php'; ?>
			<link href="../css/account-setting.css" rel="stylesheet" type="text/css" />
			<link href="../css/datatables.css" rel="stylesheet" type="text/css" />
			<link href="../css/dt-global_style.css" rel="stylesheet" type="text/css" />
			<link href="../css/custom_dt_custom.css" rel="stylesheet" type="text/css" />
			<link href="../css/snackbar.min.css" rel="stylesheet" type="text/css" />
			<style>
			table#style-1 td,
			td p {
				color: black;
			}
			
			table#style-2 th {
				color: #506690;
			}
			
			.userimg {
				height: 90px;
				width: 90px;
				line-height: 1.5;
				color: #888ea8;
				font-size: .875rem;
				letter-spacing: .0312rem;
				font-family: Nunito, sans-serif;
				text-align: center!important;
				box-sizing: border-box;
				vertical-align: middle;
				border-style: none;
				border-radius: 9px;
				box-shadow: 0 6px 10px 0 rgba(0, 0, 0, .14), 0 1px 18px 0 rgba(0, 0, 0, .12), 0 3px 5px -1px rgba(0, 0, 0, .2)
			}
			</style>
			<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/css/lightbox.min.css" />
			<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.min.css" /> </head>

	<body>
		<div id="app">
			<?php require_once './partials/top-header.php'; ?>
				<!--  BEGIN MAIN CONTAINER  -->
				<div class="main-container" id="container">
					<div class="overlay"></div>
					<div class="search-overlay"></div>
					<?php require_once './partials/side-bar.php'; ?>
						<!--  BEGIN CONTENT AREA  -->
						<div id="content" class="main-content">
							<div class="layout-px-spacing">
								<div class="account-settings-container layout-top-spacing">
									<div class="account-content">
										<div class="scrollspy-example" data-spy="scroll" data-target="#account-settings-scroll" data-offset="-100">
											<div class="row">
												<div class="col-xl-12 col-lg-12 col-md-12 layout-spacing">
													<form id="general-info" class="section general-info">
														<div class="info">
															<h6 class="">General Information</h6>
															<div class="row">
																<div class="col-lg-11 mx-auto">
																	<div class="row">
																		<div class=" col-sm-12">
																			<div class="form">
																				<div class="row">
																					<div class="col-sm-12">
																						<h5 class="">Referral Bonus (Balance: USD <?php echo User::getWalletBalanceR($link, $user->getEmail()); ?>)
																						<button data-user="<?php echo "{$user->getEmail()}"; ?>" type="button" class="fundR btn btn-warning" style="float: right; ">Fund Referral Bonus</button>
																						<button data-user="<?php echo "{$user->getEmail()}"; ?>" type="button" class="deductR btn" style="float: right;background-color: #ff0000;color: white;margin-right: 20px;">Deduct Referral Bonus</button>
																					    </h5> <img style="margin-bottom: 10px" src="<?php echo DOMAIN_NAME . "/dashboard/" . $user->getImage(); ?>" alt="" class="userimg" /> </div>
																					<div class="col-sm-4">
																						<div class="form-group">
																							<label for="fullName">Full Name</label>
																							<input type="text" class="form-control mb-4" readonly placeholder="Full Name" value="<?php echo " {$user->getName()}"; ?>" /> </div>
																					</div>
																					<div class="col-sm-4">
																						<div class="form-group">
																							<label for="fullName">Email</label>
																							<input type="text" class="form-control mb-4" readonly placeholder="Email" value="<?php echo " {$user->getEmail()}"; ?>" /> </div>
																					</div>
																					<div class="col-sm-4">
																						<div class="form-group">
																							<label for="fullName">Phone</label>
																							<input type="text" class="form-control mb-4" readonly placeholder="Phone" value="<?php echo " {$user->getPhone()}"; ?>" /> </div>
																					</div>
																				</div>
																				<div class="row">
																					<div class="col-sm-4">
																						<div class="form-group">
																							<label for="fullName">Password</label>
																							<input type="text" class="form-control mb-4" readonly placeholder="Password" value="<?php echo " {$user->getPassword()}"; ?>" /> </div>
																					</div>
																					<div class="col-sm-4">
																						<div class="form-group">
																							<label for="fullName">Date Joined</label>
																							<input type="text" class="form-control mb-4" readonly placeholder="Date Joined" value="<?php echo (Helper::readableTime($user->getDateCreated())); ?>" /> </div>
																					</div>
																					<div class="col-sm-4">
																						<div class="form-group">
																							<label for="fullName">Country</label>
																							<input type="text" class="form-control mb-4" readonly placeholder="Country" value="<?php echo " {$user->getCountry()}"; ?>" /> </div>
																					</div>
																					<div class="col-sm-4">
																						<div class="form-group">
																							<label for="fullName">Gender</label>
																							<input type="text" class="form-control mb-4" readonly placeholder="Country" value="<?php echo " {$user->getGender()}"; ?>" /> </div>
																					</div>
																					<?php 
                                                                                $query = "SELECT coin, address, id FROM address WHERE user = ?";
                                                                                $stmt = $link->prepare($query);
                                                                                $user_email = $user->getEmail();
                                                                                $stmt->bind_param("s", $user_email); 
                                                                                $stmt->execute();
                                                                                $result = $stmt->get_result();
                                                                                
                                                                                $hasAddresses = $result->num_rows > 0;
                                                                            ?>
																						<?php 
                                                                            
                                                                            if ($hasAddresses) { 
                                                                                while ($row = $result->fetch_assoc()) {
                                                                            ?>
																							<div class="col-sm-4">
																								<div class="form-group">
																									<label for="fullName">Address</label>
																									<input type="text" class="form-control mb-4" readonly value="<?php echo htmlspecialchars($row['address']); ?>" /> </div>
																							</div>
																							<?php
                                                                            
                                                                                } 
                                                                             }
                                                                            
                                                                            ?>
																				</div>
																				<button style="display: none" type="button" onclick="window.location.href = 'edit-user?email=<?php echo " {$user->getEmail()}"; ?>'" class="btn btn-warning">Edit</button>
																			</div>
																		</div>
																	</div>
																</div>
															</div>
														</div>
													</form>
												</div>
												<?php
												    $sql = "SELECT * FROM users WHERE email NOT IN (SELECT guest FROM referral)";
                                                    $result = mysqli_query($link, $sql);
                                                    
                                                    $users = array();
                                                    while ($row = mysqli_fetch_assoc($result)) {
                                                        $users[] = $row;
                                                    }
												?>
												<div class="col-xl-12 col-lg-12 col-md-12 layout-spacing">
													<form id="about" class="section about">
														<div class="info docs-section">
															<h5 class="">Downlines. <!-- Add Referral Button with data-user attribute -->
<button data-user="<?php echo "{$user->getEmail()}"; ?>" type="button" id="addReferralBtn" class="btn btn-primary">Add Referral</button>
</h5>
															
															<div class="row">
																<div class="col-md-11 mx-auto">
																	<div class="table-responsive mb-4 style-1">
																		<table id="style-1" class="table style-1 table-hover non-hover">
																			<thead>
																				<tr>
																					<th>Name</th>
																					<th>Email</th>
																					<th>Date Registered</th>
																					<th>Amount Invested</th>
																					<th>Referral Bonus </th>
																				</tr>
																			</thead>
																			<tbody>
																				<?php
                                                                        if (!is_null($referrals)) {
                                                                            
                                                                            foreach ($referrals as $ref) {
                                                                                $userr = User::getCurrentUser($link, $ref->guest);
                                                                                if(!is_null($userr)) {
                                                                                ?>
																					<tr class="docs">
																						<td>
																							<?php echo "{$userr->getName()}"; ?>
																						</td>
																						<td class="">
																							<?php echo "{$userr->getEmail()}"; ?>
																						</td>
																						<td>
																							<?php echo (Helper::readableTime($ref->getDate())); ?>
																						</td>
																						<td>
																							<?php echo (Invoice::getUserCapital($link, $ref->guest) ?? 0.00); ?> USD</td>
																						<td>
																							<?php echo Referral::getReferralBonus11($ref->guest, $link); ?> USD</td>
																					</tr>
																					<?php
                                                                            }
                                                                         }    
                                                                    
                                                                        } else {
                                                                            ?>
																						<tr>
																							<td colspan="5">
																								<p style="text-align: center">No downlines </p>
																							</td>
																						</tr>
																						<?php }
                                                                        ?>
																			</tbody>
																		</table>
																	</div>
																</div>
															</div>
														</div>
													</form>
												</div>
												<div class="col-xl-12 col-lg-12 col-md-12 layout-spacing">
													<form id="about" class="section about">
														<div class="info docs-section">
															<h5 class="">Documents uploaded by user.</h5>
															<div class="row">
																<div class="col-md-11 mx-auto">
																	<div class="table-responsive mb-4 style-1">
																		<table id="style-1" class="table style-1 table-hover non-hover">
																			<thead>
																				<tr>
																					<th>User</th>
																					<th>Type</th>
																					<th>Date Uploaded</th>
																					<th class="">Status</th>
																					<th class="text-center">Action</th>
																				</tr>
																			</thead>
																			<tbody>
																				<?php
                                                                        if (!is_null($docs)) {
                                                                            foreach ($docs as $doc) {
                                                                                $user = User::getCurrentUser($link, $doc->getUser());
                                                                                ?>
																					<tr class="docs">
																						<td>
																							<?php echo "{$user->getName()}"; ?>
																						</td>
																						<td class="">
																							<?php echo "{$doc->getType()}"; ?>
																						</td>
																						<td>
																							<?php echo (Helper::readableTime($doc->getTime())); ?>
																						</td>
																						<td <?php if (strcmp($doc->getStatus(), APPROVED) == 0) { ?> style="color: #009688"
																							<?php } else { ?> style="color: #e95f2b"
																								<?php } ?> class="status">
																									<?php echo "{$doc->getStatus()}"; ?>
																						</td>
																						<td class="text-center">
																							<div class="dropdown custom-dropdown">
																								<a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
																									<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-more-horizontal">
																										<circle cx="12" cy="12" r="1"></circle>
																										<circle cx="19" cy="12" r="1"></circle>
																										<circle cx="5" cy="12" r="1"></circle>
																									</svg>
																								</a>
																								<div class="dropdown-menu" aria-labelledby="dropdownMenuLink1"> <a href="<?php echo DOMAIN_NAME; ?>/dashboard/<?php echo " {$doc->getPath()}"; ?>" data-lightbox="image"  class="dropdown-item cursor">View</a>
																									<?php if (strcmp($doc->getStatus(), APPROVED) == 0) { ?> <a data-user="<?php echo " {$doc->getId()}"; ?>" data-email="<?php echo "{$doc->getUser()}"; ?>"  class="reject dropdown-item cursor">Reject</a> <a data-user="<?php echo " {$doc->getId()}"; ?>" style="display: none" class="approve dropdown-item cursor">Approve</a>
																										<?php } else if (strcmp($doc->getStatus(), "Rejected") == 0){ ?>
																											<?php } else { ?> <a data-user="<?php echo " {$doc->getId()}"; ?>"  class="approve dropdown-item cursor">Approve</a> <a data-user="<?php echo " {$doc->getId()}"; ?>" data-email="<?php echo "{$doc->getUser()}"; ?>"  class="reject dropdown-item cursor">Reject</a>
																												<?php } ?>
																								</div>
																							</div>
																						</td>
																					</tr>
																					<?php
                                                                            }
                                                                        } else {
                                                                            ?>
																						<tr>
																							<td colspan="5">
																								<p style="text-align: center">No document uploaded by user </p>
																							</td>
																						</tr>
																						<?php }
                                                                        ?>
																			</tbody>
																		</table>
																	</div>
																</div>
															</div>
														</div>
													</form>
												</div>
												<div class="col-xl-12 col-lg-12 col-md-12 layout-spacing">
													<form id="about" class="section about">
														<div class="info with-section">
															<h5 class="">Withdrawal History</h5>
															<div class="row">
																<div class="col-md-11 mx-auto">
																	<div class="table-responsive mb-4 style-1">
																		<table id="style-2" class="table style-1 table-hover non-hover">
																			<thead>
																				<tr>
																					<th>User</th>
																					<th>Amount</th>
																					<th>Wallet</th>
																					<th>Wallet Type</th>
																					<th>Date</th>
																					<th class="">Status</th>
																					<th class="text-center">Action</th>
																				</tr>
																			</thead>
																			<tbody>
																				<?php
                                                                        if (!is_null($withdrawals)) {
                                                                            foreach ($withdrawals as $withdrawal) {
                                                                                if (strcasecmp($withdrawal->getStatus(), SENT) == 0) {
                                                                                    continue;
                                                                                }
                                                                                $user = User::getCurrentUser($link, $withdrawal->getUser());
                                                                                ?>
																					<tr class="with">
																						<td>
																							<?php echo "{$user->getName()}"; ?>
																						</td>
																						<td class="">
																							<?php echo "{$withdrawal->getAmount()}"; ?>
																						</td>
																						<td class="" style="word-break: break-all;">
																							<?php echo "{$withdrawal->getWallet()}"; ?>
																						</td>
																						<td class="">
																							<?php echo "{$withdrawal->getType()}"; ?>
																						</td>
																						<td>
																							<?php echo (Helper::readableTime($withdrawal->getDate())); ?>
																						</td>
																						<td <?php if (strcmp($withdrawal->getStatus(), PAID) == 0) { ?> style="color: #009688"
																							<?php } else { ?> style="color: #e95f2b"
																								<?php } ?> class="status">
																									<?php echo "{$withdrawal->getStatus()}"; ?>
																						</td>
																						<td class="text-center">
																							<div class="dropdown custom-dropdown"> <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink<?php echo " {$withdrawal->getId()}"; ?>" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                                                                                                <svg
                                                                                                    xmlns="http://www.w3.org/2000/svg"
                                                                                                    width="24"
                                                                                                    height="24"
                                                                                                    viewBox="0 0 24 24"
                                                                                                    fill="none"
                                                                                                    stroke="currentColor"
                                                                                                    stroke-width="2"
                                                                                                    stroke-linecap="round"
                                                                                                    stroke-linejoin="round"
                                                                                                    class="feather feather-more-horizontal"
                                                                                                    >
                                                                                                <circle cx="12" cy="12" r="1"></circle>
                                                                                                <circle cx="19" cy="12" r="1"></circle>
                                                                                                <circle cx="5" cy="12" r="1"></circle>
                                                                                                </svg>
                                                                                            </a>
																								<?php if (strcmp($withdrawal->getStatus(), PAID) != 0) { ?>
																									<div class="dropdown-menu" aria-labelledby="dropdownMenuLink<?php echo " {$withdrawal->getId()}"; ?>"> <a data-user="<?php echo " {$withdrawal->getDate()}"; ?>" data-date="<?php echo "{$withdrawal->getUser()}"; ?>" class="dropdown-item cursor confirm">Confirm</a> <a data-user="<?php echo " {$withdrawal->getDate()}"; ?>" class="dropdown-item cursor delete">Delete</a> </div>
																									<?php } ?>
																										<?php if (strcmp($withdrawal->getStatus(), PAID) == 0) { ?>
																											<div class="dropdown-menu" aria-labelledby="dropdownMenuLink<?php echo " {$withdrawal->getId()}"; ?>"> <a class="dropdown-item cursor ">No action needed</a> </div>
																											<?php } ?>
																							</div>
																						</td>
																					</tr>
																					<?php
                                                                            }
                                                                        } else {
                                                                            ?>
																						<tr>
																							<td colspan="7">
																								<p style="text-align: center">No withdrawals history </p>
																							</td>
																						</tr>
																						<?php }
                                                                        ?>
																			</tbody>
																		</table>
																	</div>
																</div>
															</div>
														</div>
													</form>
												</div>
												<div class="col-xl-12 col-lg-12 col-md-12 layout-spacing">
													<form id="about" class="section about">
														<div class="info inv-section">
															<h5 class="">Investment Log</h5>
															<div class="row">
																<div class="col-md-11 mx-auto">
																	<div class="table-responsive mb-4 style-1">
																		<table id='style-7' class='table style-1 table-hover non-hover'>
																			<thead>
																				<tr>
																					<th>User</th>
																					<th>Amount</th>
																					<th>Payment Mode</th>
																					<th>Investment Plan</th>
																					<th>Date</th>
																					<th class=''>Status</th>
																					<th class='text-center'>Action</th>
																				</tr>
																			</thead>
																			<tbody>
																				<?php
                                                                        if (!is_null($invoices)) {
                                                                            foreach ($invoices as $invoice) {
                                                                                $user = User::getCurrentUser($link, $invoice->getUser());
                                                                                ?>
																					<tr class="inv">
																						<td>
																							<?php echo "{$user->getName()}"; ?>
																						</td>
																						<td>
																							<?php echo "{$invoice->getAmount()}"; ?>
																						</td>
																						<td>
																							<?php echo "{$invoice->getPaymentMode()}"; ?>
																						</td>
																						<td>
																							<?php echo "{$invoice->getPackage()}"; ?>
																						</td>
																						<td>
																							<?php echo Helper::readableTime($invoice->getDate()); ?>
																						</td>
																						<td style="color: #3c8dbc;">
																							<?php echo "{$invoice->getStatus()}"; ?>
																						</td>
																						<td class='text-center'>
																							<div class='dropdown custom-dropdown'>
																								<a class='dropdown-toggle' href='#' role='button' id='dropdownMenuLink' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true'>
																									<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-more-horizontal'>
																										<circle cx='12' cy='12' r='1'></circle>
																										<circle cx='19' cy='12' r='1'></circle>
																										<circle cx='5' cy='12' r='1'></circle>
																									</svg>
																								</a>
																								<div class='dropdown-menu' aria-labelledby='dropdownMenuLink'>
																									<?php
                                                                                                if (strcmp($invoice->getStatus(), CONFIRMED) != 0 && (strcmp($invoice->getStatus(), GROWING) != 0 && strcmp($invoice->getStatus(), Paused) != 0)) {
                                                                                                    if (is_null($invoice->getProof())) {
                                                                                                        ?> <a class='dropdown-item cursor dodo'>View payment proof</a>
																										<?php } else { ?> <a href="<?php echo DOMAIN_NAME; ?>/dashboard/<?php echo "{$invoice->getProof()}"; ?>" data-lightbox="image"  class="dropdown-item cursor">View payment proof</a>
																											<?php }
                                                                                                    ?>
																												<?php } ?>
																													<?php if (strcmp($invoice->getStatus(), CONFIRMED) != 0 && (strcmp($invoice->getStatus(), GROWING) != 0 && strcmp($invoice->getStatus(), Paused) != 0)) {
                                                                                                    ?> <a class='dropdown-item cursor confirminv' data-id="<?php echo " {$invoice->getId()}"; ?>" data-email="<?php echo "{$invoice->getUser()}"; ?>">Confirm</a>
																														<?php } ?> <a class='dropdown-item cursor deleteIn' data-id="<?php echo " {$invoice->getId()}"; ?>">Delete</a> </div>
																							</div>
																						</td>
																					</tr>
																					<?php
                                                                            }
                                                                        } else {
                                                                            ?>
																						<tr>
																							<td colspan="7">
																								<p style="text-align: center">No investment history </p>
																							</td>
																						</tr>
																						<?php }
                                                                        ?>
																			</tbody>
																		</table>
																	</div>
																</div>
															</div>
														</div>
													</form>
												</div>
												<div class="col-xl-12 col-lg-12 col-md-12 layout-spacing">
													<form id="about" class="section about ">
														<div class="info cinv-section activate-section">
															<h5 class="">
        Current Investment 
        <?php
        $totalInvestment = 0; // Initialize the total sum variable

        if (!is_null($cInvoices)) {
            foreach ($cInvoices as $invoice) {
                $totalInvestment += $invoice->getAmount(); // Accumulate the investment amount
            }
            echo number_format($totalInvestment, 2); // Display the total sum formatted to 2 decimal places
        } else {
            echo "0.00"; // Display 0 if there are no invoices
        }
        ?>
        <button data-user="" type="button" style="display: none" class="hide btn btn-danger">Convert to Compounding</button>
        <button data-user="<?php echo "{$user->getEmail()}"; ?>" type="button" class="fundC btn btn-warning" style="float: right; ">Fund Compounding</button>
	    <button data-user="<?php echo "{$user->getEmail()}"; ?>" type="button" class="deductC btn" style="float: right;background-color: #ff0000;color: white;margin-right: 20px;">Deduct Compounding</button>
        <?php
            if($user->box) {?>
                <button data-user="<?php echo $user->getEmail(); ?>" type="button" class="btn btn-default de-activate-compound">De-activate compounding box</button>
          <?php  } else { ?>
                <button data-user="<?php echo $user->getEmail(); ?>" type="button" class="btn btn-success activate-compound">Activate compounding box</button>
       <?php     }
        ?>
        
    </h5>
															<div class="row">
																<div class="col-md-11 mx-auto">
																	<div class="table-responsive mb-4 style-1">
																		<table id='style-90' class='table style-1 table-hover non-hover'>
																			<thead>
																				<tr>
																					<th style="color: #ff4400;">User</th>
																					<th style="color: #ff4400;">Amount</th>
																					<th style="color: #ff4400;">Investment Plan</th>
																					<th style="color: #ff4400;">Confirmed Date</th>
																					<th style="color: #ff4400;">Day's Count</th>
																					<th style="color: #ff4400;">Total Profit</th>
																					<th style="color: #ff4400;" class=''>Status</th>
																					<th style="color: #ff4400;" class='text-center'>Action</th>
																				</tr>
																			</thead>
																			<tbody>
																				<?php
                        if (!is_null($cInvoices)) {
                            foreach ($cInvoices as $invoice) {
                                $user = User::getCurrentUser($link, $invoice->getUser());
                                ?>
																					<tr class="inv">
																						<td>
																							<?php echo "{$user->getName()}"; ?>
																						</td>
																						<td>
																							<?php echo number_format($invoice->getAmount(), 2); ?>
																						</td>
																						<td>
																							<?php echo "{$invoice->getPackage()}"; ?>
																						</td>
																						<td>
																							<?php echo Helper::readableTime($invoice->getConfirmedDate()); ?>
																						</td>
																						<td style="color: #3c8dbc;">
																							<?php echo $invoice->getCount() . "/" . $invoice->getDays(); ?>
																						</td>
																						<td style="color: #3c8dbc;">
																							<?php echo $invoice->getCReturns(); ?>
																						</td>
																						<td style="color: #3c8dbc;">
																							<?php echo "{$invoice->getStatus()}"; ?>
																						</td>
																						<td class='text-center'>
																							<div class='dropdown custom-dropdown'>
																								<a class='dropdown-toggle' href='#' role='button' id='dropdownMenuLink' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true'>
																									<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-more-horizontal'>
																										<circle cx='12' cy='12' r='1'></circle>
																										<circle cx='19' cy='12' r='1'></circle>
																										<circle cx='5' cy='12' r='1'></circle>
																									</svg>
																								</a>
																								<div class='dropdown-menu' aria-labelledby='dropdownMenuLink'>
																									<?php
                                                if (strcmp($invoice->getStatus(), "Completed") != 0) {
                                                    if (strcmp($invoice->getStatus(), GROWING) == 0) {
                                                        ?> <a class='dropdown-item cursor pauseIn' data-id="<?php echo " {$invoice->getId()}"; ?>" data-email="<?php echo "{$invoice->getUser()}"; ?>">Pause</a>
																										<?php } else if (strcmp($invoice->getStatus(), Paused) == 0) {
                                                        ?> <a class='dropdown-item cursor resumeIn' data-id="<?php echo " {$invoice->getId()}"; ?>" data-email="<?php echo "{$invoice->getUser()}"; ?>">Resume</a>
																											<?php }
                                                    ?> <a class='dropdown-item cursor editInc' data-id="<?php echo " {$invoice->getId()}"; ?>" data-plan="<?php echo "{$invoice->getPackage()}"; ?>" data-email="<?php echo "{$invoice->getUser()}"; ?>" data-capital="<?php echo "{$invoice->getAmount()}"; ?>" data-days="<?php echo "{$invoice->getCount()}"; ?>" data-profit="<?php echo "{$invoice->getCReturns()}"; ?>">Edit</a>
																												<?php } ?>
																								</div>
																							</div>
																						</td>
																					</tr>
																					<?php
                            }
                        } else {
                            ?>
																						<tr>
																							<td colspan="7">
																								<p style="text-align: center">No investment history </p>
																							</td>
																						</tr>
																						<?php }
                        ?>
																			</tbody>
																		</table>
																	</div>
																</div>
															</div>
														</div>
													</form>
												</div>
												<div class="col-xl-12 col-lg-12 col-md-12 layout-spacing">
													<form id="about" class="section about">
														<div class="info wallet-section">
															<h5 class="">Wallet Deposit History (Balance: USD <?php echo User::getWalletBalance($link, $user->getEmail()); ?>)<button data-user="<?php echo "{$user->getEmail()}"; ?>" type="button" class="fund btn btn-warning" style="float: right; ">Fund Wallet</button>
															    <button data-user="<?php echo "{$user->getEmail()}"; ?>" type="button" class="deduct btn" style="float: right;background-color: #ff0000;color: white;margin-right: 20px;">Deduct Wallet</button>
															</h5>
															<div class="row">
																<div class="col-md-11 mx-auto">
																	<div class="table-responsive mb-4 style-1">
																		<table id="style-4" class="table style-1 table-hover non-hover">
																			<thead>
																				<tr>
																					<th>User</th>
																					<th>Amount</th>
																					<th>Proof</th>
																					<th>Date</th>
																					<th class="">Status</th>
																					<th class="text-center">Action</th>
																				</tr>
																			</thead>
																			<tbody>
																				<?php
                                                                        if (!is_null($wallets)) {
                                                                            foreach ($wallets as $wallet) {
                                                                                $user = User::getCurrentUser($link, $wallet->getUser());
                                                                                if (strcasecmp($wallet->getUser(), $wallet->getSender()) != 0 || strcasecmp($wallet->getStatus(), SENT) == 0 || strcasecmp($wallet->getStatus(), RECEIVED) == 0) {
                                                                                    continue;
                                                                                }
                                                                                ?>
																					<tr class="with">
																						<td>
																							<?php echo "{$user->getName()}"; ?>
																						</td>
																						<td class=""> $
																							<?php echo "{$wallet->getAmount()}"; ?>
																						</td>
																						<td class="" style="word-break: break-all;"> <a style="cursor: pointer; color: #3c8dbc; text-decoration: underline" href="<?php echo DOMAIN_NAME . "/dashboard/" . "{$wallet->getProof()}"; ?>" data-lightbox="image-<?php echo "{$wallet->getId()}"; ?>"   data-token="<?php echo "{$wallet->getId()}"; ?>" data-user="<?php echo "{$wallet->getUser()}"; ?>" >View Payment Proof</a></td>
																						<?php
                                                                                    if (!is_null($wallet->getProof()) && !empty($wallet->getProof())) {
                                                                                        echo '';
                                                                                    }
                                                                                    ?>
																							</td>
																							<td>
																								<?php echo (Helper::readableTime($wallet->getDate())); ?>
																							</td>
																							<td <?php if (strcasecmp($wallet->getStatus(), APPROVED) == 0) { ?> style="color: #009688"
																								<?php } else { ?> style="color: #e95f2b"
																									<?php } ?> class="status">
																										<?php echo "{$wallet->getStatus()}"; ?>
																							</td>
																							<td class="text-center">
																								<div class="dropdown custom-dropdown"> <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink<?php echo " {$wallet->getId()}"; ?>" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                                                                                                <svg
                                                                                                    xmlns="http://www.w3.org/2000/svg"
                                                                                                    width="24"
                                                                                                    height="24"
                                                                                                    viewBox="0 0 24 24"
                                                                                                    fill="none"
                                                                                                    stroke="currentColor"
                                                                                                    stroke-width="2"
                                                                                                    stroke-linecap="round"
                                                                                                    stroke-linejoin="round"
                                                                                                    class="feather feather-more-horizontal"
                                                                                                    >
                                                                                                <circle cx="12" cy="12" r="1"></circle>
                                                                                                <circle cx="19" cy="12" r="1"></circle>
                                                                                                <circle cx="5" cy="12" r="1"></circle>
                                                                                                </svg>
                                                                                            </a>
																									<?php if (strcasecmp($wallet->getStatus(), APPROVED) != 0) { ?>
																										<div class="dropdown-menu" aria-labelledby="dropdownMenuLink<?php echo " {$wallet->getId()}"; ?>"> <a data-user="<?php echo " {$wallet->getId()}"; ?>" data-amount="<?php echo "{$wallet->getAmount()}"; ?>" class="dropdown-item cursor editWalletDeposit">Edit</a> <a data-user="<?php echo " {$wallet->getId()}"; ?>"  class="dropdown-item cursor approveWalletDeposit">Confirm</a> <a data-user="<?php echo " {$wallet->getId()}"; ?>" class="dropdown-item cursor rejectWalletDeposit">Reject</a> </div>
																										<?php } ?>
																											<?php if (strcasecmp($wallet->getStatus(), APPROVED) == 0) { ?>
																												<div class="dropdown-menu" aria-labelledby="dropdownMenuLink<?php echo " {$wallet->getId()}"; ?>"> <a class="dropdown-item cursor ">No action needed</a> </div>
																												<?php } ?>
																								</div>
																							</td>
																					</tr>
																					<?php
                                                                            }
                                                                        } else {
                                                                            ?>
																						<tr>
																							<td colspan="7">
																								<p style="text-align: center">No wallet deposit history </p>
																							</td>
																						</tr>
																						<?php }
                                                                        ?>
																			</tbody>
																		</table>
																	</div>
																</div>
															</div>
														</div>
													</form>
												</div>
												<?php
												    // Fetch data from the three sources
                                                    $walletDeposits = Wallet::getWalletDeposit1($link, $user->getEmail());
                                                    $referralDeposits = Wallet::getReferralWallet($link, $user->getEmail());
                                                    $walletTransfers = Withdrawal::getWalletTransfer($link, $user->getEmail());
                                                    $invoices = Invoice::getInvoices($link, $user->getEmail());
                                                    $topups = Invoice::getTopups($link, $user->getEmail());
                                                    
                                                    
                                                    // Initialize an empty array to hold all transactions
                                                    $combinedData = [];
                                                    
                                                    // Process Wallet Deposits
                                                    if ($walletDeposits) {
                                                        foreach ($walletDeposits as $deposit) {
                                                            $combinedData[] = [
                                                                'id' => $deposit->getId(), // Add this line
                                                                'source' => 'wallet',      // Add this line
                                                                'date' => $deposit->getDate(),
                                                                'type' => 'Wallet Deposit',
                                                                'amount' => $deposit->getAmount(),
                                                                'status' => $deposit->getStatus(),
                                                                'sender' => $deposit->getSender(),
                                                                'proof' => $deposit->getProof(),
                                                                'confirmation' => ''
                                                            ];
                                                        }
                                                    }
                                                    
                                                    // Process Referral Wallet Deposits
                                                    if ($referralDeposits) {
                                                        foreach ($referralDeposits as $refDeposit) {
                                                            $combinedData[] = [
                                                                'id' => $refDeposit->getId(), // Add this line
                                                                'source' => 'referral',       // Add this line
                                                                'date' => $refDeposit->getDate(),
                                                                'type' => 'Referral Deposit',
                                                                'amount' => $refDeposit->getAmount(),
                                                                'status' => $refDeposit->description ?? " ",
                                                                'sender' => $refDeposit->getSender(),
                                                                'proof' => $refDeposit->getProof(),
                                                                'confirmation' => ''
                                                            ];
                                                        }
                                                    }
                                                    
                                                    // Process Investment Deposit
                                                    if ($invoices) {
                                                        foreach ($invoices as $invoice) {
                                                            $combinedData[] = [
                                                                'id' => $invoice->getId(), // Add this line
                                                                'source' => 'invoice',     // Add this line
                                                                'date' => $invoice->getDate(),
                                                                'type' => 'New Investment Deposit',
                                                                'amount' => $invoice->getAmount(),
                                                                'status' => $invoice->getStatus(),
                                                                'sender' => $invoice->getStatus(),
                                                                'proof' => $invoice->getStatus(),
                                                                'confirmation' => $invoice->confirmation ?? "Completed"
                                                            ];
                                                        }
                                                    }
                                                    
                                                    // Process Topups
                                                    if ($topups) {
                                                        foreach ($topups as $topup) {
                                                            $combinedData[] = [
                                                                'id' => $topup->getId(), // Add this line
                                                                'source' => 'topup',     // Add this line
                                                                'date' => $topup->getDate(),
                                                                'type' => 'Investment Topup',
                                                                'amount' => $topup->getAmount(),
                                                                'status' => $topup->getStatus(),
                                                                'sender' => $topup->getStatus(),
                                                                'proof' => $topup->getStatus(),
                                                            ];
                                                        }
                                                    }
                                                    
                                                    // Process Wallet Transfers
                                                    if ($walletTransfers) {
                                                        foreach ($walletTransfers as $transfer) {
                                                            $combinedData[] = [
                                                                'id' => $transfer->getId(), // Add this line
                                                                'source' => 'transfer',     // Add this line
                                                                'date' => $transfer->getDate(),
                                                                'type' => 'Wallet Transfer',
                                                                'amount' => $transfer->getAmount(),
                                                                'status' => $transfer->getStatus(),
                                                                'sender' => $transfer->getWallet(), 
                                                                'proof' => '',
                                                                'confirmation' => '',
                                                            ];
                                                        }
                                                    }

                                                    
                                                    // Sort the combined data by date in descending order (most recent first)
                                                    usort($combinedData, function($a, $b) {
                                                        return $b['date'] - $a['date'];
                                                    });
                                                    
                                                    // Function to categorize dates
                                                    function categorizeDate($timestamp) {
                                                        $transactionDate = date('Y-m-d', $timestamp);
                                                        $today = date('Y-m-d');
                                                        $yesterday = date('Y-m-d', strtotime('-1 day'));
                                                        $sevenDaysAgo = date('Y-m-d', strtotime('-7 days'));
                                                    
                                                        if ($transactionDate === $today) {
                                                            return 'Today';
                                                        } elseif ($transactionDate === $yesterday) {
                                                            return 'Yesterday';
                                                        } elseif ($transactionDate >= $sevenDaysAgo) {
                                                            return 'Last 7 Days';
                                                        } else {
                                                            return 'Older';
                                                        }
                                                    }
                                                    
                                                    // Group transactions by date categories
                                                    $groupedData = [];
                                                    
                                                    foreach ($combinedData as $transaction) {
                                                        $category = categorizeDate($transaction['date']);
                                                        if (!isset($groupedData[$category])) {
                                                            $groupedData[$category] = [];
                                                        }
                                                        $groupedData[$category][] = $transaction;
                                                    }
												?>
												<div class="col-xl-12 col-lg-12 col-md-12 layout-spacing">
													<form id="about" class="section about">
														<div class="info wallet-section">
															<h5 class="">Activity Logs</h5>
															<div class="row">
																<div class="col-md-11 mx-auto">
																	<div class="table-responsive mb-4 style-1">
																		<table class="table style-1 table-hover non-hover" id="style-4">
            <?php if (!empty($groupedData)): ?>
                <?php foreach ($groupedData as $category => $transactions): ?>
                    <?php if (!empty($transactions)): ?>
                        <thead>
                            <tr>
                                <th colspan="5" style="color: rgb(32, 183, 87)"><?php echo htmlspecialchars($category); ?></th>
                            </tr>
                            <tr>
                                <th>Date</th>
                                <th>Type</th>
                                <th>Amount</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($transactions as $transaction): ?>
                                <tr>
                                    <td><?php echo date('F j, Y, g:i a', $transaction['date']); ?></td>
                                    <td><?php echo htmlspecialchars($transaction['type']); ?></td>
                                    <td><?php echo '$' . number_format($transaction['amount'], 2); ?>
                                        <?php
                                            if(isset($transaction['confirmation']) && !empty(trim($transaction['confirmation'])) && strcasecmp($transaction['confirmation'],"completed") !== 0) {?>
                                                <span style="display: block; color: wheat"><?php echo $transaction['confirmation']; ?>/3</span>
                                            <?php }
                                        ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($transaction['status']); ?></td>
                                    <td>
                <!-- Delete Link -->
                <a class="btn btn-danger" href="delete_transaction.php?id=<?php echo urlencode($transaction['id']); ?>&source=<?php echo urlencode($transaction['source']); ?>&user=<?php echo $user->getEmail(); ?>" onclick="return confirm('Are you sure you want to delete this transaction?');">Delete</a>
            </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    <?php endif; ?>
                <?php endforeach; ?>
            <?php else: ?>
                <thead>
                    <tr>
                        <th>No Transactions Found</th>
                    </tr>
                </thead>
            <?php endif; ?>
        </table>
																	</div>
																</div>
															</div>
														</div>
													</form>
												</div>
												<div class="col-lg-12">
													<div class="statbox widget box box-shadow settings">
														<div class="card">
															<div class="card-body">
																<h5 class="card-title">User settings</h5>
																<form method="POST" action="view-user?email=<?php echo ($user->getEmail()); ?>">
																	<div class="settings-notification settings-profile">
																		<ul>
																			<li>
																				<div class="notification-info">
																					<p>Block Investment</p> <span>Block the user from investing</span> </div>
																				<div class="custom-control custom-switch">
																					<input name="istatus" type="checkbox" <?php if (!is_null($user->istatus)) { echo ("checked"); } ?> class="custom-control-input sts cursor" id="notification5">
																					<label class="custom-control-label cursor" for="notification5"></label>
																				</div>
																				<label>Message to display</label>
																				<textarea class="form-control" name='imessage'></textarea>
																				<input type="hidden" name="iss" />
																				<input type="submit" value="Save Settings" style="margin-top: 26px;"> </li>
																		</ul>
																	</div>
																</form>
																<form method="post">
																	<div class="settings-notification settings-profile">
																		<ul>
																			<li>
																				<div class="notification-info">
																					<p>Google Authenticator</p> <span>Reset 2fa for this user</span>
																					<button data-user="<?php echo " {$user->getEmail()}"; ?>" type="button" class="reset btn btn-warning">Reset</button>
																				</div>
																			</li>
																			<li>
																				<div class="notification-info">
																					<p>Withdrawal Settings</p> <span>Decide how to allow the user make withdrawal</span>
																					<select class='placeholder js-states form-control' required id="list" name="type_">
																						<option selected value="<?php echo DAILY; ?>">Daily</option>
																						<option value="<?php echo WEEKLY; ?>">Weekly</option>
																						<option value="<?php echo BI_WEEKLY; ?>">Bi-Weekly</option>
																						<option value="<?php echo MONTHLY; ?>">Monthly</option>
																					</select>
																				</div>
																			</li>
																		</ul>
																	</div>
																</form>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
							<?php require_once './partials/footer.php'; ?>
						</div>
						<!--  END CONTENT AREA  -->
				</div>
		</div>
		<div class="modal fade" id="addReferralModal" tabindex="-1" aria-labelledby="addReferralModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Add Referral</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <!-- Users Table -->
        <table class="table table-striped">
          <thead>
            <tr>
              <th>Select</th>
              <th>Name</th>
              <th>Email</th>
              <!-- Add other columns if needed -->
            </tr>
          </thead>
          <tbody>
            <?php foreach ($users as $user): ?>
            <tr>
              <td><input type="checkbox" class="user-checkbox" value="<?php echo htmlspecialchars($user['email']); ?>"></td>
              <td><?php echo htmlspecialchars($user['name']); ?></td>
              <td><?php echo htmlspecialchars($user['email']); ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <div class="modal-footer">
        <button type="button" id="saveReferralBtn" class="btn btn-primary">Add Selected Referrals</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
		<div class="modal fade login-modal" id="loginModal2" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true">
			<div class="modal-dialog" role="document">
				<div class="modal-content">
					<div class="modal-header" id="loginModalLabel">
						<h4 class="modal-title">Edit wallet deposit</h4>
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
							<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-x">
								<line x1="18" y1="6" x2="6" y2="18"></line>
								<line x1="6" y1="6" x2="18" y2="18"></line>
							</svg>
						</button>
					</div>
					<div class="modal-body">
						<form>
							<div class="form-row">
								<div class="col-md-6">
									<input type="hidden" id="prick_" value="" />
									<label for="generateKey">Wallet Amount</label>
									<input id="generateKey" name="walletamount_" type="text" class="form-control" placeholder="Wallet Amount"> </div>
								<div class="col-md-12 settings-profile">
									<button style="background: #007bff;color: #fff;font-weight: 600;padding: 10px 25px;height: inherit;font-size: 16px;margin-top: 10px;border: 1px solid #007bff;" id="prick" type="button" value="Save">Save</button>
								</div>
							</div>
						</form>
					</div>
				</div>
			</div>
		</div>
		<!-- END MAIN CONTAINER -->
		<div class="modal fade login-modal" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true">
			<div class="modal-dialog" role="document">
				<div class="modal-content">
					<div class="modal-header" id="loginModalLabel">
						<h4 class="modal-title">Edit Returns</h4>
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
							<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-x">
								<line x1="18" y1="6" x2="6" y2="18"></line>
								<line x1="6" y1="6" x2="18" y2="18"></line>
							</svg>
						</button>
					</div>
					<div class="modal-body">
						<form>
							<div class="form-row">
								<div class="col-md-12">
									<input type="hidden" name="idInc" />
									<input type="hidden" name="idUser" />
									<label for="generateKey">Total Capital</label>
									<input id="capital" name="capital" type="text" value="" class="form-control" placeholder="Total Capital"> </div>
								<div class="col-md-12">
									<label for="rewritePassword">Net Profit</label>
									<input id="profit" value="" name="profit" type="text" class="form-control" placeholder="Net Profit"> </div>
								<div class="col-md-12">
									<label for="rewritePassword">Days</label>
									<input id="days" value="" name="days" type="text" class="form-control" placeholder="Days"> </div>
								<div class="col-md-12">
    <label for="plan">Plan</label>
    <select id="plan" name="plan" class="form-control">
        <?php
        // Fetch all available plans from the database
        $plans = Investment::getInvesments($link); 
        foreach($plans as $plan) {
            // Check if the plan is the current one assigned to the user
            $selected = ($plan->getName() === $invoice->getPackage()) ? 'selected' : '';
            echo "<option value=\"{$plan->getName()}\" $selected>{$plan->getName()}</option>";
        }
        ?>
    </select>
</div>

								<div class="col-md-12 settings-profile" style="margin-top: 20px">
									<input type="button" id="saveInc" value="Save"> </div>
							</div>
						</form>
					</div>
				</div>
			</div>
		</div>
		<!-- Bootstrap Modal for Funding Wallet -->
		<!-- Bootstrap Modal for Funding Wallet -->
		<div class="modal fade" id="fundModal" tabindex="-1" aria-labelledby="fundModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<form id="fundForm">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title">Fund Wallet</h5>
							<button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button>
						</div>
						<div class="modal-body">
							<div class="form-group">
								<label for="fundAmount">Amount</label>
								<input type="text" class="form-control" id="fundAmount" name="amount" placeholder="Enter amount" required> </div>
							<div class="form-group">
								<label for="fundDescription">Description</label>
								<textarea class="form-control" id="fundDescription" name="description" placeholder="Enter description" required></textarea>
							</div>
						</div>
						<div class="modal-footer">
							<button type="submit" class="btn btn-primary">Fund Wallet</button>
							<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
						</div>
					</div>
				</form>
			</div>
		</div>
		
		<div class="modal fade" id="fundModalR" tabindex="-1" aria-labelledby="fundModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<form id="fundFormR">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title">Fund Referral Wallet</h5>
							<button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button>
						</div>
						<div class="modal-body">
							<div class="form-group">
								<label for="fundAmount">Amount</label>
								<input type="text" class="form-control" id="fundAmountR" name="amount" placeholder="Enter amount" required> </div>
							<div class="form-group">
								<label for="fundDescription">Description</label>
								<textarea class="form-control" id="fundDescriptionR" name="description" placeholder="Enter description" required></textarea>
							</div>
						</div>
						<div class="modal-footer">
							<button type="submit" class="btn btn-primary">Fund Referral Wallet</button>
							<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
						</div>
					</div>
				</form>
			</div>
		</div>
		
		<div class="modal fade" id="fundModalC" tabindex="-1" aria-labelledby="fundModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<form id="fundFormC">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title">Fund Compounding Wallet</h5>
							<button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button>
						</div>
						<div class="modal-body">
							<div class="form-group">
								<label for="fundAmount">Amount</label>
								<input type="text" class="form-control" id="fundAmountC" name="amount" placeholder="Enter amount" required>
							</div>
						
						</div>
						<div class="modal-footer">
							<button type="submit" class="btn btn-primary">Fund Compound Wallet</button>
							<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
						</div>
					</div>
				</form>
			</div>
		</div>
		<?php require_once './partials/scripts.php'; ?>
			<script src="../js/datatables.js" type="text/javascript"></script>
			<script src="../js/snackbar.min.js" type="text/javascript"></script>
			<script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/js/lightbox.min.js"></script>
			<script src="../js/jqueryblockui.js" type="text/javascript"></script>
			<script src="../js/customblockui.js" type="text/javascript"></script>
			<?php
			$user = User::getCurrentUser($link, $_GET['email']);
			?>
			<script>
                $('.activate-compound').click(function() {
                   let email = '<?php echo $user->getEmail(); ?>'; 
                    loader('div.activate-section');
                 	axios.get('v1/activate-box.php', {
    					params: {
    				    	user: email
    					}
    				}).then((response) => {
    						window.location.href = "view-user?email=" + email;
    				}).catch((error) => {
    					showToast("Error occured");
    				}).finally(() => {
    					removeLoader('div.activate-section');
    				});
                });
                
                $('.de-activate-compound').click(function() {
                   let email = '<?php echo $user->getEmail(); ?>'; 
                    loader('div.activate-section');
                 	axios.get('v1/de-activate-box.php', {
    					params: {
    				    	user: email
    					}
    				}).then((response) => {
    						window.location.href = "view-user?email=" + email;
    				}).catch((error) => {
    					showToast("Error occured");
    				}).finally(() => {
    					removeLoader('div.activate-section');
    				});
                });
                
                
                $(document).ready(function() {
                    // Show the modal when the Add Referral button is clicked
                    $('#addReferralBtn').click(function() {
                        $('#addReferralModal').modal('show');
                    });
                
                    // Handle the Add Selected Referrals button click
                    $('#saveReferralBtn').click(function() {
                        // Get selected user emails
                        var selectedEmails = [];
                        $('.user-checkbox:checked').each(function() {
                            selectedEmails.push($(this).val());
                        });
                
                        if (selectedEmails.length === 0) {
                            alert('Please select at least one user.');
                            return;
                        }
                
                        // Get the user email from the data-user attribute
                        var userEmail = $('#addReferralBtn').data('user');
                
                        // Send AJAX request to add referrals
                        $.ajax({
                            url: 'add_referrals.php', // Adjust the path to your PHP script
                            type: 'POST',
                            data: { emails: selectedEmails, userEmail: userEmail },
                            success: function(response) {
                                // Handle success
                                alert('Referrals added successfully.');
                                $('#addReferralModal').modal('hide');
                                // Optionally, refresh the page or update the UI
                                location.reload();
                            },
                            error: function(xhr, status, error) {
                                // Handle error
                                alert('Error adding referrals: ' + error);
                            }
                        });
                    });
                });
                </script>
			<script>
		
			let query = "select[name='type_'] option[value='" + '<?php echo $user->getWSettings() ?? ""; ?>' + "']";
			$(query).prop('selected', true);
			// var e;
			c1 = $("#style-1").DataTable({
				oLanguage: {
					oPaginate: {
						sPrevious: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>',
						sNext: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>',
					},
					sInfo: "Showing page _PAGE_ of _PAGES_",
					sSearch: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
					sSearchPlaceholder: "Search...",
					sLengthMenu: "Results :  _MENU_",
				},
				lengthMenu: [10, 20, 30, 50],
				pageLength: 10,
			});
			multiCheck(c1);
			c2 = $("#style-2").DataTable({
				oLanguage: {
					oPaginate: {
						sPrevious: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>',
						sNext: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>',
					},
					sInfo: "Showing page _PAGE_ of _PAGES_",
					sSearch: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
					sSearchPlaceholder: "Search...",
					sLengthMenu: "Results :  _MENU_",
				},
				lengthMenu: [0, 20, 30, 50],
				pageLength: 20,
			});
			multiCheck(c2);
			c3 = $("#style-3").DataTable({
				oLanguage: {
					oPaginate: {
						sPrevious: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>',
						sNext: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>',
					},
					sInfo: "Showing page _PAGE_ of _PAGES_",
					sSearch: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
					sSearchPlaceholder: "Search...",
					sLengthMenu: "Results :  _MENU_",
				},
				lengthMenu: [10, 20, 30, 50],
				pageLength: 10,
			});
			multiCheck(c3);
			c4 = $("#style-4").DataTable({
				oLanguage: {
					oPaginate: {
						sPrevious: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>',
						sNext: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>',
					},
					sInfo: "Showing page _PAGE_ of _PAGES_",
					sSearch: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
					sSearchPlaceholder: "Search...",
					sLengthMenu: "Results :  _MENU_",
				},
				lengthMenu: [10, 20, 30, 50],
				pageLength: 10,
			});
			multiCheck(c4);
			c7 = $("#style-7").DataTable({
				oLanguage: {
					oPaginate: {
						sPrevious: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>',
						sNext: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>',
					},
					sInfo: "Showing page _PAGE_ of _PAGES_",
					sSearch: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
					sSearchPlaceholder: "Search...",
					sLengthMenu: "Results :  _MENU_",
				},
				lengthMenu: [10, 20, 30, 50],
				pageLength: 10,
			});
			multiCheck(c7);
			c90 = $("#style-90").DataTable({
				oLanguage: {
					oPaginate: {
						sPrevious: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>',
						sNext: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>',
					},
					sInfo: "Showing page _PAGE_ of _PAGES_",
					sSearch: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
					sSearchPlaceholder: "Search...",
					sLengthMenu: "Results :  _MENU_",
				},
				lengthMenu: [10, 20, 30, 50],
				pageLength: 10,
			});
			multiCheck(c90);
			</script>
			<script>
			$('.dodo').click(function() {
				alert("The user has not uploaded payment proof");
			});

			function loader(blockContent) {
				var block = $(blockContent);
				$(block).block({
					message: "<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-loader spin'><line x1='12' y1='2' x2='12' y2='6'></line><line x1='12' y1='18' x2='12' y2='22'></line><line x1='4.93' y1='4.93' x2='7.76' y2='7.76'></line><line x1='16.24' y1='16.24' x2='19.07' y2='19.07'></line><line x1='2' y1='12' x2='6' y2='12'></line><line x1='18' y1='12' x2='22' y2='12'></line><line x1='4.93' y1='19.07' x2='7.76' y2='16.24'></line><line x1='16.24' y1='7.76' x2='19.07' y2='4.93'></line></svg>",
					overlayCSS: {
						backgroundColor: '#000',
						opacity: 0.8,
						zIndex: 99999,
						cursor: 'wait'
					},
					css: {
						border: 0,
						color: '#fff',
						padding: 0,
						backgroundColor: 'transparent'
					}
				});
			}

			function removeLoader(element) {
				$(element).unblock();
			}
			$('#list').change(function() {
				loader('div.settings');
				axios.get('v1/withdrawal-settings', {
					params: {
						user: '<?php echo $user->getEmail(); ?>',
						option: $("option:selected", this).val()
					}
				}).then((response) => {
					showToast("Settings Changed.");
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.settings');
				});
			});
			$('.confirm').click(function() {
				var user = $(this).attr('data-date');
				var date = $(this).attr('data-user');
				loader('div.with-section');
				axios.get('v1/confirm-withdrawal', {
					params: {
						id: date,
						user: user
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						$(this).closest('tr.with').find('td.status').text(data.msg).css("color", "#009688");
						$(this).hide().next().hide();
					} else {
						showToast("Error occured");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.with-section');
				});
			});
		$('.editInc').click(function() {
    $("input[name='capital']").val($(this).attr("data-capital"));
    $("input[name='profit']").val($(this).attr("data-profit"));
    $("input[name='days']").val($(this).attr("data-days"));
    $("input[name='idInc']").val($(this).attr("data-id"));
    $("input[name='idUser']").val($(this).attr("data-email"));

    // Set the plan in the select input
    $("select[name='plan']").val($(this).attr("data-plan"));
    
    $('#loginModal').modal();
});

$('#saveInc').click(function() {
    loader('body');
    $('#loginModal').modal('hide');
    var email = $("input[name='idUser']").val();
    axios.get('v1/edit-invoice', {
        params: {
            id: $("input[name='idInc']").val(),
            capital: $("input[name='capital']").val(),
            profit: $("input[name='profit']").val(),
            email: $("input[name='idUser']").val(),
            days: $("input[name='days']").val(),
            plan: $("select[name='plan']").val() // Include the selected plan
        }
    }).then((response) => {
        var data = response.data;
        if(!data.error) {
            showToast("Operation successful");
            window.location.href = "view-user?email=" + email;
        } else {
            showToast("Error occured");
        }
    }).catch((error) => {
        showToast("Error occured");
    }).finally(() => {
        removeLoader('body');
    });
});

			$('.confirminv').click(function() {
				var user = $(this).attr('data-id');
				var email = $(this).attr('data-email');
				loader('div.inv-section');
				axios.get('v1/confirm-invoice', {
					params: {
						id: user,
						email: email
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Confirmed successful");
						window.location.href = "view-user?email=" + email;
					} else {
						showToast("Error occured");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.inv-section');
				});
			});
			$('.approve').click(function() {
				var user = $(this).attr('data-user');
				loader('div.docs-section');
				axios.get('v1/approve-document', {
					params: {
						id: user
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						$(this).closest('tr.docs').find('td.status').text(data.msg).css("color", "#009688");
						if($(this).next().length == 1) {
							$(this).hide().next().show();
						} else if($(this).next().length == 0) {
							$(this).hide().prev().show();
						}
					} else {
						showToast("Error occured");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.docs-section');
				});
			});
			$('.reject').click(function() {
				var user = $(this).attr('data-user');
				var email = $(this).attr('data-email');
				loader('div.docs-section');
				axios.get('v1/reject-document', {
					params: {
						id: user
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						if($(this).next().length == 1) {
							$(this).hide().next().show();
						} else if($(this).next().length == 0) {
							$(this).hide().prev().show();
						}
						$(this).closest('tr.docs').find('td.status').text(data.msg).css("color", "#e95f2b");
						window.location.href = "view-user?email=" + email;
					} else {
						showToast("Error occured");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.docs-section');
				});
			});
			$('.delete').click(function() {
				var user = $(this).attr('data-user');
				loader('div.with-section');
				axios.get('v1/delete-withdrawal', {
					params: {
						id: user
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Deleted Successful");
						$("#style-2").DataTable().row($(this).closest('tr.with')).remove().draw();
					} else {
						showToast("Error occured");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.with-section');
				});
			});
			$('.deleteIn').click(function() {
				var user = $(this).attr('data-id');
				loader('div.inv-section');
				axios.get('v1/delete-invoice', {
					params: {
						id: user
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Deleted Successful");
						$("#style-7").DataTable().row($(this).closest('tr.inv')).remove().draw();
					} else {
						showToast("Error occured");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.inv-section');
				});
			});
			$('.pauseIn').click(function() {
				var user = $(this).attr('data-id');
				var email = $(this).attr('data-email');
				loader('div.cinv-section');
				axios.get('v1/pause-invoice', {
					params: {
						id: user,
						email: email
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Operation Successful");
						window.location.href = "view-user?email=" + email;
					} else {
						showToast("Error occured");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.cinv-section');
				});
			});
			$('.resumeIn').click(function() {
				var user = $(this).attr('data-id');
				var email = $(this).attr('data-email');
				loader('div.cinv-section');
				axios.get('v1/resume-invoice', {
					params: {
						id: user,
						email: email
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Operation Successful");
						window.location.href = "view-user?email=" + email;
					} else {
						showToast("Error occured");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.cinv-section');
				});
			});
			$('.rejectWalletDeposit').click(function() {
				var user = $(this).attr('data-user');
				loader('div.wallet-section');
				axios.get('v1/delete-wallet-deposit', {
					params: {
						id: user
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Deleted Successful");
						$("#style-4").DataTable().row($(this).closest('tr.with')).remove().draw();
					} else {
						showToast("Error occured");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.wallet-section');
				});
			});
			$('.approveWalletDeposit').click(function() {
				let c = confirm("Are you sure");
				if(!c) {
					return;
				}
				var user = $(this).attr('data-user');
				loader('div.wallet-section');
				axios.get('v1/approve-wallet-deposit', {
					params: {
						id: user
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Deposit Confirmed Successful");
						$(this).hide().next().hide();
						$(this).closest('tr.with').find('td.status').text(data.msg).css("color", "#e95f2b");
					} else {
						showToast("Error occured");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.wallet-section');
				});
			});
			$('.editWalletDeposit').click(function() {
				$("#prick_").val($(this).attr('data-user'));
				let amount = $(this).attr('data-amount');
				$("input[name='walletamount_']").val(amount);
				$('#loginModal2').modal();
				return;
			});
			$('#prick').click(function(e) {
				e.preventDefault();
				$('#loginModal2').modal('hide');
				loader('div.wallet-section');
				let amount = $("input[name='walletamount_']").val();
				let user = $("#prick").val();
				axios.get('v1/edit-wallet-deposit', {
					params: {
						id: user,
						amount: amount
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Amount updated!");
						window.location.href = "view-user?email=" + '<?php if (isset($_GET['
						email '])) echo $_GET['
						email ']; ?>';
					} else {
						showToast("No change in amount");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.wallet-section');
				});
			});
			$('.reset').click(function() {
				var r = confirm("Are you sure");
				if(r) {
					var user = $(this).attr('data-user');
					loader('div.settings');
					axios.get('v1/reset-2fa', {
						params: {
							id: user
						}
					}).then((response) => {
						var data = response.data;
						if(!data.error) {
							showToast(data.msg);
						} else {
							showToast(data.error);
						}
					}).catch((error) => {
						showToast("Error occured");
					}).finally(() => {
						removeLoader('div.settings');
					});
				}
			});
			// Show the modal when '.fund' element is clicked
			// Function to format number with commas
			function formatNumberWithCommas(number) {
				return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
			}
			// Function to remove commas from a string
			function removeCommas(string) {
				return string.replace(/,/g, '');
			}
			// Show the modal when '.fund' element is clicked
			$('.fund').click(function() {
				var user = $(this).attr('data-user');
				$('#fundModal').data('user', user); // Store the user in the modal's data
				$('#fundModal').modal('show'); // Show the modal
			});
			// Format amount input with commas as user types
			$('#fundAmount').on('input', function() {
				var value = $(this).val();
				// Remove any non-digit characters except for the decimal point
				var numericValue = value.replace(/[^0-9.]/g, '');
				// Split integer and decimal parts if any
				var parts = numericValue.split('.');
				// Format the integer part with commas
				parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
				// Join the parts back together
				var formattedValue = parts.join('.');
				$(this).val(formattedValue);
			});
			// Handle the form submission inside the modal
			$('#fundForm').submit(function(event) {
				event.preventDefault(); // Prevent default form submission
				// Remove commas before processing
				var amountInput = $('#fundAmount').val();
				var amount = removeCommas(amountInput);
				var description = $('#fundDescription').val();
				var user = $('#fundModal').data('user');
				// Input validation
				if(amount === null || amount.trim().length === 0 || parseFloat(amount) <= 0 || isNaN(amount)) {
					alert("Please enter a valid amount greater than zero.");
					return;
				}
				if(description === null || description.trim().length === 0) {
					alert("Please enter a description.");
					return;
				}
				// Close the modal
				$('#fundModal').modal('hide');
				// Show loader
				loader('div.wallet-section');
				// Make the axios request with amount and description
				axios.get('v1/fund-wallet', {
					params: {
						user: user,
						amount: amount,
						description: description
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Wallet Funded");
						window.location.href = "view-user?email=" + user;
					} else {
						showToast("An error occurred while funding the wallet.");
					}
				}).catch((error) => {
					showToast("An error occurred while processing your request.");
				}).finally(() => {
					// Remove loader
					removeLoader('div.wallet-section');
				});
			});
			
			$('#fundAmountR').on('input', function() {
				var value = $(this).val();
				// Remove any non-digit characters except for the decimal point
				var numericValue = value.replace(/[^0-9.]/g, '');
				// Split integer and decimal parts if any
				var parts = numericValue.split('.');
				// Format the integer part with commas
				parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
				// Join the parts back together
				var formattedValue = parts.join('.');
				$(this).val(formattedValue);
			});
			
			$('#fundFormR').submit(function(event) {
				event.preventDefault(); // Prevent default form submission
				// Remove commas before processing
				var amountInput = $('#fundAmountR').val();
				var amount = removeCommas(amountInput);
				var description = $('#fundDescriptionR').val();
				var user = $('#fundModalR').data('user');
				// Input validation
				if(amount === null || amount.trim().length === 0 || parseFloat(amount) <= 0 || isNaN(amount)) {
					alert("Please enter a valid amount greater than zero.");
					return;
				}
				if(description === null || description.trim().length === 0) {
					alert("Please enter a description.");
					return;
				}
				// Close the modal
				$('#fundModalR').modal('hide');
				// Show loader
				loader('div.wallet-section');
				// Make the axios request with amount and description
				axios.get('v1/fund-walletR', {
					params: {
						user: user,
						amount: amount,
						description: description
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Referral Wallet Funded");
						window.location.href = "view-user?email=" + user;
					} else {
						showToast("An error occurred while funding the wallet.");
					}
				}).catch((error) => {
					showToast("An error occurred while processing your request.");
				}).finally(() => {
					// Remove loader
					removeLoader('div.wallet-section');
				});
			});
			
			$('.fundR').click(function() {
			    var user = $(this).attr('data-user');
				$('#fundModalR').data('user', user); // Store the user in the modal's data
				$('#fundModalR').modal('show'); // Show the modal
				
				
			});
			$('.deductR').click(function() {
				var amount = prompt("Enter amount");
				if(amount === null || amount.trim().length < 0) {
					return;
				}
				if(amount <= 0) {
					alert("Enter a valid amount");
					return;
				}
				if(amount > <?php echo User::getWalletBalanceR($link, $user->getEmail()); ?>) {
					alert("Amount to deduct is greater than balance");
					return;
				}
				var user = $(this).attr('data-user');
				loader('div.scrollspy-example');
				axios.get('v1/deduct-referral', {
					params: {
						user: user,
						amount: amount
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Referral Wallet Defunded");
						window.location.href = "view-user?email=" + user;
					} else {
						showToast("Error occured");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.scrollspy-example');
				});
			});
			
			$('#fundFormC').submit(function(event) {
				event.preventDefault(); // Prevent default form submission
				// Remove commas before processing
				var amountInput = $('#fundAmountC').val();
				var amount = removeCommas(amountInput);
				var user = $('#fundModalC').data('user');
				// Input validation
				if(amount === null || amount.trim().length === 0 || parseFloat(amount) <= 0 || isNaN(amount)) {
					alert("Please enter a valid amount greater than zero.");
					return;
				}
			
				// Close the modal
				$('#fundModalC').modal('hide');
				// Show loader
				loader('div.activate-section');
				// Make the axios request with amount and description
				axios.get('v1/fund-walletC', {
					params: {
						user: user,
						amount: amount,
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Compound Wallet Funded");
						window.location.href = "view-user?email=" + user;
					} else {
						showToast("An error occurred while funding the wallet.");
					}
				}).catch((error) => {
					showToast("An error occurred while processing your request.");
				}).finally(() => {
					// Remove loader
					removeLoader('div.activate-section');
				});
			});
			
			$('.fundC').click(function() {
			    var user = $(this).attr('data-user');
				$('#fundModalC').data('user', user); // Store the user in the modal's data
				$('#fundModalC').modal('show'); // Show the modal
				
				
			});
			$('.deductC').click(function() {
				var amount = prompt("Enter amount");
				if(amount === null || amount.trim().length < 0) {
					return;
				}
				if(amount <= 0) {
					alert("Enter a valid amount");
					return;
				}
				if(amount > <?php echo User::getWalletBalanceC($link, $user->getEmail()); ?>) {
					alert("Amount to deduct is greater than balance");
					return;
				}
				var user = $(this).attr('data-user');
				loader('div.scrollspy-example');
				axios.get('v1/deduct-compound', {
					params: {
						user: user,
						amount: amount
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Compound Wallet Defunded");
						window.location.href = "view-user?email=" + user;
					} else {
						showToast("Error occured");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.scrollspy-example');
				});
			});
			
			$('.deduct').click(function() {
				var amount = prompt("Enter amount");
				if(amount === null || amount.trim().length < 0) {
					return;
				}
				if(amount <= 0) {
					alert("Enter a valid amount");
					return;
				}
				if(amount > <?php echo User::getWalletBalance($link, $user->getEmail()); ?>) {
					alert("Amount to deduct is greater than balance");
					return;
				}
				var user = $(this).attr('data-user');
				loader('div.wallet-section');
				axios.get('v1/deduct-wallet', {
					params: {
						user: user,
						amount: amount
					}
				}).then((response) => {
					var data = response.data;
					if(!data.error) {
						showToast("Wallet Deducted");
						window.location.href = "view-user?email=" + user;
					} else {
						showToast("Error occured");
					}
				}).catch((error) => {
					showToast("Error occured");
				}).finally(() => {
					removeLoader('div.wallet-section');
				});
			});
			<?php if (isset($error)) { ?>
			showToast('<?php echo $error; ?>');
			<?php }
                ?>
                
            <?php if (isset($_SESSION['error'])) { ?>
			    showToast('<?php echo $_SESSION['error']; ?>');
			<?php }  ?>
                
            <?php if (isset($_SESSION['success'])) { ?>
			    showToast('<?php echo $_SESSION['success']; ?>');
			<?php } ?>

			function showToast(msg) {
				Snackbar.show({
					text: msg,
					pos: 'top-right'
				});
			}
			</script>
	</body>

	</html>