<?php
require_once 'db.php';
require_once 'auth_check.php';

$uid = $user_id;
$msg = '';
$msg_type = '';

// ── Handle AJAX / POST saves ──────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    $action = $_POST['action'] ?? '';

    switch ($action) {

        case 'save_avatar':
            $response = ['success' => false, 'msg' => 'No file uploaded'];
            if (!empty($_FILES['avatar']['tmp_name'])) {
                $ext = strtolower(pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION));
                $allowed = ['jpg','jpeg','png','gif','webp'];
                if (in_array($ext, $allowed)) {
                    $dir = 'uploads/avatars/';
                    if (!is_dir($dir)) mkdir($dir, 0755, true);
                    $filename = $dir . 'avatar_' . $uid . '_' . time() . '.' . $ext;
                    if (move_uploaded_file($_FILES['avatar']['tmp_name'], $filename)) {
                        $stmt = $conn->prepare("UPDATE users SET avatar=? WHERE id=?");
                        $stmt->bind_param('si', $filename, $uid);
                        $stmt->execute();
                        $response = ['success' => true, 'msg' => 'Avatar updated!', 'avatar' => $filename];
                    }
                } else {
                    $response['msg'] = 'Invalid file type';
                }
            }
            echo json_encode($response);
            exit;

        case 'save_usdt':
            $wallet = trim($_POST['wallet'] ?? '');
            if (strlen($wallet) < 10) {
                echo json_encode(['success'=>false,'msg'=>'Wallet address too short']);
                exit;
            }
            $stmt = $conn->prepare("UPDATE users SET usdt_wallet=? WHERE id=?");
            $stmt->bind_param('si', $wallet, $uid);
            $stmt->execute();
            echo json_encode(['success'=>true,'msg'=>'USDT Wallet saved!']);
            exit;

        case 'save_login_password':
            $old = $_POST['old_password'] ?? '';
            $new = $_POST['new_password'] ?? '';
            $confirm = $_POST['confirm_password'] ?? '';
            if ($new !== $confirm) {
                echo json_encode(['success'=>false,'msg'=>'New passwords do not match']);
                exit;
            }
            if (strlen($new) < 6) {
                echo json_encode(['success'=>false,'msg'=>'Password must be at least 6 characters']);
                exit;
            }
            $row = $conn->query("SELECT password FROM users WHERE id=$uid")->fetch_assoc();
            if (!password_verify($old, $row['password'])) {
                echo json_encode(['success'=>false,'msg'=>'Old password incorrect']);
                exit;
            }
            $hash = password_hash($new, PASSWORD_BCRYPT);
            $stmt = $conn->prepare("UPDATE users SET password=? WHERE id=?");
            $stmt->bind_param('si', $hash, $uid);
            $stmt->execute();
            echo json_encode(['success'=>true,'msg'=>'Login password updated!']);
            exit;

        case 'save_fund_password':
            $new = $_POST['fund_password'] ?? '';
            $confirm = $_POST['confirm_fund'] ?? '';
            if ($new !== $confirm) {
                echo json_encode(['success'=>false,'msg'=>'Passwords do not match']);
                exit;
            }
            if (strlen($new) < 4) {
                echo json_encode(['success'=>false,'msg'=>'Fund password must be at least 4 digits']);
                exit;
            }
            $hash = password_hash($new, PASSWORD_BCRYPT);
            $stmt = $conn->prepare("UPDATE users SET fund_password=? WHERE id=?");
            $stmt->bind_param('si', $hash, $uid);
            $stmt->execute();
            echo json_encode(['success'=>true,'msg'=>'Fund password set!']);
            exit;

        case 'clear_cache':
            // server-side: clear session cache or any temp data
            echo json_encode(['success'=>true,'msg'=>'Cache cleared!']);
            exit;
    }

    echo json_encode(['success'=>false,'msg'=>'Unknown action']);
    exit;
}

// ── Fetch fresh user data ─────────────────────────────────
$u = $conn->query("SELECT * FROM users WHERE id=$uid")->fetch_assoc();
$phone    = $u['phone'] ?? '';
$avatar   = $u['avatar'] ?? '';
$usdt     = $u['usdt_wallet'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>WFM - Personal Information</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{
  font-family:'Segoe UI',sans-serif;
  background:linear-gradient(160deg,#b8cba8 0%,#a8bc96 40%,#8faa7a 100%);
  min-height:100vh;
  padding-bottom:90px
}

/* ── Top Bar ── */
.top-bar{
  background:rgba(255,255,255,.45);
  backdrop-filter:blur(8px);
  padding:14px 16px;
  display:flex;
  align-items:center;
  justify-content:space-between;
  border-bottom:1px solid rgba(255,255,255,.3)
}
.back-btn{
  width:36px;height:36px;
  background:rgba(255,255,255,.6);
  border-radius:50%;
  display:flex;align-items:center;justify-content:center;
  text-decoration:none;
  cursor:pointer;border:none
}
.back-btn svg{width:20px;height:20px;fill:#1a2a0a}
.top-bar h1{font-size:17px;font-weight:700;color:#1a2a0a;flex:1;text-align:center}
.top-bar-right{width:36px}

/* ── List Card ── */
.list-card{
  margin:16px 12px 0;
  background:#fff;
  border-radius:16px;
  overflow:hidden
}
.list-item{
  display:flex;
  align-items:center;
  padding:14px 16px;
  border-bottom:1px solid #f0f0f0;
  cursor:pointer;
  transition:background .15s;
  gap:12px
}
.list-item:last-child{border-bottom:none}
.list-item:active{background:#f7f7f7}
.item-icon{
  width:34px;height:34px;
  border-radius:50%;
  display:flex;align-items:center;justify-content:center;
  flex-shrink:0;font-size:16px
}
.item-label{flex:1;font-size:14px;color:#333;font-weight:500}
.item-value{font-size:13px;color:#999;margin-right:6px;max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.item-arrow svg{width:16px;height:16px;fill:#bbb}

/* Avatar preview */
.avatar-preview{
  width:36px;height:36px;
  border-radius:50%;
  object-fit:cover;
  border:2px solid #eee
}
.avatar-placeholder-sm{
  width:36px;height:36px;
  border-radius:50%;
  background:linear-gradient(135deg,#3eaabb,#2c7be5);
  display:flex;align-items:center;justify-content:center
}
.avatar-placeholder-sm svg{width:20px;height:20px;fill:#fff}

/* ── Logout Button ── */
.logout-big{
  display:block;
  margin:16px 12px;
  background:linear-gradient(90deg,#3ecf8e,#2c7be5);
  color:#fff;
  text-align:center;
  padding:16px;
  border-radius:14px;
  font-size:16px;
  font-weight:700;
  text-decoration:none
}

/* ── Bottom Nav ── */
.bottom-nav{
  position:fixed;
  bottom:0;left:0;right:0;
  height:64px;
  background:#fff;
  border-top:1px solid #e0e0e0;
  display:flex;
  align-items:center;
  justify-content:space-around;
  z-index:1000
}
.bn-item{
  display:flex;flex-direction:column;align-items:center;
  gap:3px;text-decoration:none;flex:1;padding:6px 0
}
.bn-item .bn-icon{
  width:26px;height:26px;
  background-size:contain;
  background-repeat:no-repeat;
  background-position:center
}
.bn-item span{font-size:10px;font-weight:600}
.bn-item.active span{color:#3eaabb}
.bn-item:not(.active) span{color:#aaa}

/* ── Float Service ── */
.float-service{
  position:fixed;bottom:80px;right:10px;
  display:flex;flex-direction:column;align-items:center;
  z-index:999;text-decoration:none;cursor:pointer
}
.float-service img{width:55px;height:55px;border-radius:50%;object-fit:cover}
.float-service span{font-size:10px;color:#3a5a2a;font-weight:600;text-align:center;margin-top:2px}

/* ═══════════════════════════════════════
   OVERLAY & POPUP
═══════════════════════════════════════ */
.overlay{
  display:none;
  position:fixed;inset:0;
  background:rgba(0,0,0,.45);
  z-index:2000;
  align-items:flex-end;
  justify-content:center
}
.overlay.show{display:flex}

.popup{
  background:#fff;
  border-radius:20px 20px 0 0;
  width:100%;
  max-width:520px;
  padding:0 0 24px;
  transform:translateY(100%);
  transition:transform .3s ease;
  overflow:hidden
}
.overlay.show .popup{transform:translateY(0)}

.popup-header{
  padding:16px 20px 14px;
  border-bottom:1px solid #f0f0f0;
  display:flex;align-items:center;justify-content:space-between
}
.popup-title{font-size:16px;font-weight:700;color:#1a2a0a}
.popup-close{
  width:30px;height:30px;
  background:#f0f0f0;
  border-radius:50%;
  border:none;cursor:pointer;
  display:flex;align-items:center;justify-content:center
}
.popup-close svg{width:16px;height:16px;fill:#555}

.popup-body{padding:20px}

/* Avatar upload area */
.avatar-upload-area{
  display:flex;flex-direction:column;align-items:center;gap:16px
}
.avatar-big{
  width:90px;height:90px;
  border-radius:50%;
  object-fit:cover;
  border:3px solid #e0e0e0
}
.avatar-big-placeholder{
  width:90px;height:90px;
  border-radius:50%;
  background:linear-gradient(135deg,#3eaabb,#2c7be5);
  display:flex;align-items:center;justify-content:center
}
.avatar-big-placeholder svg{width:44px;height:44px;fill:#fff}
.upload-label{
  display:inline-flex;align-items:center;gap:8px;
  background:linear-gradient(90deg,#3ecf8e,#2c7be5);
  color:#fff;
  padding:10px 24px;
  border-radius:25px;
  font-size:14px;font-weight:600;
  cursor:pointer
}
.upload-label input{display:none}

/* Form inputs */
.form-group{margin-bottom:16px}
.form-label{font-size:13px;font-weight:600;color:#555;margin-bottom:7px;display:block}
.form-input{
  width:100%;
  padding:12px 14px;
  border:1.5px solid #e0e0e0;
  border-radius:10px;
  font-size:14px;
  font-family:inherit;
  outline:none;
  transition:border-color .2s
}
.form-input:focus{border-color:#3eaabb}

.btn-save{
  width:100%;
  padding:14px;
  background:linear-gradient(90deg,#3ecf8e,#2c7be5);
  color:#fff;
  border:none;
  border-radius:12px;
  font-size:15px;font-weight:700;
  font-family:inherit;
  cursor:pointer;
  margin-top:4px
}

/* Toast */
.toast{
  position:fixed;
  top:20px;left:50%;
  transform:translateX(-50%) translateY(-80px);
  background:#1a2a0a;
  color:#fff;
  padding:12px 24px;
  border-radius:25px;
  font-size:13px;font-weight:600;
  z-index:9999;
  transition:transform .3s ease;
  white-space:nowrap;
  pointer-events:none
}
.toast.show{transform:translateX(-50%) translateY(0)}
.toast.success{background:linear-gradient(90deg,#3ecf8e,#2c7be5)}
.toast.error{background:linear-gradient(90deg,#e74c3c,#c0392b)}

/* Spinner */
.spinner{
  width:20px;height:20px;
  border:2px solid rgba(255,255,255,.4);
  border-top-color:#fff;
  border-radius:50%;
  animation:spin .7s linear infinite;
  display:none
}
@keyframes spin{to{transform:rotate(360deg)}}
.btn-save.loading .btn-text{display:none}
.btn-save.loading .spinner{display:inline-block}

/* Info row for read-only display */
.info-note{
  text-align:center;
  font-size:13px;
  color:#999;
  margin-bottom:16px
}
</style>
</head>
<body>

<!-- Top Bar -->
<div class="top-bar">
  <a href="account.php" class="back-btn">
    <svg viewBox="0 0 24 24"><path d="M15.41 16.59L10.83 12l4.58-4.59L14 6l-6 6 6 6z"/></svg>
  </a>
  <h1>Personal Information</h1>
  <div class="top-bar-right"></div>
</div>

<!-- List Card -->
<div class="list-card">

  <!-- Avatar -->
  <div class="list-item" onclick="openPopup('avatar')">
    <div class="item-icon" style="background:#fff3e0">🧑</div>
    <span class="item-label">Avatar</span>
    <?php if ($avatar): ?>
      <img src="<?= htmlspecialchars($avatar) ?>" class="avatar-preview" id="avatarThumb">
    <?php else: ?>
      <div class="avatar-placeholder-sm" id="avatarThumb">
        <svg viewBox="0 0 24 24"><path d="M12 12c2.7 0 5-2.3 5-5s-2.3-5-5-5-5 2.3-5 5 2.3 5 5 5zm0 2c-3.3 0-10 1.7-10 5v2h20v-2c0-3.3-6.7-5-10-5z"/></svg>
      </div>
    <?php endif; ?>
    <div class="item-arrow"><svg viewBox="0 0 24 24"><path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6z"/></svg></div>
  </div>

  <!-- Phone Number (read-only) -->
  <div class="list-item" onclick="openPopup('phone')">
    <div class="item-icon" style="background:#fff9c4">📱</div>
    <span class="item-label">Phone Number</span>
    <span class="item-value"><?= htmlspecialchars($phone) ?></span>
    <div class="item-arrow"><svg viewBox="0 0 24 24"><path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6z"/></svg></div>
  </div>

  <!-- Wallet Account -->
  <div class="list-item" onclick="openPopup('usdt')">
    <div class="item-icon" style="background:#e8f5e9">💚</div>
    <span class="item-label">Wallet Account</span>
    <span class="item-value"><?= $usdt ? htmlspecialchars(substr($usdt,0,10).'...') : 'Click to Set' ?></span>
    <div class="item-arrow"><svg viewBox="0 0 24 24"><path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6z"/></svg></div>
  </div>

  <!-- Login Password -->
  <div class="list-item" onclick="openPopup('login_password')">
    <div class="item-icon" style="background:#ede7f6">🔒</div>
    <span class="item-label">Login Password</span>
    <span class="item-value">Click to Set</span>
    <div class="item-arrow"><svg viewBox="0 0 24 24"><path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6z"/></svg></div>
  </div>

  <!-- Fund Password -->
  <div class="list-item" onclick="openPopup('fund_password')">
    <div class="item-icon" style="background:#e3f2fd">🔵</div>
    <span class="item-label">Fund Password</span>
    <span class="item-value">Click to Set</span>
    <div class="item-arrow"><svg viewBox="0 0 24 24"><path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6z"/></svg></div>
  </div>

  <!-- Clear Cache -->
  <div class="list-item" onclick="openPopup('clear_cache')">
    <div class="item-icon" style="background:#f5f5f5">🗑️</div>
    <span class="item-label">Clear Cache</span>
    <div class="item-arrow"><svg viewBox="0 0 24 24"><path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6z"/></svg></div>
  </div>

</div>

<!-- Logout -->
<a href="logout.php" class="logout-big">⏻ Logout</a>

<!-- Float Service -->
<a href="#" target="_blank" class="float-service">
  <img src="https://api.wfmtr.me/static/api/images/icon/service.png" alt="" onerror="this.src='care.png'">
  <span>Online Service</span>
</a>

<!-- Bottom Nav -->
<?php include 'navigation_bottom.php'; ?>

<!-- Toast -->
<div class="toast" id="toast"></div>

<!-- ═══════════════════════════════
     POPUPS
═══════════════════════════════ -->

<!-- 1. Avatar Popup -->
<div class="overlay" id="popup-avatar" onclick="overlayClick(event,'avatar')">
  <div class="popup">
    <div class="popup-header">
      <span class="popup-title">Change Avatar</span>
      <button class="popup-close" onclick="closePopup('avatar')">
        <svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
      </button>
    </div>
    <div class="popup-body">
      <div class="avatar-upload-area">
        <?php if ($avatar): ?>
          <img src="<?= htmlspecialchars($avatar) ?>" class="avatar-big" id="avatarPreviewBig">
        <?php else: ?>
          <div class="avatar-big-placeholder" id="avatarPreviewBig">
            <svg viewBox="0 0 24 24"><path d="M12 12c2.7 0 5-2.3 5-5s-2.3-5-5-5-5 2.3-5 5 2.3 5 5 5zm0 2c-3.3 0-10 1.7-10 5v2h20v-2c0-3.3-6.7-5-10-5z"/></svg>
          </div>
        <?php endif; ?>
        <label class="upload-label">
          <svg viewBox="0 0 24 24" width="18" height="18" fill="white"><path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/></svg>
          Choose Photo
          <input type="file" accept="image/*" id="avatarFileInput" onchange="previewAvatar(event)">
        </label>
        <button class="btn-save" id="btnSaveAvatar" onclick="saveAvatar()">
          <span class="btn-text">Save Avatar</span>
          <span class="spinner"></span>
        </button>
      </div>
    </div>
  </div>
</div>

<!-- 2. Phone Number Popup (read-only) -->
<div class="overlay" id="popup-phone" onclick="overlayClick(event,'phone')">
  <div class="popup">
    <div class="popup-header">
      <span class="popup-title">Phone Number</span>
      <button class="popup-close" onclick="closePopup('phone')">
        <svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
      </button>
    </div>
    <div class="popup-body">
      <p class="info-note">Your registered phone number</p>
      <div class="form-group">
        <input class="form-input" value="<?= htmlspecialchars($phone) ?>" readonly style="background:#f7f7f7;color:#333;font-size:16px;text-align:center;letter-spacing:2px">
      </div>
      <p class="info-note" style="color:#e74c3c">Phone number cannot be changed. Contact support if needed.</p>
    </div>
  </div>
</div>

<!-- 3. USDT Wallet Popup -->
<div class="overlay" id="popup-usdt" onclick="overlayClick(event,'usdt')">
  <div class="popup">
    <div class="popup-header">
      <span class="popup-title">Wallet Account</span>
      <button class="popup-close" onclick="closePopup('usdt')">
        <svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
      </button>
    </div>
    <div class="popup-body">
      <div class="form-group">
        <label class="form-label">Wallet Account Number</label>
        <input class="form-input" id="usdtWalletInput" placeholder="Enter your wallet account number"
               value="<?= htmlspecialchars($usdt) ?>">
      </div>
      <button class="btn-save" id="btnSaveUsdt" onclick="saveUsdt()">
        <span class="btn-text">Save Wallet Account</span>
        <span class="spinner"></span>
      </button>
    </div>
  </div>
</div>

<!-- 4. Login Password Popup -->
<div class="overlay" id="popup-login_password" onclick="overlayClick(event,'login_password')">
  <div class="popup">
    <div class="popup-header">
      <span class="popup-title">Change Login Password</span>
      <button class="popup-close" onclick="closePopup('login_password')">
        <svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
      </button>
    </div>
    <div class="popup-body">
      <div class="form-group">
        <label class="form-label">Current Password</label>
        <input class="form-input" type="password" id="oldPassword" placeholder="Enter current password">
      </div>
      <div class="form-group">
        <label class="form-label">New Password</label>
        <input class="form-input" type="password" id="newPassword" placeholder="Enter new password (min 6 chars)">
      </div>
      <div class="form-group">
        <label class="form-label">Confirm New Password</label>
        <input class="form-input" type="password" id="confirmPassword" placeholder="Repeat new password">
      </div>
      <button class="btn-save" id="btnSaveLoginPw" onclick="saveLoginPassword()">
        <span class="btn-text">Update Password</span>
        <span class="spinner"></span>
      </button>
    </div>
  </div>
</div>

<!-- 5. Fund Password Popup -->
<div class="overlay" id="popup-fund_password" onclick="overlayClick(event,'fund_password')">
  <div class="popup">
    <div class="popup-header">
      <span class="popup-title">Set Fund Password</span>
      <button class="popup-close" onclick="closePopup('fund_password')">
        <svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
      </button>
    </div>
    <div class="popup-body">
      <div class="form-group">
        <label class="form-label">Fund Password (4-6 digits)</label>
        <input class="form-input" type="password" inputmode="numeric" maxlength="6"
               id="fundPassword" placeholder="Enter fund password">
      </div>
      <div class="form-group">
        <label class="form-label">Confirm Fund Password</label>
        <input class="form-input" type="password" inputmode="numeric" maxlength="6"
               id="confirmFund" placeholder="Repeat fund password">
      </div>
      <button class="btn-save" id="btnSaveFundPw" onclick="saveFundPassword()">
        <span class="btn-text">Set Fund Password</span>
        <span class="spinner"></span>
      </button>
    </div>
  </div>
</div>

<!-- 6. Clear Cache Popup -->
<div class="overlay" id="popup-clear_cache" onclick="overlayClick(event,'clear_cache')">
  <div class="popup">
    <div class="popup-header">
      <span class="popup-title">Clear Cache</span>
      <button class="popup-close" onclick="closePopup('clear_cache')">
        <svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
      </button>
    </div>
    <div class="popup-body">
      <p class="info-note" style="font-size:15px;color:#555;margin-bottom:20px">
        This will clear your local app cache and temporary data.
      </p>
      <button class="btn-save" id="btnClearCache" onclick="doClearCache()" style="background:linear-gradient(90deg,#e74c3c,#c0392b)">
        <span class="btn-text">🗑️ Clear Cache Now</span>
        <span class="spinner"></span>
      </button>
    </div>
  </div>
</div>

<!-- ═══════════════════════════════
     JAVASCRIPT
═══════════════════════════════ -->
<script>
// ── Popup helpers ──────────────────────────────────────────
function openPopup(name) {
  const el = document.getElementById('popup-' + name);
  el.style.display = 'flex';
  requestAnimationFrame(() => el.classList.add('show'));
  document.body.style.overflow = 'hidden';
}
function closePopup(name) {
  const el = document.getElementById('popup-' + name);
  el.classList.remove('show');
  setTimeout(() => { el.style.display = 'none'; }, 300);
  document.body.style.overflow = '';
}
function overlayClick(e, name) {
  if (e.target === document.getElementById('popup-' + name)) closePopup(name);
}

// ── Toast ──────────────────────────────────────────────────
function showToast(msg, type='success') {
  const t = document.getElementById('toast');
  t.textContent = msg;
  t.className = 'toast ' + type + ' show';
  setTimeout(() => t.className = 'toast', 2800);
}

// ── Button loading ─────────────────────────────────────────
function setLoading(btnId, on) {
  const b = document.getElementById(btnId);
  if (on) b.classList.add('loading');
  else b.classList.remove('loading');
  b.disabled = on;
}

// ── POST helper ────────────────────────────────────────────
async function postForm(formData) {
  const res = await fetch('info.php', { method:'POST', body: formData });
  return res.json();
}

// ── Avatar ─────────────────────────────────────────────────
let avatarFile = null;

function previewAvatar(e) {
  avatarFile = e.target.files[0];
  if (!avatarFile) return;
  const url = URL.createObjectURL(avatarFile);
  const container = document.getElementById('avatarPreviewBig');
  // Replace whatever is there with an img
  const img = document.createElement('img');
  img.src = url;
  img.className = 'avatar-big';
  img.id = 'avatarPreviewBig';
  container.parentNode.replaceChild(img, container);
}

async function saveAvatar() {
  if (!avatarFile) { showToast('Please choose a photo first', 'error'); return; }
  setLoading('btnSaveAvatar', true);
  const fd = new FormData();
  fd.append('action', 'save_avatar');
  fd.append('avatar', avatarFile);
  try {
    const data = await postForm(fd);
    if (data.success) {
      showToast(data.msg, 'success');
      // Update thumbnail in the list
      const thumb = document.getElementById('avatarThumb');
      const newImg = document.createElement('img');
      newImg.src = data.avatar;
      newImg.className = 'avatar-preview';
      newImg.id = 'avatarThumb';
      thumb.parentNode.replaceChild(newImg, thumb);
      setTimeout(() => closePopup('avatar'), 800);
    } else {
      showToast(data.msg, 'error');
    }
  } catch(e) { showToast('Error saving avatar', 'error'); }
  setLoading('btnSaveAvatar', false);
}

// ── USDT Wallet ────────────────────────────────────────────
async function saveUsdt() {
  const wallet = document.getElementById('usdtWalletInput').value.trim();
  if (!wallet) { showToast('Please enter wallet address', 'error'); return; }
  setLoading('btnSaveUsdt', true);
  const fd = new FormData();
  fd.append('action', 'save_usdt');
  fd.append('wallet', wallet);
  try {
    const data = await postForm(fd);
    showToast(data.msg, data.success ? 'success' : 'error');
    if (data.success) setTimeout(() => closePopup('usdt'), 800);
  } catch(e) { showToast('Error saving wallet', 'error'); }
  setLoading('btnSaveUsdt', false);
}

// ── Login Password ─────────────────────────────────────────
async function saveLoginPassword() {
  const old_password = document.getElementById('oldPassword').value;
  const new_password = document.getElementById('newPassword').value;
  const confirm_password = document.getElementById('confirmPassword').value;
  if (!old_password || !new_password || !confirm_password) {
    showToast('Please fill all fields', 'error'); return;
  }
  setLoading('btnSaveLoginPw', true);
  const fd = new FormData();
  fd.append('action', 'save_login_password');
  fd.append('old_password', old_password);
  fd.append('new_password', new_password);
  fd.append('confirm_password', confirm_password);
  try {
    const data = await postForm(fd);
    showToast(data.msg, data.success ? 'success' : 'error');
    if (data.success) {
      document.getElementById('oldPassword').value = '';
      document.getElementById('newPassword').value = '';
      document.getElementById('confirmPassword').value = '';
      setTimeout(() => closePopup('login_password'), 900);
    }
  } catch(e) { showToast('Error updating password', 'error'); }
  setLoading('btnSaveLoginPw', false);
}

// ── Fund Password ──────────────────────────────────────────
async function saveFundPassword() {
  const fund_password = document.getElementById('fundPassword').value;
  const confirm_fund = document.getElementById('confirmFund').value;
  if (!fund_password || !confirm_fund) {
    showToast('Please fill all fields', 'error'); return;
  }
  setLoading('btnSaveFundPw', true);
  const fd = new FormData();
  fd.append('action', 'save_fund_password');
  fd.append('fund_password', fund_password);
  fd.append('confirm_fund', confirm_fund);
  try {
    const data = await postForm(fd);
    showToast(data.msg, data.success ? 'success' : 'error');
    if (data.success) {
      document.getElementById('fundPassword').value = '';
      document.getElementById('confirmFund').value = '';
      setTimeout(() => closePopup('fund_password'), 900);
    }
  } catch(e) { showToast('Error setting fund password', 'error'); }
  setLoading('btnSaveFundPw', false);
}

// ── Clear Cache ────────────────────────────────────────────
async function doClearCache() {
  setLoading('btnClearCache', true);
  const fd = new FormData();
  fd.append('action', 'clear_cache');
  try {
    const data = await postForm(fd);
    // Also clear localStorage / sessionStorage
    localStorage.clear();
    sessionStorage.clear();
    showToast('Cache cleared successfully!', 'success');
    setTimeout(() => closePopup('clear_cache'), 900);
  } catch(e) { showToast('Error clearing cache', 'error'); }
  setLoading('btnClearCache', false);
}
</script>
</body>
</html>