<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);
include "config.php";

/* =========================
   Helpers
========================= */
function is_strong_pwd($pwd) {
  return (bool) preg_match('/^(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/', $pwd);
}

/* CSRF */
if (empty($_SESSION['csrf_change_pwd'])) {
  $_SESSION['csrf_change_pwd'] = bin2hex(random_bytes(32));
}
$csrf  = $_SESSION['csrf_change_pwd'];
$flash = ['type'=>null,'msg'=>null];

/* =========================
   AJAX: fetch current password
========================= */
if (isset($_POST['mode']) && $_POST['mode'] === 'fetch_pwd') {
  header('Content-Type: application/json');
  $posted_csrf = $_POST['csrf'] ?? '';
  $email = trim($_POST['user_email'] ?? '');
  $tid   = trim($_POST['tradeid'] ?? '');
  $type  = $_POST['password_type'] ?? '';

  if (!hash_equals($csrf, $posted_csrf)) { echo json_encode(['ok'=>false,'msg'=>'Invalid CSRF']); exit; }
  if (!$email || !$tid || !in_array($type, ['trader','investor'], true)) { echo json_encode(['ok'=>false,'msg'=>'Missing fields']); exit; }

  $stmt = $conn->prepare("SELECT trader_pwd, invester_pwd FROM liveaccount WHERE trade_id = ? AND email = ? LIMIT 1");
  $stmt->execute([$tid, $email]);
  $row = $stmt->fetch(PDO::FETCH_ASSOC);
  if (!$row) { echo json_encode(['ok'=>false,'msg'=>'Not found']); exit; }

  $pwd = ($type === 'trader') ? ($row['trader_pwd'] ?? '') : ($row['invester_pwd'] ?? '');
  echo json_encode(['ok'=>true,'pwd'=>$pwd]); exit;
}

/* =========================
   AJAX: fetch current leverage (NEW)
========================= */
if (isset($_POST['mode']) && $_POST['mode'] === 'fetch_lev') {
  header('Content-Type: application/json');
  $posted_csrf = $_POST['csrf'] ?? '';
  $email = trim($_POST['user_email'] ?? '');
  $tid   = trim($_POST['tradeid'] ?? '');

  if (!hash_equals($csrf, $posted_csrf)) { echo json_encode(['ok'=>false,'msg'=>'Invalid CSRF']); exit; }
  if (!$email || !$tid) { echo json_encode(['ok'=>false,'msg'=>'Missing fields']); exit; }

  // <-- leverage column
  $stmt = $conn->prepare("SELECT leverage FROM liveaccount WHERE trade_id = ? AND email = ? LIMIT 1");
  $stmt->execute([$tid, $email]);
  $lev = $stmt->fetchColumn();
  if ($lev === false) { echo json_encode(['ok'=>false,'msg'=>'Not found']); exit; }

  echo json_encode(['ok'=>true,'leverage'=>(int)$lev]); exit;
}

/* =========================
   Load users (emails)
========================= */
$emails = [];
try {
  $stmt = $conn->query("SELECT email FROM aspnetusers WHERE email IS NOT NULL AND email<>'' ORDER BY email ASC");
  $emails = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (Throwable $e) { $emails = []; }

/* =========================
   email -> trade_ids map
========================= */
$emailToAccounts = [];
try {
  $q = $conn->query("SELECT email, trade_id FROM liveaccount ORDER BY email, trade_id");
  while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
    $em  = (string)($r['email'] ?? '');
    $tid = (string)($r['trade_id'] ?? '');
    if ($em && $tid) $emailToAccounts[$em][] = $tid;
  }
} catch (Throwable $e) {}

$sel_email   = $_POST['user_email']    ?? '';
$sel_tradeid = $_POST['tradeid']       ?? '';
$sel_type    = $_POST['password_type'] ?? '';

/* =========================
   Handle submit (PWD and/or LEV)
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_POST['mode'])) {
  $posted_csrf = $_POST['csrf'] ?? '';
  if (!hash_equals($csrf, $posted_csrf)) {
    $flash = ['type'=>'error','msg'=>'Invalid request (CSRF). Please refresh and try again.'];
  } else {
    /* Which action? 'pwd' or 'lev' */
    $do = $_POST['do'] ?? 'pwd';

    if ($do === 'pwd') {
      $user_email    = trim($_POST['user_email'] ?? '');
      $trade_id      = trim($_POST['tradeid'] ?? '');
      $password_type = $_POST['password_type'] ?? '';
      $current_pwd   = $_POST['current_pwd'] ?? '';
      $new_pwd       = $_POST['new_pwd'] ?? '';
      $confirm_pwd   = $_POST['confirm_pwd'] ?? '';

      if (!$user_email || !$trade_id || !in_array($password_type, ['trader','investor'], true)) {
        $flash = ['type'=>'error','msg'=>'Please select Email, MT5 Account ID and Password Type.'];
      } elseif ($new_pwd !== $confirm_pwd) {
        $flash = ['type'=>'error','msg'=>'New Password and Confirm Password do not match.'];
      } elseif (!is_strong_pwd($new_pwd)) {
        $flash = ['type'=>'error','msg'=>'Password must be ≥ 8 chars with 1 uppercase, 1 number, and 1 special character.'];
      } else {
        $stmt = $conn->prepare("SELECT trader_pwd, invester_pwd FROM liveaccount WHERE trade_id = ? AND email = ? LIMIT 1");
        $stmt->execute([$trade_id, $user_email]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
          $flash = ['type'=>'error','msg'=>'This Trade ID does not belong to the selected email.'];
        } else {
          $stored_current = ($password_type === 'trader') ? ($row['trader_pwd'] ?? '') : ($row['invester_pwd'] ?? '');
          if ($stored_current !== $current_pwd) {
            $flash = ['type'=>'error','msg'=>'Current password is incorrect.'];
          } else {
            try {
              if ($password_type === 'trader') {
                $upd = $conn->prepare("UPDATE liveaccount SET trader_pwd = ? WHERE trade_id = ? AND email = ? LIMIT 1");
              } else {
                $upd = $conn->prepare("UPDATE liveaccount SET invester_pwd = ? WHERE trade_id = ? AND email = ? LIMIT 1");
              }
              $upd->execute([$new_pwd, $trade_id, $user_email]);
              $flash = ['type'=>'success','msg'=>'Trader/Investor password updated successfully.'];
            } catch (Throwable $e) {
              $flash = ['type'=>'error','msg'=>'Password update failed. Please try again.'];
            }
          }
        }
      }
    }

    if ($do === 'lev') {
      $lev_email   = trim($_POST['lev_email']  ?? '');
      $lev_tradeid = trim($_POST['lev_tradeid'] ?? '');
      $newLev      = (int)($_POST['new_leverage'] ?? 0);

      if (!$lev_email || !$lev_tradeid || !in_array($newLev, [50,100,200,300,500], true)) {
        $flash = ['type'=>'error','msg'=>'Please select Email, MT5 Account ID and a valid leverage.'];
      } else {
        try {
          // ensure ownership
          $chk = $conn->prepare("SELECT 1 FROM liveaccount WHERE trade_id = ? AND email = ? LIMIT 1");
          $chk->execute([$lev_tradeid, $lev_email]);
          if (!$chk->fetchColumn()) {
            $flash = ['type'=>'error','msg'=>'This Trade ID does not belong to the selected email.'];
          } else {
            // <-- leverage column
            $upd = $conn->prepare("UPDATE liveaccount SET leverage = ? WHERE trade_id = ? AND email = ? LIMIT 1");
            $upd->execute([$newLev, $lev_tradeid, $lev_email]);
            $flash = ['type'=>'success','msg'=>'Leverage updated successfully.'];
          }
        } catch (Throwable $e) {
          $flash = ['type'=>'error','msg'=>'Leverage update failed. Please try again.'];
        }
      }
    }
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Change MT5 Password & Leverage</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
  <style>
    :root{ --brand:#ff6a00; --brand-700:#cc3300; }
    .brand { color:var(--brand); }
    .btn-brand{ background:var(--brand); }
    .btn-brand:hover{ background:var(--brand-700); }
    .ring-brand:focus{ outline:none; box-shadow:0 0 0 3px rgb(255 106 0 / .35); border-color:var(--brand); }
    .hint { font-size:12px; color:#6b7280; }
    .err  { color:#b91c1c; font-size:12px; margin-top:6px; display:none; }
    .ok   { color:#065f46; font-size:12px; margin-top:6px; display:none; }
    .input-bad { border-color:#ef4444 !important; }
    .bg-gradient-dark-orange{ background:linear-gradient(135deg,#ff6a00 0%,#cc3300 100%); }
    .switch { position:relative; width:48px; height:26px; }
    .switch input { opacity:0; width:0; height:0; }
    .slider { position:absolute; cursor:pointer; inset:0; background:#e5e7eb; transition:.2s; border-radius:999px; }
    .slider:before { content:""; position:absolute; height:20px; width:20px; left:3px; top:3px; background:white; transition:.2s; border-radius:999px; }
    .switch input:checked + .slider { background:#fb923c; }
    .switch input:checked + .slider:before { transform:translateX(22px); }
  </style>
</head>
<body class="bg-gray-50">
<?php include "header.php"; ?>
<div class="flex flex-col md:flex-row min-h-screen">
  <?php include "side_bar.php"; ?>

  <main class="flex-1 md:ml-64">
    <!-- Hero -->
    <section class="bg-gradient-dark-orange text-white">
      <div class="max-w-5xl mx-auto px-6 py-6">
        <h1 class="text-xl md:text-2xl font-semibold">Change MT5 Password & Leverage</h1>
        <p class="text-white/85 text-sm mt-1">Pick a user (email), then the user’s MT5 Account ID. Update password or (optionally) leverage.</p>
      </div>
    </section>

    <div class="max-w-3xl mx-auto px-6 py-6">
      <?php if ($flash['type']==='success'): ?>
        <div class="mb-4 rounded-md bg-green-50 p-4 text-green-700 border border-green-200"><?= htmlspecialchars($flash['msg']) ?></div>
      <?php elseif ($flash['type']==='error'): ?>
        <div class="mb-4 rounded-md bg-red-50 p-4 text-red-700 border border-red-200"><?= htmlspecialchars($flash['msg']) ?></div>
      <?php endif; ?>

      <!-- ================= Password Form ================= -->
      <form id="pwdForm" method="POST" class="bg-white p-6 rounded-lg shadow-md space-y-6" novalidate>
        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf) ?>">
        <input type="hidden" name="do" value="pwd">

        <!-- 1) User Email -->
        <div>
          <label for="user_email" class="block text-sm font-semibold brand mb-2">User Email</label>
          <select id="user_email" name="user_email" required
                  class="w-full p-3 border border-gray-300 rounded-md text-sm ring-brand">
            <option value="">-- Select User Email --</option>
            <?php foreach ($emails as $em): ?>
              <option value="<?= htmlspecialchars($em) ?>" <?= ($sel_email===$em ? 'selected':'') ?>>
                <?= htmlspecialchars($em) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <!-- 2) Trade ID (filtered by email) -->
        <div>
          <label for="tradeid" class="block text-sm font-semibold brand mb-2">MT5 Account ID</label>
          <select id="tradeid" name="tradeid" required
                  class="w-full p-3 border border-gray-300 rounded-md text-sm ring-brand" disabled>
            <option value="">-- Select MT5 Account ID --</option>
          </select>
          <div class="hint">Only Trade IDs belonging to the selected email will be shown.</div>
        </div>

        <!-- 3) Password Type -->
        <div>
          <label for="password_type" class="block text-sm font-semibold brand mb-2">Password Type</label>
          <select id="password_type" name="password_type" required
                  class="w-full p-3 border border-gray-300 rounded-md text-sm ring-brand">
            <option value="">-- Select Password Type --</option>
            <option value="trader"   <?= ($sel_type==='trader'?'selected':'') ?>>Trader Password</option>
            <option value="investor" <?= ($sel_type==='investor'?'selected':'') ?>>Investor Password</option>
          </select>
        </div>

        <!-- 4) Current Password (auto-fetched via AJAX) -->
        <div>
          <label for="current_pwd" class="block text-sm font-semibold brand mb-2">Current Password</label>
          <div class="relative">
            <input type="password" id="current_pwd" name="current_pwd"
                   class="w-full p-3 pr-12 border border-gray-300 rounded-md text-sm ring-brand"
                   placeholder="Auto-fetched after you pick Email + MT5 ID + Type" value="<?= isset($_POST['current_pwd']) ? htmlspecialchars($_POST['current_pwd']) : '' ?>" required>
            <button type="button" id="toggle_cur" class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500">
              <i class="fa-regular fa-eye"></i>
            </button>
          </div>
        </div>

        <!-- 5) New Password -->
        <div>
          <label for="new_pwd" class="block text-sm font-semibold brand mb-2">New Password</label>
          <input type="password" id="new_pwd" name="new_pwd" required
                 class="w-full p-3 border border-gray-300 rounded-md text-sm ring-brand"
                 placeholder="Min 8 chars incl. A-Z, number, special" value="<?= isset($_POST['new_pwd']) ? htmlspecialchars($_POST['new_pwd']) : '' ?>">
          <div id="ruleErr" class="err">Must be ≥ 8 chars with 1 uppercase, 1 number, 1 special character.</div>
          <div id="ruleOk"  class="ok">Looks good ✅</div>
        </div>

        <!-- 6) Confirm Password -->
        <div>
          <label for="confirm_pwd" class="block text-sm font-semibold brand mb-2">Confirm New Password</label>
          <input type="password" id="confirm_pwd" name="confirm_pwd" required
                 class="w-full p-3 border border-gray-300 rounded-md text-sm ring-brand"
                 placeholder="Re-enter new password" value="<?= isset($_POST['confirm_pwd']) ? htmlspecialchars($_POST['confirm_pwd']) : '' ?>">
          <div id="matchErr" class="err">Passwords do not match.</div>
        </div>

        <button type="submit"
                class="w-full btn-brand text-white py-3 rounded-md font-semibold text-sm transition duration-300">
          Update Password
        </button>
      </form>

      <!-- ================= Leverage Toggle + Form ================= -->
      <div class="mt-6 bg-white rounded-lg shadow-md">
        <div class="flex items-center justify-between px-6 py-4">
          <div>
            <h3 class="text-sm font-semibold brand">Also update Leverage</h3>
            <p class="text-xs text-gray-500">Toggle to reveal leverage controls (email & trade ID are separate so you can change either independently).</p>
          </div>
          <label class="switch">
            <input id="lev_toggle" type="checkbox">
            <span class="slider"></span>
          </label>
        </div>

        <form id="levForm" method="POST" class="px-6 pb-6 pt-0 space-y-4 hidden" novalidate>
          <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf) ?>">
          <input type="hidden" name="do" value="lev">

          <!-- Email -->
          <div class="grid md:grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-semibold brand mb-2" for="lev_email">User Email</label>
              <select id="lev_email" name="lev_email" class="w-full p-3 border border-gray-300 rounded-md text-sm ring-brand" required>
                <option value="">-- Select User Email --</option>
                <?php foreach ($emails as $em): ?>
                  <option value="<?= htmlspecialchars($em) ?>"><?= htmlspecialchars($em) ?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <!-- Trade ID (dependent) -->
            <div>
              <label class="block text-sm font-semibold brand mb-2" for="lev_tradeid">MT5 Account ID</label>
              <select id="lev_tradeid" name="lev_tradeid" class="w-full p-3 border border-gray-300 rounded-md text-sm ring-brand" required disabled>
                <option value="">-- Select MT5 Account ID --</option>
              </select>
              <div class="hint">Only Trade IDs of the selected email are listed.</div>
            </div>
          </div>

          <!-- Current & New Leverage -->
          <div class="grid md:grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-semibold brand mb-2">Current Leverage</label>
              <input id="current_lev" type="text" class="w-full p-3 border border-gray-300 rounded-md text-sm bg-gray-50" placeholder="Auto-fetched" readonly>
            </div>
            <div>
              <label class="block text-sm font-semibold brand mb-2" for="new_leverage">New Leverage</label>
              <select id="new_leverage" name="new_leverage" class="w-full p-3 border border-gray-300 rounded-md text-sm ring-brand" required>
                <option value="">-- Select --</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="500">1:500</option>
              </select>
            </div>
          </div>

          <button type="submit" class="w-full btn-brand text-white py-3 rounded-md font-semibold text-sm transition">
            Update Leverage
          </button>
        </form>
      </div>
    </div>

    <?php include "footer.php"; ?>
  </main>
</div>

<script>
// ===== dependent lists (shared) =====
const emailToAccounts = <?= json_encode($emailToAccounts, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;

// Main (password) controls
const selEmail = document.getElementById('user_email');
const selTrade = document.getElementById('tradeid');
const selType  = document.getElementById('password_type');
const curInp   = document.getElementById('current_pwd');

// Leverage controls
const levToggle   = document.getElementById('lev_toggle');
const levForm     = document.getElementById('levForm');
const levEmailSel = document.getElementById('lev_email');
const levTradeSel = document.getElementById('lev_tradeid');
const currentLev  = document.getElementById('current_lev');
const newLevSel   = document.getElementById('new_leverage');

// ============ Password section ============
function refreshTradeIds() {
  const em = selEmail.value || '';
  const list = emailToAccounts[em] || [];
  selTrade.innerHTML = '<option value="">-- Select MT5 Account ID --</option>';
  if (list.length) {
    list.forEach(tid => {
      const opt = document.createElement('option');
      opt.value = tid; opt.textContent = tid;
      selTrade.appendChild(opt);
    });
    selTrade.disabled = false;
  } else {
    selTrade.disabled = true;
  }
}
async function fetchCurrentPwd(){
  const email = selEmail?.value || '';
  const tid   = selTrade?.value || '';
  const type  = selType ?.value || '';
  const csrf  = document.querySelector('#pwdForm input[name="csrf"]')?.value || '';
  if (!email || !tid || !type) { curInp.value = ''; return; }
  try {
    const res = await fetch(location.href, {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: new URLSearchParams({ mode:'fetch_pwd', csrf, user_email:email, tradeid:tid, password_type:type })
    });
    const data = await res.json();
    curInp.value = (data.ok && data.pwd) ? data.pwd : '';
  } catch { curInp.value = ''; }
}
selEmail.addEventListener('change', () => { refreshTradeIds(); curInp.value=''; });
selTrade.addEventListener('change', fetchCurrentPwd);
selType .addEventListener('change', fetchCurrentPwd);

// hydrate posted tradeid (if any)
(function initHydrate(){
  refreshTradeIds();
  <?php if (!empty($sel_tradeid)): ?>
    const wanted = "<?= htmlspecialchars($sel_tradeid, ENT_QUOTES) ?>";
    if ([...selTrade.options].some(o => o.value===wanted)) selTrade.value = wanted;
  <?php endif; ?>
  fetchCurrentPwd();
})();

// eye toggle
document.getElementById('toggle_cur')?.addEventListener('click', (event) => {
  if (!curInp.value) return;
  curInp.type = (curInp.type === 'password') ? 'text' : 'password';
  event.currentTarget.innerHTML = (curInp.type === 'password')
    ? '<i class="fa-regular fa-eye"></i>' : '<i class="fa-regular fa-eye-slash"></i>';
});

// pwd validations
const form     = document.getElementById('pwdForm');
const newInp   = document.getElementById('new_pwd');
const confInp  = document.getElementById('confirm_pwd');
const ruleErr  = document.getElementById('ruleErr');
const ruleOk   = document.getElementById('ruleOk');
const matchErr = document.getElementById('matchErr');
const strongRe = /^(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/;
function validateStrength() {
  if (!newInp.value) { ruleErr.style.display='none'; ruleOk.style.display='none'; newInp.classList.remove('input-bad'); return true; }
  const ok = strongRe.test(newInp.value);
  ruleErr.style.display = ok ? 'none' : 'block';
  ruleOk.style.display  = ok ? 'block' : 'none';
  newInp.classList.toggle('input-bad', !ok); return ok;
}
function validateMatch() {
  if (!confInp.value) { matchErr.style.display='none'; confInp.classList.remove('input-bad'); return true; }
  const ok = newInp.value === confInp.value;
  matchErr.style.display = ok ? 'none' : 'block';
  confInp.classList.toggle('input-bad', !ok); return ok;
}
newInp.addEventListener('input', () => { validateStrength(); validateMatch(); });
confInp.addEventListener('input', validateMatch);
form?.addEventListener('submit', (e) => {
  const ok1 = validateStrength(), ok2 = validateMatch();
  if (!ok1 || !ok2) { e.preventDefault(); alert('Please fix password errors before submitting.'); }
});

// ============ Leverage section ============
levToggle.addEventListener('change', e => {
  levForm.classList.toggle('hidden', !e.target.checked);
  if (e.target.checked) currentLev.value = '';
});

function refreshLevTradeIds(){
  const em = levEmailSel.value || '';
  const list = emailToAccounts[em] || [];
  levTradeSel.innerHTML = '<option value="">-- Select MT5 Account ID --</option>';
  if (list.length) {
    list.forEach(tid => {
      const o = document.createElement('option');
      o.value = tid; o.textContent = tid;
      levTradeSel.appendChild(o);
    });
    levTradeSel.disabled = false;
  } else {
    levTradeSel.disabled = true;
  }
  currentLev.value = '';
}
async function fetchCurrentLev(){
  const email = levEmailSel?.value || '';
  const tid   = levTradeSel?.value || '';
  const csrf  = document.querySelector('#levForm input[name="csrf"]')?.value || '';
  if (!email || !tid) { currentLev.value=''; return; }
  try{
    const res = await fetch(location.href, {
      method:'POST',
      headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body:new URLSearchParams({ mode:'fetch_lev', csrf, user_email:email, tradeid:tid })
    });
    const data = await res.json();
    currentLev.value = (data.ok && data.leverage) ? ('1:'+data.leverage) : '';
  } catch { currentLev.value=''; }
}
levEmailSel.addEventListener('change', ()=>{ refreshLevTradeIds(); });
levTradeSel.addEventListener('change', fetchCurrentLev);

// optional: when you pick a new leverage, you can auto-highlight
newLevSel.addEventListener('change', ()=> {
  if (newLevSel.value) newLevSel.classList.add('ring-brand'); else newLevSel.classList.remove('ring-brand');
});
</script>
</body>
</html>
