<?php 
include('connection.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">Edit Trader</a></li>
                        <li class="breadcrumb-item active">Edit Trader</li>
                    </ol>
                    <h4 class="page-title">Edit Trader</h4>
                </div>
                <!-- End page title box -->

           <?php

// Check if trader ID is passed in the URL (e.g., trader_id=123)
if (isset($_GET['id'])) {
    $trader_id = $_GET['id'];

    // SQL query to retrieve trader data
    $query = "SELECT * FROM traders WHERE id = ?";
    
    // Prepare and execute the query
    if ($stmt = $myConn->prepare($query)) {
        $stmt->bind_param("i", $trader_id); // 'i' for integer
        $stmt->execute();
        $result = $stmt->get_result();

        // Fetch the trader's data
        if ($row = $result->fetch_assoc()) {
            $name = $row['name'];
            $username = $row['username'];
            $gain_percentage = $row['gain_percentage'];
            $risk_level = $row['risk_level'];
            $trades = $row['trades'];
            $investment_capital = $row['investment_capital'];
            $avg_trade_time = $row['avg_trade_time'];
            $copiers = $row['copiers'];
            $avatar = $row['avatar'];
        } else {
            echo "Trader not found.";
            exit;
        }

        // Close the statement
        $stmt->close();
    } else {
        echo "Error preparing the query: " . $myConn->error;
        exit;
    }
} else {
    echo "Trader ID is missing.";
    exit;
}

// Handling form submission for updating trader information
if (isset($_POST['update'])) {
    // Get form data
    $name = $_POST['name'];
    $username = $_POST['username'];
    $gain_percentage = $_POST['gain_percentage'];
    $risk_level = $_POST['risk_level'];
    $trades = $_POST['trades'];
    $investment_capital = $_POST['investment_capital'];
    $avg_trade_time = $_POST['avg_trade_time'];
    $copiers = $_POST['copiers'];
    
    // Handle file upload for avatar
    $avatar = $avatar;  // Keep current avatar if no new file is uploaded
    if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
        // Define upload directory and file name
        $upload_dir = "../app/assets/images/currency/";
        $file_name = basename($_FILES['avatar']['name']);
        $upload_file = $upload_dir . $file_name;
        
        // Move the uploaded file to the directory
        if (move_uploaded_file($_FILES['avatar']['tmp_name'], $upload_file)) {
            $avatar = $file_name;
        } else {
            echo "<script>alert('Failed to upload avatar image.');</script>";
        }
    }

    // SQL query to update trader information
    $update_query = "UPDATE traders 
                     SET name = ?, username = ?, gain_percentage = ?, risk_level = ?, trades = ?, 
                         investment_capital = ?, avg_trade_time = ?, copiers = ?, avatar = ? 
                     WHERE id = ?";
                     
    if ($stmt_update = $myConn->prepare($update_query)) {
        $stmt_update->bind_param("ssdiidissi", $name, $username, $gain_percentage, $risk_level, $trades, 
                                  $investment_capital, $avg_trade_time, $copiers, $avatar, $trader_id);
        if ($stmt_update->execute()) {
            echo "<script>alert('Trader information updated successfully.');</script>";
        } else {
            echo "<script>alert('Error updating trader information.');</script>";
        }
        $stmt_update->close();
    } else {
        echo "<script>alert('Error preparing update query: " . $myConn->error . "');</script>";
    }
}
?>

<!-- end row -->
<div class="row">
    <div class="col-md-12">
        <div class="card-box">
            <form action="" method="POST" enctype="multipart/form-data">
                <div class="form-row">
                    <!-- Name Field -->
                    <div class="form-group col-md-4 col-12">
                        <label for="name">Name:</label>
                        <input type="text" class="form-control" id="name" name="name" value="<?php echo $name; ?>" required>
                    </div>

                    <!-- Username Field -->
                    <div class="form-group col-md-4 col-12">
                        <label for="username">Username:</label>
                        <input type="text" class="form-control" id="username" name="username" value="<?php echo $username; ?>" required>
                    </div>

                    <!-- Gain Percentage Field -->
                    <div class="form-group col-md-4 col-12">
                        <label for="gain_percentage">Gain Percentage:</label>
                        <input type="number" class="form-control" id="gain_percentage" name="gain_percentage" step="0.1" value="<?php echo $gain_percentage; ?>" required>
                    </div>

                    <!-- Risk Level Field -->
                    <div class="form-group col-md-4 col-12">
                        <label for="risk_level">Risk Level:</label>
                        <input type="number" class="form-control" id="risk_level" name="risk_level" value="<?php echo $risk_level; ?>" required>
                    </div>

                    <!-- Total Trades Field -->
                    <div class="form-group col-md-4 col-12">
                        <label for="trades">Total Trades:</label>
                        <input type="number" class="form-control" id="trades" name="trades" value="<?php echo $trades; ?>" required>
                    </div>

                    <!-- Investment Capital Field -->
                    <div class="form-group col-md-4 col-12">
                        <label for="investment_capital">Investment Capital:</label>
                        <input type="number" class="form-control" id="investment_capital" name="investment_capital" value="<?php echo $investment_capital; ?>" required>
                    </div>

                    <!-- Average Trade Time Field -->
                    <div class="form-group col-md-4 col-12">
                        <label for="avg_trade_time">Average Trade Time (in minutes):</label>
                        <input type="number" class="form-control" id="avg_trade_time" name="avg_trade_time" value="<?php echo $avg_trade_time; ?>" required>
                    </div>

                    <!-- Copiers Field -->
                    <div class="form-group col-md-4 col-12">
                        <label for="copiers">Number of Copiers:</label>
                        <input type="number" class="form-control" id="copiers" name="copiers" value="<?php echo $copiers; ?>" required>
                    </div>

                    <!-- Avatar Field (Image upload) -->
                    <div class="form-group col-md-4 col-12">
                        <label for="avatar">Avatar Image:</label>
                        <input type="file" class="form-control" id="avatar" name="avatar" accept="image/*">
                        <?php
                        if ($avatar) {
                            echo "<img src='../app/assets/images/currency/$avatar' width='100' height='100' alt='Avatar'>";
                        }
                        ?>
                    </div>

                    <!-- Submit Button -->
                    <div class="form-group col-md-12 col-12">
                        <button type="submit" name="update" class="btn btn-primary btn-block">Update</button>
                    </div>
                </div>
            </form>
        </div> <!-- end card-box -->
    </div> <!-- end col -->
</div>
<!-- end row -->



            </div> <!-- end container-fluid-->
        </div> <!-- end contant-->
    </div>
    <!-- End Page Content-->
<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>
