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


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['approve'])) {

    $copyId = intval($_POST['copyId']);

    $stmtSelect = $conn->prepare("SELECT ct.*, u.email, u.username FROM copy_trades ct JOIN users u ON ct.user_id = u.id WHERE ct.id = ?");
    $stmtSelect->bind_param("i", $copyId);
    $stmtSelect->execute();
    $result = $stmtSelect->get_result();

    if ($result->num_rows === 0) {
        echo "<script>alert('Copy trade not found.');</script>";
        exit;
    }

    $row = $result->fetch_assoc();

    // Update status to Active
    $stmtUpdate = $conn->prepare("UPDATE copy_trades SET status = 'Active', start_date = ?, end_date = ? WHERE id = ?");
    $start_date = date("Y-m-d H:i:s");
    $end_date = date("Y-m-d H:i:s", strtotime("+" . $row['duration'] . " days"));
    $stmtUpdate->bind_param("ssi", $start_date, $end_date, $copyId);

    if ($stmtUpdate->execute()) {
        // Prepare and send email
        $email = $row['email'];
        $username = $row['username'];
        $subject = 'Copy Trade Now Active';
        
        $htmlMessage = '
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; background-color: #f9f9f9; }
                .container { max-width: 600px; margin: 20px auto; background: #fff; padding: 20px; border-radius: 8px; }
                .header { background-color: #015a63; color: white; padding: 15px; text-align: center; font-size: 18px; }
                .details { margin-top: 20px; font-size: 16px; color: #333; }
                .footer { margin-top: 30px; font-size: 13px; color: #777; text-align: center; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">Your Copy Trade is Now Active</div>
                <div class="details">
                    <p>Hi <strong>' . htmlspecialchars($username) . '</strong>,</p>
                    <p>You have successfully started copying <strong>' . htmlspecialchars($row['trader_name']) . '</strong>.</p>
                    <p><strong>Investment:</strong> $' . number_format($row['invest_amt'], 2) . '<br>
                    <strong>Duration:</strong> ' . $row['duration'] . ' days<br>
                    <strong>Total Expected Profit:</strong> $' . number_format($row['total_profit'], 2) . '</p>
                    <p>Your copy trade is now <strong>Active</strong> and will run from <strong>' . $start_date . '</strong> to <strong>' . $end_date . '</strong>.</p>
                </div>
                <div class="footer">
                    &copy; ' . date('Y') . ' ' . $sitename . '. All rights reserved.
                </div>
            </div>
        </body>
        </html>';

        // sendmail(to, name, subject, html)
        sendmail($email, $username, $subject, $htmlMessage);

        echo "<script>alert('Trade approved and user notified via email.'); window.location.href='copy_trade_history.php';</script>";
    } else {
        echo "<script>alert('Failed to approve trade.');</script>";
    }
}

?>

<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">Copy Trade</a></li>
                        <li class="breadcrumb-item active">Copy Trade</li>
                    </ol>
                    <h4 class="page-title">Copy Trade</h4>
                </div>
                <!-- End page title box -->
                    <?php
                    // Get transaction ID from the URL
                    $copyId = $_GET['id'];
                    
                    $sql = "SELECT ct.*, u.username FROM copy_trades ct 
                            JOIN users u ON ct.user_id = u.id 
                            WHERE ct.id = '$copyId' ";
                    $result = $conn->query($sql);
                    $result->num_rows > 0;
                    $row = $result->fetch_assoc();
                  
                    
                    
                    if (isset($_POST['approve'])) {
                        
                    } 
                    
                    ?>
                    
                    <!-- end row -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card-box">
                                <form action="" method="post">
                                    <input type="hidden" value="<?php echo $copyId ?>" name="copyId">
                                    <div class="form-row">
                                        <div class="form-group col-md-6">
                                            <label class="control-label mb-10 text-left">Trader name: </label>
                                            <input type="text" name="" class="form-control" value="<?= $row['trader_name'] ?>" 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="<?= $row['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="<?= $row['invest_amt'] ?>" 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="<?= $row['date'] ?>" readonly>
                                        </div>

                                        <div class="form-group col-md-6">
                                            <label class="control-label mb-10 text-left">Status: </label>
                                            <input type="text" class="form-control" value="<?= $row['status'] ?>" readonly>
                                        </div>
                    
                                        <div class="form-group col-md-12">
                                            <button type="submit" name="approve" class="btn btn-primary btn-block <?= $row['status'] == 'Approved' ? 'disabled' : '' ?>" >Approve</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>
