<?php
session_start();
error_reporting(0);
include('config.php');

if (isset($_POST['update'])) {
    $did             = intval($_GET['id']);
    $email           = $_GET['email'];
    $withdraw_amount = $_GET['withdraw'];
    $description     = $_POST['description'];
    $transaction_id  = $_POST['transaction_id'];
    $status          = $_POST['status'];

    // Update wallet_withdraw
    $sql = "UPDATE wallet_withdraw 
               SET transaction_id = :transaction_id, 
                   AdminRemark    = :description, 
                   Status         = :status 
             WHERE id = :did";
    $query = $conn->prepare($sql);
    $query->bindValue(':transaction_id', $transaction_id, PDO::PARAM_STR);
    $query->bindValue(':description',     $description,    PDO::PARAM_STR);
    $query->bindValue(':status',          $status,         PDO::PARAM_INT);
    $query->bindValue(':did',             $did,            PDO::PARAM_INT);
    $query->execute();

    // If status is approved, update total_balance
    if ($status == 1) {
        $sql = "INSERT INTO total_balance (email, withdraw_amount) 
                VALUES (:email, :withdraw_amount)";
        $query = $conn->prepare($sql);
        $query->bindValue(':email',           $email,           PDO::PARAM_STR);
        $query->bindValue(':withdraw_amount', $withdraw_amount, PDO::PARAM_STR);
        $query->execute();
    }

    $trade_id = $_POST['tradeid'];
    define("PATH_TO_SCRIPTS", "mt5_api/");
    include PATH_TO_SCRIPTS . "mt5_api.php";

    define('T_QUOTES', 'EURUSD,GBPUSD,USDJPY,AUDUSD,USDCAD');
   define("MT5_SERVER_IP", "access.tgshost.org");
define("MT5_SERVER_PORT", "26043");
define("MT5_SERVER_WEB_LOGIN", "7020");
define("MT5_SERVER_WEB_PASSWORD", "Aa@123456");

    define("MT5_CRYPT_PROTOCOL", true);
    define("IS_WRITE_DEBUG_LOG", true);
    define("MT5_CONNECTION_TIMEOUT", 3);
    define("PATH_TO_LOGS", "./logs");
    define("AGENT", "WebAPITesterArt");

    $api = new MTWebAPI(AGENT, PATH_TO_LOGS, MT5_CRYPT_PROTOCOL);
    $api->SetLoggerWriteDebug(IS_WRITE_DEBUG_LOG);

    // mt5 manager connection
    if (($error_code = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, MT5_CONNECTION_TIMEOUT, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD)) != MTRetCode::MT_RET_OK) {
        echo "<script>alert('Invalid Details');</script>";
        exit;
    }

    // Get user account details (optional validation)
    $login = $trade_id;
    if (($error_code = $api->UserAccountGet($login, $account)) != MTRetCode::MT_RET_OK) {
        echo "Error: " . $api->GetError($error_code);
        exit;
    }

    if ($status == 1) {
        // Approved ⇒ deduct on MT5
        $comment = "Withdrawal";
        $type    = MTEnDealAction::DEAL_BALANCE;

        if (($error_code = $api->UserDepositChange($login, -$withdraw_amount, $comment, $type)) != MTRetCode::MT_RET_OK) {
            echo "Error making deduction: " . $error_code;
            exit;
        }

        // Success alert ONLY when approved
        echo "<script>alert('Client Wallet Withdraw Updated Successfully'); window.location.href='view_withdrawal.php?id={$did}';</script>";
        exit;

    } elseif ($status == 2) {
        // Declined
        echo "<script>alert('Withdrawal Declined successfully.'); window.location.href='view_withdrawal.php?id={$did}';</script>";
        exit;

    } else {
        // Pending/other
        echo "<script>alert('Withdrawal status updated.'); window.location.href='view_withdrawal.php?id={$did}';</script>";
        exit;
    }
}

// (No trailing else here anymore)

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Wallet Withdraw Details</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Tailwind (kept as you had) -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- Font Awesome (kept as you had) -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">

  <!-- Bootstrap 4.6 CSS for modal -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.2/css/bootstrap.min.css"/>

  <style>
    /* Modern Base Styles */
    body {
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
        background-color: #f5f7fa;
        color: #2d3748;
        line-height: 1.6;
    }
    /* Glassmorphism Card Effect */
    .card {
        background: rgba(255, 255, 255, 0.85);
        backdrop-filter: blur(12px);
        -webkit-backdrop-filter: blur(12px);
        border-radius: 16px;
        border: 1px solid rgba(255, 255, 255, 0.2);
        box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.1);
        margin-bottom: 25px;
        transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.1);
        overflow: hidden;
    }
    .card:hover { transform: translateY(-5px); box-shadow: 0 12px 40px 0 rgba(31,38,135,0.15); }
    .card-header { background: linear-gradient(135deg,#667eea 0%,#764ba2 100%); color: #fff; padding: 18px 25px; border-bottom: none; }
    .card-body { padding: 25px; }

    /* Badges */
    .badge { display:inline-block; padding:.45em .85em; font-size:.75em; font-weight:700; border-radius:50px; text-transform:uppercase; letter-spacing:.5px; }
    .badge-success { background: linear-gradient(135deg,#0cebeb 0%,#20e3b2 50%,#29ffc6 100%); color:#111; }
    .badge-danger { background: linear-gradient(135deg,#ff416c 0%,#ff4b2b 100%); color:#fff; }
    .badge-primary { background: linear-gradient(135deg,#4776E6 0%,#8E54E9 100%); color:#fff; }
    .badge-warning { background: linear-gradient(135deg,#f7971e 0%,#ffd200 100%); color:#111; }

    .dashboard-summery-one { background: linear-gradient(135deg,#ffffff 0%,#f8f9fa 100%); padding:20px; border-radius:16px; box-shadow:0 8px 32px 0 rgba(31,38,135,0.05); margin-bottom:30px; border:1px solid rgba(255,255,255,0.3); }

    .btn-fill-lmd { padding:12px 28px; border-radius:50px; font-weight:600; letter-spacing:.5px; border:none; position:relative; overflow:hidden; z-index:1; }
    .btn-fill-lmd:before { content:''; position:absolute; top:0; left:0; width:0; height:100%; background-color:rgba(255,255,255,.2); transition:all .3s; z-index:-1; }
    .btn-fill-lmd:hover:before { width:100%; }
    .bg-dark-pastel-green { background:linear-gradient(135deg,#00b09b 0%,#96c93d 100%); color:#fff; }
    .bg-orange-peel { background:linear-gradient(135deg,#ff8008 0%,#ffc837 100%); color:#fff; }

    .table { width:100%; margin-bottom:1rem; color:#2d3748; border-collapse:separate; border-spacing:0; }
    .table tr { transition: all .2s ease; }
    .table tr:hover { background: rgba(102,126,234,.05); }
    .table td { padding:1rem; vertical-align:middle; border-top:1px solid rgba(0,0,0,.03); }
    .table tr:first-child td { border-top:none; }

    .section-header { position:relative; padding-bottom:15px; margin-bottom:25px; }
    .section-header h5 { display:inline-block; font-weight:700; color:#2d3748; margin:0; font-size:1.25rem; }
    .section-header h5:after { content:''; position:absolute; width:50px; height:3px; bottom:0; left:0; background: linear-gradient(135deg,#667eea 0%,#764ba2 100%); border-radius:3px; }

    .form-control { border-radius:8px; padding:12px 18px; border:1px solid rgba(0,0,0,.08); transition: all .3s; background: rgba(255,255,255,.7); }
    .form-control:focus { border-color:#667eea; box-shadow:0 0 0 3px rgba(102,126,234,.2); }
    textarea.form-control { min-height:120px; }

    .action-btn { background: linear-gradient(135deg,#667eea 0%,#764ba2 100%); color:#fff; border:none; padding:12px 30px; border-radius:50px; font-weight:600; letter-spacing:.5px; transition: all .4s; position:relative; overflow:hidden; box-shadow:0 4px 15px rgba(102,126,234,.3); }
    .action-btn:hover { transform: translateY(-3px); box-shadow:0 8px 25px rgba(102,126,234,.4); }

    @media (max-width: 768px) {
        .card { margin-bottom: 15px; }
        .card-body { padding: 15px; }
        .btn-fill-lmd { padding: 10px 20px; font-size: 14px; }
        .table td { padding: .75rem; font-size: 14px; }
        .dashboard-summery-one { padding: 15px; }
    }

    /* Make modal appear just below header */
    .modal-dialog {
        /* Adjust this to your header height (e.g., 64px header + 16px gap) */
        margin: 80px auto 1.75rem auto; 
    }
    /* Ensure modal sits above any fixed sidebar/header */
    .modal { z-index: 1060; }
    .modal-backdrop { z-index: 1055; }
    /* Mobile-friendly modal */
@media (max-width: 576px) {
  .modal-dialog {
    margin: 60px auto;         /* still below header */
    max-width: 95% !important; /* take almost full width */
  }
  .modal-content {
    border-radius: 12px;
  }
  .modal-body .form-control {
    width: 50%;   height:60px;            /* make inputs full width */
    font-size: 14px;
  }
  .modal-footer {
    flex-direction: column;    /* stack buttons on small screens */
    gap: 10px;
  }
  .modal-footer .btn {
    width: 100%;               /* buttons stretch full width */
  }
}

  </style>
</head>

<body class="bg-gray-100">
<?php include('header.php'); ?>
<div class="flex flex-col md:flex-row h-screen">
  <?php include "side_bar.php"; ?>

  <main class="flex-1 p-4 md:p-6 md:ml-64">
    <br>
    <div class="row gutters-20">
      <div class="col-xl-12 col-sm-12 col-12">
        <div class="dashboard-summery-one mg-b-20">
          <div class="row align-items-center">
            <div class="col-6">
              <button type="button" class="btn-fill-lmd radius-30 text-light shadow-dark-pastel-green bg-dark-pastel-green">Wallet Withdraw Details</button>
            </div>
            <div class="col-6 text-right">
              <a href="wallet_withdraw.php" class="btn-fill-lmd radius-30 text-light shadow-dodger-blue bg-orange-peel">Get Back</a>
            </div>
          </div>
        </div>
      </div>
    </div>

<?php
$id = intval($_GET['id']);
$sql = "SELECT * FROM wallet_withdraw WHERE id = :id LIMIT 1";
$query = $conn->prepare($sql);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$record = $query->fetch(PDO::FETCH_OBJ);
?>

<?php if ($record): ?>
  <div class="row">
    <!-- Left: Withdraw Details -->
    <div class="col-md-7">
      <div class="card">
        <div class="card-body">
          <div class="row" style="margin-top:-18px;">
            <div class="col-md-12" style="box-shadow:0 4px 8px rgba(0,0,0,0.2); padding-top:20px; border:1px solid #9ccc65; background-color:#ecf0f57a;">
              <h5><b>1. Withdraw Details</b></h5>
            </div>
          </div>
          <br>
          <div class="table-responsive">
            <table class="table table-sm mb-0">
              <tbody>
                <tr><td>Email</td><td> : &nbsp;<?php echo htmlentities($record->email); ?></td></tr>
                <tr><td>Trading Account</td><td> : &nbsp;<?php echo htmlentities($record->trade_id); ?></td></tr>
                <tr><td>Amount</td><td> : &nbsp;$<?php echo htmlentities($record->withdraw_amount); ?></td></tr>
                <tr><td>Method</td><td> : &nbsp;<?php echo htmlentities($record->withdraw_type); ?></td></tr>
                <tr><td>Client Bank</td><td> : &nbsp;<?php echo htmlentities($record->client_bank); ?></td></tr>
                <tr><td>Account Number</td><td> : &nbsp;<?php echo htmlentities($record->account_number); ?></td></tr>
                <tr><td>IFSC Code</td><td> : &nbsp;<?php echo htmlentities($record->ifsc); ?></td></tr>
                <tr>
                  <td>Reference ID</td>
                  <td> : &nbsp;<?php echo ($record->transaction_id == "") ? "waiting for Approval" : htmlentities($record->transaction_id); ?></td>
                </tr>
              </tbody>
            </table>
          </div>
          <br>
        </div>
      </div>
    </div>

    <!-- Right: Withdraw Status -->
    <div class="col-md-5">
      <div class="card">
        <div class="card-body">
          <div class="row" style="margin-top:-18px;">
            <div class="col-md-12" style="box-shadow:0 4px 8px rgba(0,0,0,0.2); padding-top:20px; border:1px solid #9ccc65; background-color:#ecf0f57a;">
              <h5><b>2. Withdraw Status</b></h5>
            </div>
          </div>
          <br>
          <div class="table-responsive">
            <table class="table table-sm mb-0">
              <tbody>
                <tr>
                  <td>Withdraw Date</td>
                  <td> : &nbsp;<?php echo htmlentities($record->withdraw_date); ?></td>
                </tr>
                <tr>
                  <td>Withdraw Status</td>
                  <td> : &nbsp;
                    <?php
                      $stats = (int)$record->Status;
                      if ($stats === 1) {
                        echo '<div class="badge badge-success badge-pill">Approved</div>';
                      } elseif ($stats === 2) {
                        echo '<div class="badge badge-primary badge-pill">Not Approved</div>';
                      } else {
                        echo '<div class="badge badge-danger badge-pill">waiting for approval</div>';
                      }
                    ?>
                  </td>
                </tr>
                <tr>
                  <td>Admin Remark</td>
                  <td> : &nbsp;<?php echo ($record->AdminRemark == "") ? "waiting for Approval" : htmlentities($record->AdminRemark); ?></td>
                </tr>
                <tr>
                  <td>Admin Action Taken</td>
                  <td> : &nbsp;<?php echo ($record->Js_Admin_Remark_Date == "") ? "NA" : htmlentities($record->Js_Admin_Remark_Date); ?></td>
                </tr>

                <?php if ($stats === 0): ?>
                <tr>
                  <td colspan="2" class="text-center">
                    <br>
                    <!-- Trigger button ONLY -->
                    <button type="button"
                            class="btn btn-primary"
                            data-toggle="modal"
                            data-target="#takeActionModal"
                            style="width:200px; font-size:16px;">
                      Take&nbsp;Action
                    </button>
                  </td>
                </tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
          <br><br>
        </div>
      </div>
    </div>
  </div>
<?php endif; ?>
  </main>
</div>

<!-- ===================== MODAL (OUTSIDE TABLE) ===================== -->
<div id="takeActionModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title mb-0">Wallet Withdraw – Take Action</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>
      </div>
      <form name="adminaction" method="post">
        <div class="modal-body">
          <div class="form-group">
            <label class="form-control-label" style="color:#ed1c24;">Wallet Deposit Take Action:</label>
            <select name="status" class="form-control" required>
              <option value="">Choose your option</option>
              <option value="1">Approved</option>
              <option value="2">Not Approved</option>
            </select>
          </div>
          <div class="form-group">
            <label class="form-control-label" style="color:#ed1c24;">Withdraw Reference ID:</label>
            <input type="text" class="form-control" name="transaction_id" required>
          </div>
          <div class="form-group">
            <label class="form-control-label" style="color:#ed1c24;">Description:</label>
            <textarea class="form-control" name="description" required></textarea>
          </div>
          <input type="hidden" name="tradeid" value="<?php echo isset($record->trade_id) ? htmlentities($record->trade_id) : ''; ?>">
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-primary" name="update">Update</button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        </div>
      </form>
    </div>
  </div>
</div>
<!-- ===================== /MODAL ===================== -->

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

<!-- jQuery + Popper + Bootstrap JS (for modal) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.2/js/bootstrap.min.js"></script>
</body>
</html>
