<?php 
session_start();
include 'header.php'; 
$msg = "";

// Database connection (assuming $link is defined in header.php)
if(!isset($link)) {
    die("Database connection not established");
}

if(isset($_POST['delete'])){
    $uid = trim($_POST['userId']);
    
    $delete_query = mysqli_query($link, "DELETE FROM orders WHERE id = '$uid'");
    if($delete_query) {
        echo '<script>alert("Order was deleted successfully");window.location.href = "trade.php" </script>';
    } else {
        echo '<script>alert("Error deleting order: '.mysqli_error($link).'");</script>';
    }
}

// Handle edit form submission
if(isset($_POST['update_order'])){
    $id = mysqli_real_escape_string($link, $_POST['id']);
    $user_id = mysqli_real_escape_string($link, $_POST['user_id']);
    $type = mysqli_real_escape_string($link, $_POST['type']);
    $mode = mysqli_real_escape_string($link, $_POST['mode']);
    $order_type = mysqli_real_escape_string($link, $_POST['order_type']);
    $price = mysqli_real_escape_string($link, $_POST['price']);
    $amount = mysqli_real_escape_string($link, $_POST['amount']);
    $leverage = mysqli_real_escape_string($link, $_POST['leverage']);
    $take_profit = mysqli_real_escape_string($link, $_POST['take_profit']);
    $stop_loss = mysqli_real_escape_string($link, $_POST['stop_loss']);
    $status = mysqli_real_escape_string($link, $_POST['status']);
    $amount_end = mysqli_real_escape_string($link, $_POST['amount_end']);
    
    // Start transaction
    mysqli_begin_transaction($link);
    
    try {
        // First update the order
        $sql = "UPDATE orders SET 
                type = '$type',
                mode = '$mode',
                order_type = '$order_type',
                price = '$price',
                amount = '$amount',
                leverage = '$leverage',
                take_profit = '$take_profit',
                stop_loss = '$stop_loss',
                status = '$status',
                amount_end = '$amount_end'
                WHERE id = '$id'";
                
        if(!mysqli_query($link, $sql)){
            throw new Exception("Error updating order: ".mysqli_error($link));
        }
        
        // Only update balance if status is 'won'
        if($status == 'won') {
            // Get the current balance of the user
            $user_query = "SELECT balance FROM users WHERE id = '$user_id'";
            $user_result = mysqli_query($link, $user_query);
            
            if(!$user_result || mysqli_num_rows($user_result) == 0) {
                throw new Exception("User not found");
            }
            
            $user_data = mysqli_fetch_assoc($user_result);
            $current_balance = $user_data['balance'];
            
            // Calculate new balance (only add for won status)
            $new_balance = $current_balance + $amount_end;
            
            // Update user balance
            $update_balance_query = "UPDATE users SET balance = '$new_balance' WHERE id = '$user_id'";
            if(!mysqli_query($link, $update_balance_query)) {
                throw new Exception("Error updating user balance: ".mysqli_error($link));
            }
        }
        
        // Commit transaction if all queries succeeded
        mysqli_commit($link);
        echo '<script>alert("Order updated successfully");window.location.href = "trade.php"</script>';
    } catch (Exception $e) {
        // Rollback transaction if any error occurred
        mysqli_rollback($link);
        echo '<script>alert("'.$e->getMessage().'");</script>';
    }
}

// Handle add new order form submission
if(isset($_POST['add_order'])){
    $user_id = mysqli_real_escape_string($link, $_POST['user_id']);
    $type = mysqli_real_escape_string($link, $_POST['type']);
    $mode = mysqli_real_escape_string($link, $_POST['mode']);
    $order_type = mysqli_real_escape_string($link, $_POST['order_type']);
    $price = mysqli_real_escape_string($link, $_POST['price']);
    $amount = mysqli_real_escape_string($link, $_POST['amount']);
    $leverage = mysqli_real_escape_string($link, $_POST['leverage']);
    $take_profit = mysqli_real_escape_string($link, $_POST['take_profit']);
    $stop_loss = mysqli_real_escape_string($link, $_POST['stop_loss']);
    $status = mysqli_real_escape_string($link, $_POST['status']);
    
    $sql = "INSERT INTO orders (user_id, type, mode, order_type, price, amount, leverage, take_profit, stop_loss, status) 
            VALUES ('$user_id', '$type', '$mode', '$order_type', '$price', '$amount', '$leverage', '$take_profit', '$stop_loss', '$status')";
            
    if(mysqli_query($link, $sql)){
        echo '<script>alert("New order added successfully");window.location.href = "trade.php"</script>';
    } else {
        echo '<script>alert("Error adding order: '.mysqli_error($link).'");</script>';
    }
}

// Get all users for the dropdown
$users_query = mysqli_query($link, "SELECT id, email FROM users");
$users = [];
while($user = mysqli_fetch_assoc($users_query)) {
    $users[$user['id']] = $user['email'];
}
?>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.jqueryui.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.6/css/buttons.jqueryui.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.6/css/buttons.bootstrap.min.css">

<script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/dataTables.jqueryui.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.jqueryui.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.html5.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.print.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.colVis.min.js"></script>

<style>
.table-responsive {
    overflow-x: hidden;
}
@media (max-width: 8000px) {
    .table-responsive {
        overflow-x: auto;
    }
}
.modal-lg {
    max-width: 800px;
}
</style>

<?php 
if ($msg != "") {
    echo "<div class='alert alert-success' style='padding:20px;background-color:#dce8f7;color:black'>$msg</div>"; 
}
?>

<div class="page-content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="card-title mb-0">Orders</h4>
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addOrderModal">
                            Add New Order
                        </button>
                    </div><!-- end card header -->

                    <div class="card-body">
                        <div id="customerList">
                            <div class="table-responsive table-card mt-3 mb-1">
                                <table id="myTable" class="table table-striped table-bordered" style="width:100%">  
                                    <thead class="table-light">
                                        <tr>
                                            <th>User</th>
                                            <th>Type</th>
                                            <th>Mode</th>
                                            <th>Order Type</th>
                                            <th>Amount</th>
                                            <th>Leverage</th>
                                            <th>Take Profit</th>
                                            <th>Stop Loss</th>
                                            <th>Status</th>
                                            <th>Created At</th>
                                            <th>Action</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>  
                                        <?php 
                                        $sql = "SELECT o.*, u.email as user_email FROM orders o LEFT JOIN users u ON o.user_id = u.id ORDER BY o.id DESC";
                                        $result = mysqli_query($link, $sql);
                                        if($result && mysqli_num_rows($result) > 0) {
                                            while($row = mysqli_fetch_assoc($result)) {  
                                        ?>
                                        <tr>
                                            <form method="post">
                                                <input type="hidden" name="userId" value="<?php echo $row['id']; ?>">
                                                <td><?php echo htmlspecialchars($row['user_email']); ?></td>
                                                <td><?php echo htmlspecialchars($row['type']); ?></td>
                                                <td><?php echo htmlspecialchars($row['mode']); ?></td>
                                                <td><?php echo htmlspecialchars($row['order_type']); ?></td>
                                                <td><?php echo htmlspecialchars($row['amount']); ?></td>
                                                <td><?php echo htmlspecialchars($row['leverage']); ?></td>
                                                <td><?php echo htmlspecialchars($row['take_profit']); ?></td>
                                                <td><?php echo htmlspecialchars($row['stop_loss']); ?></td>
                                                <td><?php echo htmlspecialchars($row['status']); ?></td>
                                                <td><?php echo htmlspecialchars($row['created_at']); ?></td>
                                                <td>
                                                    <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#editOrderModal<?php echo $row['id']; ?>">
                                                        Edit
                                                    </button>
                                                </td>
                                                <td>
                                                    <button type="submit" onclick="return confirm('Are you sure you want to delete this order?')" name="delete" class="btn btn-danger">
                                                        Delete
                                                    </button>
                                                </td>
                                            </form>
                                        </tr>

                                        <!-- Edit Order Modal for each row -->
<div class="modal fade" id="editOrderModal<?php echo $row['id']; ?>" tabindex="-1" aria-labelledby="editOrderModalLabel<?php echo $row['id']; ?>" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editOrderModalLabel<?php echo $row['id']; ?>">Edit Order</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post">
                <div class="modal-body" style="overflow-y: auto; max-height: 70vh;">
                    <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="user_id" class="form-label">User</label>
                            <select class="form-control form-control-lg" id="user_id" name="user_id" required style="width: 100%;">
                                <?php foreach($users as $id => $email): ?>
                                    <option value="<?php echo $id; ?>" <?php echo ($id == $row['user_id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($email); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="type" class="form-label">Type</label>
                            <select class="form-control form-control-lg" id="type" name="type" required style="width: 100%;">
                                <option value="buy" <?php echo ($row['type'] == 'buy') ? 'selected' : ''; ?>>Buy</option>
                                <option value="sell" <?php echo ($row['type'] == 'sell') ? 'selected' : ''; ?>>Sell</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="mode" class="form-label">Mode</label>
                            <select class="form-control form-control-lg" id="new_mode" name="mode" required style="width: 100%;">
                                <option value="live" <?php echo ($row['mode'] == 'live') ? 'selected' : ''; ?>>Live</option>
                                <option value="demo" <?php echo ($row['mode'] == 'demo') ? 'selected' : ''; ?>>Demo</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="order_type" class="form-label">Order Type</label>
                            <select class="form-control form-control-lg" id="order_type" name="order_type" required style="width: 100%;">
                                <option value="market" <?php echo ($row['order_type'] == 'market') ? 'selected' : ''; ?>>Market</option>
                                <option value="limit" <?php echo ($row['order_type'] == 'limit') ? 'selected' : ''; ?>>Limit</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label for="price" class="form-label">Price</label>
                            <input type="number" step="0.000001" class="form-control form-control-lg" id="price" name="price" 
                                   value="<?php echo htmlspecialchars($row['price']); ?>" required style="width: 100%;">
                        </div>
                        <div class="col-md-4">
                            <label for="amount" class="form-label">Amount</label>
                            <input type="number" step="0.000001" class="form-control form-control-lg" id="amount" name="amount" 
                                   value="<?php echo htmlspecialchars($row['amount']); ?>" required style="width: 100%;">
                        </div>
                        <div class="col-md-4">
                            <label for="leverage" class="form-label">Leverage</label>
                            <input type="number" class="form-control form-control-lg" id="leverage" name="leverage" 
                                   value="<?php echo htmlspecialchars($row['leverage']); ?>" style="width: 100%;">
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label for="take_profit" class="form-label">Take Profit</label>
                            <input type="number" step="0.000001" class="form-control form-control-lg" id="take_profit" name="take_profit" 
                                   value="<?php echo htmlspecialchars($row['take_profit']); ?>" style="width: 100%;">
                        </div>
                        <div class="col-md-4">
                            <label for="stop_loss" class="form-label">Stop Loss</label>
                            <input type="number" step="0.000001" class="form-control form-control-lg" id="stop_loss" name="stop_loss" 
                                   value="<?php echo htmlspecialchars($row['stop_loss']); ?>" style="width: 100%;">
                        </div>
                        <div class="col-md-4">
                            <label for="amount_end" class="form-label">Amount (Earnings/lost)</label>
                            <input type="number" step="0.000001" class="form-control form-control-lg" id="amount_end" name="amount_end" 
                                   value="<?php echo htmlspecialchars($row['amount_end']); ?>" required style="width: 100%;">
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-control form-control-lg" id="status" name="status" required style="width: 100%;">
                                <option value="won" <?php echo ($row['status'] == 'won') ? 'selected' : ''; ?>>Won</option>
                                <option value="loss" <?php echo ($row['status'] == 'loss') ? 'selected' : ''; ?>>Loss</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-lg" data-bs-dismiss="modal">Close</button>
                    <button type="submit" name="update_order" class="btn btn-primary btn-lg">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
    /* Additional CSS to ensure proper sizing */
    .modal-lg {
        max-width: 800px;
    }
    .form-control-lg {
        padding: 0.5rem 1rem;
        font-size: 1.1rem;
        min-height: calc(2.5rem + 2px);
    }
    .form-label {
        font-weight: 500;
        margin-bottom: 0.5rem;
        display: block;
    }
    .modal-body {
        padding: 1.5rem;
    }
    .btn-lg {
        padding: 0.5rem 1.5rem;
        font-size: 1.1rem;
    }
</style>
                                        <?php 
                                            }
                                        } else {
                                            echo "<tr><td colspan='13' class='text-center'>No orders found</td></tr>";
                                        }
                                        ?>
                                    </tbody>  
                                </table>
                            </div>
                        </div>
                    </div><!-- end card -->
                </div>
                <!-- end col -->
            </div>
            <!-- end col -->
        </div>
        <!-- end row -->
    </div>
</div>

<!-- Add New Order Modal -->
<div class="modal fade" id="addOrderModal" tabindex="-1" aria-labelledby="addOrderModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addOrderModalLabel">Add New Order</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="new_user_id" class="form-label">User</label>
                            <select class="form-control" id="new_user_id" name="user_id" required>
                                <?php foreach($users as $id => $email): ?>
                                    <option value="<?php echo $id; ?>"><?php echo htmlspecialchars($email); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="new_type" class="form-label">Type</label>
                            <select class="form-control" id="new_type" name="type" required>
                                <option value="buy">Buy</option>
                                <option value="sell">Sell</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="new_mode" class="form-label">Mode</label>
                                <select class="form-control" id="new_mode" name="mode" required>
                                    <option value="live">Live</option>
                                    <option value="demo">Demo</option>
                                </select>

                        </div>
                        <div class="col-md-6">
                            <label for="new_order_type" class="form-label">Order Type</label>
                            <select class="form-control" id="new_order_type" name="order_type" required>
                                <option value="market">Market</option>
                                <option value="limit">Limit</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label for="new_price" class="form-label">Price</label>
                            <input type="number" step="0.000001" class="form-control" id="new_price" name="price" required>
                        </div>
                        <div class="col-md-4">
                            <label for="new_amount" class="form-label">Amount</label>
                            <input type="number" step="0.000001" class="form-control" id="new_amount" name="amount" required>
                        </div>
                        <div class="col-md-4">
                            <label for="new_leverage" class="form-label">Leverage</label>
                            <input type="number" class="form-control" id="new_leverage" name="leverage">
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="new_take_profit" class="form-label">Take Profit</label>
                            <input type="number" step="0.000001" class="form-control" id="new_take_profit" name="take_profit">
                        </div>
                        <div class="col-md-6">
                            <label for="new_stop_loss" class="form-label">Stop Loss</label>
                            <input type="number" step="0.000001" class="form-control" id="new_stop_loss" name="stop_loss">
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="new_status" class="form-label">Status</label>
                            <select class="form-control" id="status" name="status" required>
                                <option value="won" <?php echo ($row['status'] == 'won') ? 'selected' : ''; ?>>Won</option>
                                <option value="loss" <?php echo ($row['status'] == 'loss') ? 'selected' : ''; ?>>Loss</option>
                            </select>

                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" name="add_order" class="btn btn-primary">Add Order</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function(){
    $('#myTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    });
});
</script>

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