<?php
session_start();
include("connection.php");


if(isset($_SESSION['admin'])){
    
$email = $_GET['email'];

$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($myConn, $sql);
$row = mysqli_fetch_assoc($result);
 
$fullname = $row["firstname"] . ' ' . $row["lastname"];
$email = $row["email"];
$username = $row["username"];
$phone = $row["mobile"];
$total_balance = $row["total_balance"];
$profit_balance = $row["profit_balance"];
$kyc_status = ucfirst($row["kyc_status"]); // Capitalize KYC status
$date = date("Y-m-d H:i:s", strtotime($row["created_at"])); // Format date

?>
<?php include('header.php') ?>


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

                <!-- Page title box -->
                <div class="page-title-box">
                    <ol class="breadcrumb float-right">

                        <li class="breadcrumb-item"><a href="deposit.php">Fund</a></li>
                        <li class="breadcrumb-item active">Fund Account</li>
                    </ol>
                    <h4 class="page-title">Edit user balance for <?php echo $email;?></h4>
                </div>
                    <!-- End page title box -->




                    <div class="row">
                        <div class="col-12">
                            <div class="card-box">
                                <form action="fundusers.php?email=<?php echo $email ?>" method="post">
                                    <div class="modal-body">
                                        <!-- Hidden Input for Email -->
                                        <input type="hidden" name="email" value="<?php echo htmlspecialchars($row['email']); ?>">
                                
                                        <!-- Select Input for Balance Type -->
                                        <div class="mb-3">
                                            <label for="balanceType<?php echo $row['email']; ?>" class="form-label">Select Balance Type</label>
                                            <select class="form-control" id="balanceType<?php echo $row['email']; ?>" name="balance_type" required>
                                                <option value="total_balance">Total Balance</option>
                                                <option value="profit_balance">Profit Balance</option>
                                            </select>
                                        </div>
                                
                                        <!-- Input for Deposit Amount -->
                                        <div class="mb-3">
                                            <label for="amount<?php echo $row['email']; ?>" class="form-label">Deposit Amount</label>
                                            <input type="number" class="form-control" id="amount<?php echo $row['email']; ?>" name="amount" placeholder="Enter amount" required>
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                        <button type="submit" class="btn btn-primary">Submit</button>
                                    </div>
                                </form>

                        </div> <!-- end card-box -->
                    </div> 
                </div>
                    <!-- end row -->


            </div> <!-- end container-fluid-->
        </div> <!-- end contant-->
    </div>
    <!-- End Page Content-->


    
    <?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         // Get inputs from POST request
        // Get inputs from POST request
        $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
        $balance_type = $_POST['balance_type'];
        $amount = filter_var($_POST['amount'], FILTER_VALIDATE_FLOAT);
    
        // Validate inputs
        if (empty($email) || empty($balance_type) || $amount === false || $amount <= 0) {
            echo "<script>alert('Invalid input. Please check your data.'); window.history.back();</script>";
            exit;
        }
    
        // Whitelist balance types to prevent SQL injection
        $valid_balance_types = ['total_balance', 'profit_balance'];
        if (!in_array($balance_type, $valid_balance_types)) {
            echo "<script>alert('Invalid balance type.'); window.history.back();</script>";
            exit;
        }
    
        // Check if user exists
        $query_user = "SELECT * FROM users WHERE email = ?";
        $stmt = $myConn->prepare($query_user);
        if (!$stmt) {
            echo "<script>alert('Database error: " . htmlspecialchars($myConn->error) . "'); window.history.back();</script>";
            exit;
        }
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();
    
        if ($result->num_rows > 0) {
            // User found
            $query_update = "UPDATE users SET $balance_type = $balance_type + ? WHERE email = ?";
            $stmt_update = $myConn->prepare($query_update);
            if (!$stmt_update) {
                echo "<script>alert('Database error: " . htmlspecialchars($myConn->error) . "'); window.history.back();</script>";
                exit;
            }
            $stmt_update->bind_param("ds", $amount, $email);
    
            if ($stmt_update->execute()) {
                // Success alert
                echo "<script>alert('Balance updated successfully.'); window.location.href='users.php';</script>";
            } else {
                echo "<script>alert('Error updating balance: " . htmlspecialchars($stmt_update->error) . "'); window.history.back();</script>";
            }
        } else {
            echo "<script>alert('User not found.'); window.history.back();</script>";
        }
    }
    ?>


   <!-- Footer Start -->
                <footer class="footer">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12 text-center">
                                  <script>document.write(new Date().getFullYear())</script> ©  <?=$sitename?>
                            </div>
                        </div>
                    </div>
                </footer>
                <!-- end Footer -->

            </div>

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


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

       

        <!-- Right bar overlay-->
        <div class="rightbar-overlay"></div>

        <!-- Vendor js -->
        <script src="assets/js/vendor.min.js"></script>

        <!-- datatable js -->
        <script src="assets/libs/datatables/jquery.dataTables.min.js"></script>
        <script src="assets/libs/datatables/dataTables.bootstrap4.min.js"></script>
        <script src="assets/libs/datatables/dataTables.responsive.min.js"></script>
        <script src="assets/libs/datatables/responsive.bootstrap4.min.js"></script>
        
        <script src="assets/libs/datatables/dataTables.buttons.min.js"></script>
        <script src="assets/libs/datatables/buttons.bootstrap4.min.js"></script>
        <script src="assets/libs/datatables/buttons.html5.min.js"></script>
        <script src="assets/libs/datatables/buttons.flash.min.js"></script>
        <script src="assets/libs/datatables/buttons.print.min.js"></script>

        <script src="assets/libs/datatables/dataTables.keyTable.min.js"></script>
        <script src="assets/libs/datatables/dataTables.select.min.js"></script>

        <!-- Datatables init -->
        <script src="assets/js/pages/datatables.init.js"></script>

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


<?php } else {
    header("location:login.php");
    exit;
}?>