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

<div id="wrapper">
    <!-- 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="Transaction.php">Transaction</a></li>
                        <li class="breadcrumb-item active">Approve Transaction</li>
                    </ol>
                    <h4 class="page-title">Approve Transaction</h4>
                </div>
                <!-- End page title box -->
                    <?php
                    // Get transaction ID from the URL
                    $trx_id = $_GET['transaction_id'];
                    
                    // SQL query to get transaction details
                    $query_history = "
                        SELECT 
                            t.id, 
                            t.trx_id, 
                            t.user_id, 
                            t.amount, 
                            t.currency, 
                            t.rate, 
                            t.gateway, 
                            t.type, 
                            t.status, 
                            t.created_at, 
                            t.updated_at
                        FROM 
                            transactions t 
                        WHERE 
                            t.trx_id = ?
                    ";
                    
                    // Prepare and execute the query for transaction details
                    if ($stmt = $myConn->prepare($query_history)) {
                        $stmt->bind_param("s", $trx_id);  // Use 's' for string (assuming trx_id is a string)
                        $stmt->execute();
                        $result = $stmt->get_result();
                    
                        if ($row = $result->fetch_assoc()) {
                            $id = $row["id"];
                            $transaction_id = $row["trx_id"];
                            $user_id = $row["user_id"];
                            $amount = $row["amount"];
                            $type = $row["type"];
                            $currency = $row["currency"];
                            $rate = $row["rate"];
                            $gateway = $row["gateway"];
                            $status = $row["status"];
                            $created_at = $row["created_at"];
                            $updated_at = $row["updated_at"];
                        } else {
                            echo "Transaction not found.";
                            exit;
                        }
                    
                        // Close the statement
                        $stmt->close();
                    } else {
                        echo "Error preparing the query: " . $myConn->error;
                    }
                    
                    // Now, get the username from the users table using the user_id
                    $query_user = "SELECT username FROM users WHERE id = ?";
                    if ($stmt_user = $myConn->prepare($query_user)) {
                        $stmt_user->bind_param("i", $user_id);  // Use 'i' for integer (assuming user_id is an integer)
                        $stmt_user->execute();
                        $result_user = $stmt_user->get_result();
                    
                        if ($row_user = $result_user->fetch_assoc()) {
                            $username = $row_user["username"];
                        } else {
                            echo "User not found.";
                            exit;
                        }
                    
                        // Close the statement
                        $stmt_user->close();
                    }
                    
                    
                    if (isset($_POST['approve'])) {
                        $amount = $_POST['amount']; 
                        $username = $_POST['username']; 
                        $transaction_id = $_POST['transaction_id']; 

                        // First, check if the transaction is already approved
                        $stmt_check = $myConn->prepare("SELECT status,type FROM transactions WHERE trx_id = ?");
                        $stmt_check->bind_param("s", $transaction_id);
                        $stmt_check->execute();
                        $stmt_check->store_result();

                        if ($stmt_check->num_rows > 0) {
                            $stmt_check->bind_result($status,$type);
                            $stmt_check->fetch();

                            if ($status === 'Completed') {
                                echo "<script>
                                        alert('This transaction has already been approved.');
                                        window.location = 'transaction.php';
                                    </script>";
                                exit;
                            }

                            if($type == "Deposit"){
                                // Proceed to update balance and mark transaction as approved
                                $stmt_update_user = $myConn->prepare("UPDATE users SET total_balance = total_balance + ? WHERE username = ?");
                                $stmt_update_user->bind_param("ds", $amount, $username);

                                $stmt_update_trx = $myConn->prepare("UPDATE transactions SET status = 'Completed' WHERE trx_id = ?");
                                $stmt_update_trx->bind_param("s", $transaction_id);

                                if ($stmt_update_user->execute() && $stmt_update_trx->execute()) {
                                    echo "<script>
                                            alert('Transaction Approved');
                                            window.location = 'transaction.php';
                                        </script>";
                                } else {
                                    echo "Error approving transaction.";
                                }

                                $stmt_update_user->close();
                                $stmt_update_trx->close();
                            }else{

                                $stmt_update_trx = $myConn->prepare("UPDATE transactions SET status = 'Completed' WHERE trx_id = ?");
                                $stmt_update_trx->bind_param("s", $transaction_id);

                                if ($stmt_update_trx->execute()) {
                                    echo "<script>
                                            alert('Transaction Approved');
                                            window.location = 'transaction.php';
                                        </script>";
                                } else {
                                    echo "Error approving transaction.";
                                }
                                $stmt_update_trx->close();
                            }

                            

                        } else {
                            echo "<script>
                                    alert('Transaction not found.');
                                    window.location = 'transaction.php';
                                </script>";
                        }

                        $stmt_check->close();
                    } 
                    
                    // Handle form submission for decline
                    if (isset($_POST['decline'])) {
                        // Update the transaction status to 'Declined'
                        $result_decline = mysqli_query($myConn, "UPDATE transactions SET status = 'Failed' WHERE trx_id = '$transaction_id'");
                    
                        if ($result_decline) {
                            echo "<script>
                                    alert('Transaction Declined');
                                    window.location = 'transaction.php';
                                  </script>";
                        } else {
                            echo "Error declining transaction.";
                        }
                    }
                    ?>
                    
                    <!-- end row -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card-box">
                                <form action="" method="post">
                                    <div class="form-row">
                                        <input name="type" value="<?= $type ?>" hidden>
                                        <div class="form-group col-md-6">
                                            <label class="control-label mb-10 text-left">Transaction ID: </label>
                                            <input type="text" name="transaction_id" class="form-control" value="<?= $transaction_id ?>" readonly>
                                        </div>
                                        
                                        <div class="form-group col-md-6">
                                            <label class="control-label mb-10 text-left">Username: </label>
                                            <input type="text" name="username" class="form-control" value="<?= $username ?>" readonly>
                                        </div>
                    
                                        <div class="form-group col-md-6">
                                            <label class="control-label mb-10 text-left">Amount (USD)</label>
                                            <input type="text" name="amount" class="form-control" value="<?= $amount ?>" readonly>
                                        </div>
                    
                                        <div class="form-group col-md-6">
                                            <label class="control-label mb-10 text-left">Transaction Date: </label>
                                            <input type="text" class="form-control" value="<?= $created_at ?>" readonly>
                                        </div>
                    
                                        <div class="form-group col-md-12">
                                            <button type="submit" name="approve" class="btn btn-primary btn-block <?= $status == 'Approved' ? 'disabled' : '' ?>" >Approve</button>
                                        </div>
                    
                                        <div class="form-group col-md-12">
                                            <button type="submit" name="decline" class="btn btn-danger btn-block <?= $status == 'Declined' ? 'disabled' : '' ?>" >Decline</button>
                                        </div>
                                    </div>
                                </form>
                            </div> <!-- end card-box -->
                        </div> <!-- end col -->
                    </div>
                    <!-- end row -->




       <!-- 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>
