<?php
/*******************************************************
 * change_user_leverage_bulk.php
 *
 * Bulk update leverage for MT5 users (by trade_id):
 *  1) Reads trade_ids from liveaccount table
 *  2) For each selected trade_id:
 *       - MT5: UserGet -> set Leverage -> UserUpdate("", pass2ndArgFix)
 *       - DB : UPDATE liveaccount SET leverage = ?
 *
 * Security:
 *  - Requires login via auth_guard.php
 *  - CSRF token required for POST
 *******************************************************/

declare(strict_types=1);
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);

/* -------- 0) Session & Guards -------- */


require_once __DIR__ . '/auth_guard.php';   // must define your auth check
require_once __DIR__ . '/config.php';       // must set $conn = new PDO(...)
require_once __DIR__ . '/manager_initialize.php'; // must set $api (MTWebAPI connected)

/* --- Ensure PDO available --- */
if (!isset($conn) || !($conn instanceof PDO)) {
  http_response_code(500);
  die('Database connection not established. Check config.php (PDO).');
}

/* --- Tiny helpers --- */
function csrf_token(): string {
  if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
  }
  return $_SESSION['csrf_token'];
}
function csrf_check(string $tokenFromPost): void {
  if (empty($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $tokenFromPost)) {
    http_response_code(400);
    die('Security check failed (CSRF).');
  }
}
function rows(PDO $conn, string $sql, array $params = []): array {
  $st = $conn->prepare($sql);
  if (!$st->execute($params)) return [];
  return $st->fetchAll(PDO::FETCH_ASSOC);
}
function execUpdate(PDO $conn, string $sql, array $params = []): bool {
  $st = $conn->prepare($sql);
  return $st->execute($params);
}

/* -------- 1) Handle API POST (bulk update) -------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['api'] ?? '') === 'bulk_update') {
  header('Content-Type: application/json; charset=utf-8');

  csrf_check($_POST['csrf'] ?? '');

  $newLev     = isset($_POST['leverage']) ? (int)$_POST['leverage'] : 0;
  $tradeIds   = isset($_POST['trade_ids']) && is_array($_POST['trade_ids']) ? $_POST['trade_ids'] : [];
  $applyAll   = isset($_POST['apply_all']) && $_POST['apply_all'] === '1';

  if ($newLev <= 0) {
    echo json_encode(['ok' => false, 'error' => 'Invalid leverage']);
    exit;
  }

  // If "apply all" was chosen, load all trade_ids
  if ($applyAll) {
    $all = rows($conn, "SELECT trade_id FROM liveaccount WHERE trade_id IS NOT NULL AND trade_id<>'' ORDER BY trade_id ASC");
    $tradeIds = array_values(array_unique(array_map(fn($r) => (string)$r['trade_id'], $all)));
  }

  // Basic sanity
  $tradeIds = array_values(array_filter(array_map('trim', $tradeIds), fn($v) => $v !== ''));
  if (empty($tradeIds)) {
    echo json_encode(['ok' => false, 'error' => 'No trade_id selected']);
    exit;
  }

  // results
  $done = [];
  $fail = [];

  foreach ($tradeIds as $login) {
    $loginInt = (int)$login;
    if ($loginInt <= 0) {
      $fail[] = ['trade_id' => $login, 'why' => 'Invalid trade_id'];
      continue;
    }

    // 1) MT5: Get user
    $user = null;
    $rc = $api->UserGet($loginInt, $user);
    if ($rc != MTRetCode::MT_RET_OK || $user === null) {
      $fail[] = ['trade_id' => $login, 'why' => "MT5 user/get failed. retcode=$rc"];
      continue;
    }

    // 2) Set leverage
    // Library expects property "Leverage" (titlecase) in MT5 SDKs
    $user->Leverage = $newLev;

    // 3) Update in MT5
    // NOTE: Your SDK expects TWO arguments (you saw that error earlier).
    // Pass empty string as second arg when not changing password.
    $rc2 = $api->UserUpdate($user, "");
    if ($rc2 != MTRetCode::MT_RET_OK) {
      $fail[] = ['trade_id' => $login, 'why' => "MT5 user/update failed. retcode=$rc2"];
      continue;
    }

    // 4) Update in DB only after MT5 success
    $ok = execUpdate(
      $conn,
      "UPDATE liveaccount SET leverage = :lev WHERE trade_id = :tid",
      [':lev' => $newLev, ':tid' => $login]
    );

    if ($ok) {
      $done[] = ['trade_id' => $login, 'leverage' => $newLev];
    } else {
      // If DB fails, you may *optionally* revert MT5 here.
      $fail[] = ['trade_id' => $login, 'why' => 'DB update failed'];
    }
  }

  echo json_encode([
    'ok'   => empty($fail),
    'done' => $done,
    'fail' => $fail
  ]);
  exit;
}

/* -------- 2) GET: Render page -------- */

// Fetch a small page of accounts to display (you can change limits / add search)
$accounts = rows(
  $conn,
  "SELECT email, trade_id, leverage, account_type, account_name
   FROM liveaccount
   WHERE trade_id IS NOT NULL AND trade_id <> ''
   ORDER BY trade_id ASC
   LIMIT 500"
);

$token = csrf_token();
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Bulk Leverage Updater</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,'Helvetica Neue',Arial,sans-serif;background:#f6f7fb;color:#1f2937;margin:0}
    .wrap{max-width:1100px;margin:24px auto;padding:0 16px}
    .card{background:#fff;border:1px solid #e5e7eb;border-radius:14px;box-shadow:0 8px 24px rgba(0,0,0,.06)}
    .card-h{padding:16px 20px;border-bottom:1px solid #eef0f4;display:flex;gap:12px;align-items:center;justify-content:space-between}
    .card-b{padding:16px 20px}
    table{width:100%;border-collapse:collapse}
    th,td{padding:10px 8px;border-bottom:1px solid #f0f2f7;font-size:14px}
    th{text-align:left;color:#6b7280;font-weight:600}
    .actions{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
    .btn{background:#111827;color:#fff;border:none;border-radius:10px;padding:10px 14px;cursor:pointer}
    .btn:disabled{opacity:.6;cursor:not-allowed}
    .sel{padding:10px 12px;border:1px solid #d1d5db;border-radius:10px;background:#fff}
    .badge{padding:4px 8px;background:#eff6ff;border:1px solid #bfdbfe;border-radius:8px;color:#1d4ed8;font-size:12px}
    .ok{color:#065f46}
    .fail{color:#991b1b}
    .muted{color:#6b7280}
    .hr{height:1px;background:#eef0f4;margin:12px 0}
    .stack{display:flex;gap:6px;align-items:center}
  </style>
</head>
<body>
<div class="wrap">
  <div class="card">
    <div class="card-h">
      <div class="stack">
        <strong>Bulk Leverage Updater</strong>
        <span class="badge">MT5 + DB</span>
      </div>
      <form id="bulkForm" class="actions" method="post">
        <input type="hidden" name="api" value="bulk_update">
        <input type="hidden" name="csrf" value="<?php echo htmlspecialchars($token); ?>">
        <select name="leverage" class="sel" required>
          <option value="" disabled selected>Choose leverage…</option>
          <option value="50">1:50</option>
          <option value="100">1:100</option>
          <option value="200">1:200</option>
          <option value="300">1:300</option>
          <option value="400">1:400</option>
          <option value="500">1:500</option>
          <option value="1000">1:1000</option>
        </select>
        <label class="stack muted" style="gap:8px">
          <input type="checkbox" name="apply_all" value="1">
          Apply to ALL listed trade IDs
        </label>
        <button type="submit" class="btn">Update Selected</button>
      </form>
    </div>
    <div class="card-b">
      <div class="muted" style="margin-bottom:12px">Tick the accounts you want to update (or check “Apply to ALL”).</div>

      <form id="idsForm">
        <table>
          <thead>
          <tr>
            <th><input type="checkbox" id="checkAll"></th>
            <th>Trade ID</th>
            <th>Email</th>
            <th>Current Leverage</th>
            <th>Account</th>
          </tr>
          </thead>
          <tbody>
          <?php foreach ($accounts as $row): ?>
            <tr>
              <td><input type="checkbox" name="trade_ids[]" value="<?php echo htmlspecialchars($row['trade_id']); ?>"></td>
              <td><?php echo htmlspecialchars($row['trade_id']); ?></td>
              <td><?php echo htmlspecialchars($row['email']); ?></td>
              <td><?php echo htmlspecialchars($row['leverage']); ?></td>
              <td><?php echo htmlspecialchars($row['account_type'] . ' / ' . $row['account_name']); ?></td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </form>

      <div class="hr"></div>
      <div id="result"></div>
    </div>
  </div>
</div>

<script>
  // collect selected IDs into the bulkForm before submit
  const bulkForm = document.getElementById('bulkForm');
  const idsForm  = document.getElementById('idsForm');
  const resultEl = document.getElementById('result');
  const checkAll = document.getElementById('checkAll');

  checkAll?.addEventListener('change', () => {
    idsForm.querySelectorAll('input[type="checkbox"][name="trade_ids[]"]').forEach(cb => {
      cb.checked = checkAll.checked;
    });
  });

  bulkForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    resultEl.textContent = 'Updating…';
    const fd = new FormData(bulkForm);
    // append selected ids
    idsForm.querySelectorAll('input[type="checkbox"][name="trade_ids[]"]:checked').forEach(cb => {
      fd.append('trade_ids[]', cb.value);
    });

    const res = await fetch(location.href, { method: 'POST', body: fd });
    const data = await res.json().catch(()=>null);

    if (!data) {
      resultEl.innerHTML = '<p class="fail">Unexpected response.</p>';
      return;
    }
    const ok = !!data.ok;
    const done = data.done || [];
    const fail = data.fail || [];
    let html = '';
    if (done.length) {
      html += `<p class="ok"><strong>Updated in MT5 & DB:</strong> ${done.length}</p><ul>`;
      done.forEach(d => { html += `<li class="ok">#${d.trade_id} → leverage ${d.leverage}</li>`; });
      html += `</ul>`;
    }
    if (fail.length) {
      html += `<p class="fail"><strong>Failed:</strong> ${fail.length}</p><ul>`;
      fail.forEach(f => { html += `<li class="fail">#${f.trade_id || '(n/a)'} → ${f.why}</li>`; });
      html += `</ul>`;
    }
    resultEl.innerHTML = html || '<p class="ok">No changes.</p>';
  });
</script>
</body>
</html>
