<?php 
include_once ('session.php');
include 'dbconnect.php';
include_once 'class.crud.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $user_id = $_POST['user_id'] ?? null;
    $wallet_address = $_POST['wallet_address'] ?? null;
    $account_name = $_POST['account_name'] ?? null;
    $account_number = $_POST['account_number'] ?? null;
    $bank_name = $_POST['bank_name'] ?? null;
    $swift_code = $_POST['swift_code'] ?? null;
    $routing_number = $_POST['routing_number'] ?? null;

    // Validate input
    if (empty($wallet_address) && (empty($account_name) || empty($account_number) || empty($bank_name) || empty($swift_code) || empty($routing_number))) {
        $error_message = 'Enter wallet address and/or complete account information.';
    } else {
        // Check if a wallet already exists for the user
        $check_query = "SELECT id FROM user_wallets WHERE user_id = ?";
        if ($stmt = $connection->prepare($check_query)) {
            $stmt->bind_param('i', $user_id);
            $stmt->execute();
            $stmt->store_result();

            if ($stmt->num_rows > 0) {
                // Wallet exists, perform an UPDATE
                $update_query = "
                    UPDATE user_wallets 
                    SET wallet_address = ?, account_name = ?, account_number = ?, bank_name = ?, swift_code = ?, routing_number = ?
                    WHERE user_id = ?";
                if ($update_stmt = $connection->prepare($update_query)) {
                    $update_stmt->bind_param(
                        'ssssssi',
                        $wallet_address, $account_name, $account_number, $bank_name, $swift_code, $routing_number, $user_id
                    );
                    if ($update_stmt->execute()) {
                        $success_message = "Wallet or account details updated successfully.";
                    } else {
                        $error_message = "Failed to update wallet or account details.";
                    }
                    $update_stmt->close();
                } else {
                    $error_message = "Database error: Unable to prepare the update query.";
                }
            } else {
                // Wallet does not exist, perform an INSERT
                $insert_query = "
                    INSERT INTO user_wallets (user_id, wallet_address, account_name, account_number, bank_name, swift_code, routing_number)
                    VALUES (?, ?, ?, ?, ?, ?, ?)";
                if ($insert_stmt = $connection->prepare($insert_query)) {
                    $insert_stmt->bind_param(
                        'issssss',
                        $user_id, $wallet_address, $account_name, $account_number, $bank_name, $swift_code, $routing_number
                    );
                    if ($insert_stmt->execute()) {
                        $success_message = "Wallet or account details added successfully.";
                    } else {
                        $error_message = "Failed to add wallet or account details.";
                    }
                    $insert_stmt->close();
                } else {
                    $error_message = "Database error: Unable to prepare the insert query.";
                }
            }
            $stmt->close();
        } else {
            $error_message = "Database error: Unable to prepare the check query.";
        }
    }
}

// Fetch all users for the dropdown
$users_query = "SELECT id, uname FROM account";
$users_result = $connection->query($users_query);
if (!$users_result) {
    $error_message = "Failed to fetch users: " . $connection->error;
}

?>
       <?php include 'headeradmin.php'; ?>
 

 <!---begin of Mobile View Here   only from Domain Team-->
 
       <?php include 'menu.php'; ?>
  
  <!---End of Mobile View Here   only from Domain Team-->
  
 
     
     
     
  
    <div class="container-fluid mt--7">
     <!-- Table -->
      <div class="row">
        <div class="col">
          <div class="card shadow" >
            <div class="card-header border-0">
              <h3 class="mb-0"><a href=""   class="btn btn-danger">ADD USER WALLET/ACCOUNT DETAILS</a></h3>
            </div>
          
           <div class="card-body">

                
               <div class="container-fluid">

 	
                	<form method='post'>
                        <h5 style="color:black;">
                            Select a user to fetch and update their account details, wallet address, or bank information.
                        </h5>
                        <hr>
                         <div class="pl-lg-2">
                            <?php if (isset($success_message)) echo "<p style='color: green;'>$success_message</p>"; ?>
                            <?php if (isset($error_message)) echo "<p style='color: red;'>$error_message</p>"; ?><br>
                    
                            <!-- User Selection -->
                            <div class="row">
                                <div class="col-lg-6">
                                    <div class="form-group">
                                        <label for="user_id">Select User:</label>
                                        <select id="user_id" class="form-control input-sm validate[required]" name="user_id" required>
                                            <option value="">--Select User--</option>
                                            <?php while ($row = $users_result->fetch_assoc()): ?>
                                                <option value="<?= $row['id']; ?>"><?= $row['uname']; ?></option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                    
                            <!-- Wallet/Bank Details (To Be Fetched Asynchronously) -->
                            <div id="user-details" style="display:none;">
                                <div class="row">
                                    <div class="col-lg-6">
                                        <div class="form-group">
                                            <label for="wallet_address">Wallet Address:</label>
                                            <input type="text" id="wallet_address" class="form-control" name="wallet_address" placeholder="Enter wallet address">
                                        </div>
                                    </div>
                                    <div class="col-lg-6">
                                        <div class="form-group">
                                            <label for="account_name">Account Name:</label>
                                            <input type="text" id="account_name" class="form-control" name="account_name" placeholder="Enter account name">
                                        </div>
                                    </div>
                                </div>
                    
                                <div class="row">
                                    <div class="col-lg-6">
                                        <div class="form-group">
                                            <label for="account_number">Account Number:</label>
                                            <input type="text" id="account_number" class="form-control" name="account_number" placeholder="Enter account number">
                                        </div>
                                    </div>
                                    <div class="col-lg-6">
                                        <div class="form-group">
                                            <label for="bank_name">Bank Name:</label>
                                            <input type="text" id="bank_name" class="form-control" name="bank_name" placeholder="Enter bank name">
                                        </div>
                                    </div>
                                </div>
                    
                                <div class="row">
                                    <div class="col-lg-6">
                                        <div class="form-group">
                                            <label for="swift_code">SWIFT Code:</label>
                                            <input type="text" id="swift_code" class="form-control" name="swift_code" placeholder="Enter SWIFT code">
                                        </div>
                                    </div>
                                    <div class="col-lg-6">
                                        <div class="form-group">
                                            <label for="routing_number">Routing Number:</label>
                                            <input type="text" id="routing_number" class="form-control" name="routing_number" placeholder="Enter routing number">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                         
                 
                        <table>
                            <td colspan="2">
                            <button type="submit" class="btn btn-primary" name="btn-save">
                    		<span class="glyphicon glyphicon-plus"></span> Save Details
                			</button>  
                            <a href="index.php" class="btn btn-large btn-success"><i class="glyphicon glyphicon-backward"></i> &nbsp; Back to Main Menu</a>
                            </td>
                        </table>
                </form>
                </div>
          </div>
        </div>
      </div>
     </div>
 
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
       <script>
        $(document).ready(function () {
            $('#user_id').change(function () {
                var userId = $(this).val();
                const userDetailsSection = document.getElementById("user-details");
                if (userId) {
                    // Fetch wallet details via AJAX
                    $.ajax({
                        url: 'fetch_wallet.php',
                        type: 'GET',
                        data: { user_id: userId },
                        success: function (data) {
                            data = JSON.parse(data)
                            userDetailsSection.style.display = "block";
                            $('#wallet_address').val(data.wallet_address || '');
                            $('#account_name').val(data.account_name || '');
                            $('#account_number').val(data.account_number || '');
                            $('#bank_name').val(data.bank_name || '');
                            $('#swift_code').val(data.swift_code || '');
                            $('#routing_number').val(data.routing_number || '');
                        },
                        error: function () {
                            alert('Failed to fetch wallet details.');
                        }
                    });
                } else {
                    userDetailsSection.style.display = "none";
                    // Clear input fields if no user is selected
                    $('#wallet_address, #account_name, #account_number, #bank_name, #swift_code, #routing_number').val('');
                }
            });
        });
    </script>
       <?php include 'foot.php'; ?>