<?php
// ============================================================
//  user_edit.php — Edit User (Details + Password + Avatar)
//  Place in: /admin/user_edit.php
// ============================================================
require_once 'includes/auth_check.php';

$user_id = (int)($_GET['id'] ?? 0);
if ($user_id <= 0) {
    $_SESSION['flash_error'] = 'Invalid user ID.';
    header('Location: users.php');
    exit;
}

$user = db_fetch_one("SELECT * FROM users WHERE id = ?", [$user_id]);
if (!$user) {
    $_SESSION['flash_error'] = 'User not found.';
    header('Location: users.php');
    exit;
}

$page_title = 'Edit User — ' . $user['full_name'];

// Active tab (details | password | avatar)
$active_tab = in_array($_GET['tab'] ?? '', ['password','avatar']) ? $_GET['tab'] : 'details';

// Flash
$flash_success = $_SESSION['flash_success'] ?? '';
$flash_error   = $_SESSION['flash_error']   ?? '';
unset($_SESSION['flash_success'], $_SESSION['flash_error']);

// CSRF
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

$errors = [];

// ============================================================
//  HANDLE POST ACTIONS
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (($_POST['csrf_token'] ?? '') !== $csrf) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {

        $action = $_POST['action'] ?? '';

        // ── UPDATE DETAILS ──────────────────────────────────────
        if ($action === 'update_details' && empty($errors)) {
            $full_name = trim($_POST['full_name'] ?? '');
            $username  = trim($_POST['username']  ?? '');
            $email     = trim($_POST['email']     ?? '');
            $phone     = trim($_POST['phone']     ?? '');
            $bio       = trim($_POST['bio']       ?? '');
            $status    = $_POST['status']         ?? $user['status'];
            $verified  = isset($_POST['email_verified']) ? 1 : 0;

            if (empty($full_name)) $errors[] = 'Full name is required.';
            if (empty($username))  $errors[] = 'Username is required.';
            if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL))
                $errors[] = 'Valid email address is required.';

            // Unique checks (exclude current user)
            if (empty($errors)) {
                $dup_username = db_fetch_one(
                    "SELECT id FROM users WHERE username = ? AND id != ?", [$username, $user_id]
                );
                $dup_email = db_fetch_one(
                    "SELECT id FROM users WHERE email = ? AND id != ?", [$email, $user_id]
                );
                if ($dup_username) $errors[] = "Username '@{$username}' is already taken.";
                if ($dup_email)    $errors[] = "Email '{$email}' is already in use.";
            }

            if (empty($errors)) {
                db_execute(
                    "UPDATE users SET full_name=?, username=?, email=?, phone=?, bio=?,
                                      status=?, email_verified=?
                     WHERE id=?",
                    [$full_name, $username, $email, $phone ?: null, $bio ?: null,
                     $status, $verified, $user_id]
                );
                db_execute(
                    "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                     VALUES (?, 'edited_user', 'user', ?, ?, ?, ?)",
                    [$current_admin['id'], $user_id, $full_name,
                     "Updated profile details", $_SERVER['REMOTE_ADDR']]
                );
                $_SESSION['flash_success'] = 'User profile updated successfully.';
                header("Location: user_edit.php?id={$user_id}&tab=details");
                exit;
            }
            $active_tab = 'details';
        }

        // ── UPDATE PASSWORD ─────────────────────────────────────
        if ($action === 'update_password' && empty($errors)) {
            $new_password  = $_POST['new_password']   ?? '';
            $confirm_pass  = $_POST['confirm_password'] ?? '';

            if (strlen($new_password) < 8)
                $errors[] = 'Password must be at least 8 characters.';
            if ($new_password !== $confirm_pass)
                $errors[] = 'Passwords do not match.';
            if (!preg_match('/[A-Z]/', $new_password))
                $errors[] = 'Password must contain at least one uppercase letter.';
            if (!preg_match('/[0-9]/', $new_password))
                $errors[] = 'Password must contain at least one number.';

            if (empty($errors)) {
                $hash = password_hash($new_password, PASSWORD_BCRYPT);
                db_execute("UPDATE users SET password_hash = ? WHERE id = ?", [$hash, $user_id]);
                db_execute(
                    "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                     VALUES (?, 'reset_user_password', 'user', ?, ?, ?, ?)",
                    [$current_admin['id'], $user_id, $user['full_name'],
                     "Admin reset user password", $_SERVER['REMOTE_ADDR']]
                );
                $_SESSION['flash_success'] = "Password updated for {$user['full_name']}.";
                header("Location: user_edit.php?id={$user_id}&tab=password");
                exit;
            }
            $active_tab = 'password';
        }

        // ── UPDATE AVATAR ───────────────────────────────────────
        if ($action === 'update_avatar' && empty($errors)) {

            if (isset($_POST['remove_avatar'])) {
                // Remove avatar, reset to default
                $old = $user['avatar'];
                if ($old && $old !== 'Avatar.png' && file_exists("assets/images/avatars/{$old}")) {
                    unlink("assets/images/avatars/{$old}");
                }
                db_execute("UPDATE users SET avatar = 'Avatar.png' WHERE id = ?", [$user_id]);
                $_SESSION['flash_success'] = 'Avatar removed. Using default image.';
                header("Location: user_edit.php?id={$user_id}&tab=avatar");
                exit;
            }

            if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
                $errors[] = 'Please select a valid image file.';
            } else {
                $file     = $_FILES['avatar'];
                $ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                $allowed  = ['jpg','jpeg','png','gif','webp'];
                $max_size = 2 * 1024 * 1024; // 2MB

                if (!in_array($ext, $allowed))  $errors[] = 'Only JPG, PNG, GIF or WEBP images allowed.';
                if ($file['size'] > $max_size)  $errors[] = 'Image must be under 2MB.';

                // Verify it's actually an image
                $img_info = @getimagesize($file['tmp_name']);
                if (!$img_info)                 $errors[] = 'Uploaded file is not a valid image.';

                if (empty($errors)) {
                    // Delete old avatar
                    $old = $user['avatar'];
                    if ($old && $old !== 'Avatar.png') {
                        $old_path = "assets/images/avatars/{$old}";
                        if (file_exists($old_path)) unlink($old_path);
                    }

                    $new_filename = 'user_' . $user_id . '_' . time() . '.' . $ext;
                    $dest         = "assets/images/avatars/{$new_filename}";

                    if (move_uploaded_file($file['tmp_name'], $dest)) {
                        db_execute("UPDATE users SET avatar = ? WHERE id = ?", [$new_filename, $user_id]);
                        db_execute(
                            "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                             VALUES (?, 'updated_user_avatar', 'user', ?, ?, ?, ?)",
                            [$current_admin['id'], $user_id, $user['full_name'],
                             "Admin changed user avatar", $_SERVER['REMOTE_ADDR']]
                        );
                        $_SESSION['flash_success'] = 'Avatar updated successfully.';
                        header("Location: user_edit.php?id={$user_id}&tab=avatar");
                        exit;
                    } else {
                        $errors[] = 'Failed to save image. Check folder permissions on assets/images/avatars/';
                    }
                }
            }
            $active_tab = 'avatar';
        }
    }
}

// Reload fresh user data
$user = db_fetch_one("SELECT * FROM users WHERE id = ?", [$user_id]);

require_once 'includes/header.php';
?>

<style>
/* ── Edit Page Styles ───────────────────────────────────────── */
.edit-layout {
  display: grid;
  grid-template-columns: 260px 1fr;
  gap: 22px;
  align-items: start;
}

/* User sidebar card */
.user-sidebar-card {
  background: var(--glass-bg);
  border: 1px solid var(--glass-border);
  border-radius: var(--radius-lg);
  overflow: hidden;
  animation: fadeUp .5s ease both;
  position: sticky;
  top: calc(var(--topbar-h) + 20px);
}

.usb-top {
  background: linear-gradient(135deg,rgba(108,99,255,0.3),rgba(244,114,182,0.2));
  padding: 28px 20px 16px;
  text-align: center;
}

.usb-avatar-wrap { position: relative; display: inline-block; }

.usb-avatar {
  width: 80px; height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid var(--bg-deep);
  box-shadow: 0 4px 20px rgba(0,0,0,0.4);
}

.usb-name {
  font-family: 'Syne', sans-serif;
  font-size: 15px;
  font-weight: 700;
  color: var(--text-primary);
  margin-top: 12px;
}
.usb-username { font-size: 12px; color: var(--accent-2); margin-top: 2px; }
.usb-email    { font-size: 11px; color: var(--text-muted); margin-top: 4px; word-break:break-all; }

.usb-body { padding: 16px; }

.usb-stat {
  display: flex;
  justify-content: space-between;
  padding: 9px 0;
  border-bottom: 1px solid rgba(255,255,255,0.04);
  font-size: 12.5px;
}
.usb-stat:last-child { border-bottom: none; }
.usb-stat-label { color: var(--text-muted); }
.usb-stat-value { color: var(--text-primary); font-weight: 600; }

/* Tabs */
.edit-tabs {
  display: flex;
  gap: 0;
  background: var(--glass-bg);
  border: 1px solid var(--glass-border);
  border-radius: var(--radius-md);
  padding: 4px;
  margin-bottom: 20px;
}

.edit-tab {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px 16px;
  border-radius: 10px;
  font-size: 13px;
  font-weight: 600;
  color: var(--text-secondary);
  cursor: pointer;
  text-decoration: none;
  transition: all var(--transition);
  border: 1px solid transparent;
}

.edit-tab:hover { color: var(--text-primary); background: var(--glass-bg-hover); }

.edit-tab.active {
  background: rgba(108,99,255,0.2);
  border-color: rgba(108,99,255,0.3);
  color: var(--accent-2);
}

/* Form Card */
.form-card {
  background: var(--glass-bg);
  border: 1px solid var(--glass-border);
  border-radius: var(--radius-lg);
  overflow: hidden;
  animation: fadeUp .5s ease both;
}

.form-card-header {
  padding: 20px 24px 18px;
  border-bottom: 1px solid var(--glass-border);
  display: flex;
  align-items: center;
  gap: 12px;
}

.form-card-icon {
  width: 38px; height: 38px;
  border-radius: 11px;
  display: grid;
  place-items: center;
  font-size: 15px;
}

.form-card-title {
  font-family: 'Syne', sans-serif;
  font-size: 16px;
  font-weight: 700;
  color: var(--text-primary);
}
.form-card-subtitle { font-size: 12px; color: var(--text-muted); margin-top: 1px; }

.form-card-body { padding: 24px; }

/* Form grid */
.form-row-2 {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

/* Password strength */
.pw-strength {
  height: 4px;
  background: var(--glass-bg);
  border-radius: 10px;
  margin-top: 8px;
  overflow: hidden;
}
.pw-bar {
  height: 100%;
  border-radius: 10px;
  width: 0%;
  transition: width .3s ease, background .3s;
}

.pw-rules {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 6px;
  margin-top: 12px;
}

.pw-rule {
  display: flex;
  align-items: center;
  gap: 7px;
  font-size: 12px;
  color: var(--text-muted);
  transition: color .2s;
}
.pw-rule.pass { color: var(--success); }
.pw-rule i { font-size: 11px; width: 14px; text-align: center; }

/* Avatar upload */
.avatar-drop {
  border: 2px dashed var(--glass-border);
  border-radius: var(--radius-md);
  padding: 36px 20px;
  text-align: center;
  cursor: pointer;
  transition: all var(--transition);
  background: var(--glass-bg);
  position: relative;
}
.avatar-drop:hover, .avatar-drop.dragover {
  border-color: var(--accent);
  background: rgba(108,99,255,0.06);
}
.avatar-drop input[type=file] {
  position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%;
}
.avatar-drop-icon { font-size: 32px; color: var(--text-muted); margin-bottom: 10px; display:block; }
.avatar-drop-text { font-size: 14px; color: var(--text-secondary); }
.avatar-drop-sub  { font-size: 12px; color: var(--text-muted); margin-top: 4px; }

.avatar-preview-wrap {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: var(--glass-bg);
  border: 1px solid var(--glass-border);
  border-radius: var(--radius-md);
  margin-bottom: 16px;
}
.avatar-preview-wrap img {
  width: 64px; height: 64px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid var(--glass-border-lg);
}

/* Validation error list */
.error-list {
  background: var(--danger-bg);
  border: 1px solid var(--danger-border);
  border-radius: var(--radius-md);
  padding: 14px 18px;
  margin-bottom: 20px;
}
.error-list ul { list-style: none; }
.error-list li {
  font-size: 13px;
  color: #fca5a5;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 3px 0;
}

/* Form footer */
.form-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 20px;
  border-top: 1px solid var(--glass-border);
  margin-top: 24px;
}

@media (max-width: 900px) {
  .edit-layout { grid-template-columns: 1fr; }
  .user-sidebar-card { position: static; }
}
@media (max-width: 600px) {
  .form-row-2 { grid-template-columns: 1fr; }
  .edit-tabs  { flex-direction: column; }
  .pw-rules   { grid-template-columns: 1fr; }
}
</style>

<!-- Flash -->
<?php if ($flash_success): ?>
  <div class="flash-alert flash-success">
    <i class="fas fa-circle-check"></i><span><?= htmlspecialchars($flash_success) ?></span>
  </div>
<?php endif; ?>
<?php if ($flash_error): ?>
  <div class="flash-alert flash-error">
    <i class="fas fa-circle-exclamation"></i><span><?= htmlspecialchars($flash_error) ?></span>
  </div>
<?php endif; ?>

<!-- Errors from POST -->
<?php if (!empty($errors)): ?>
  <div class="error-list">
    <ul>
      <?php foreach ($errors as $e): ?>
        <li><i class="fas fa-circle-exclamation"></i><?= htmlspecialchars($e) ?></li>
      <?php endforeach; ?>
    </ul>
  </div>
<?php endif; ?>

<!-- Page Header -->
<div class="page-header">
  <div class="page-header-left">
    <h1>Edit <span style="color:var(--accent-2)">User</span></h1>
    <p>Modifying account for <?= htmlspecialchars($user['full_name']) ?></p>
  </div>
  <div class="page-header-right">
    <a href="user_view.php?id=<?= $user_id ?>" class="btn btn-glass btn-sm">
      <i class="fas fa-eye"></i> View Profile
    </a>
    <a href="users.php" class="btn btn-glass btn-sm">
      <i class="fas fa-arrow-left"></i> All Users
    </a>
  </div>
</div>

<!-- Layout -->
<div class="edit-layout">

  <!-- ── Left: User Summary Card ───────────────────────────── -->
  <div class="user-sidebar-card">
    <div class="usb-top">
      <div class="usb-avatar-wrap">
        <img src="assets/images/avatars/<?= htmlspecialchars($user['avatar'] ?? 'Avatar.png') ?>"
             onerror="this.src='assets/images/Avatar.png'"
             class="usb-avatar" id="avatarPreviewMain" alt="" />
      </div>
      <div class="usb-name"><?= htmlspecialchars($user['full_name']) ?></div>
      <div class="usb-username">@<?= htmlspecialchars($user['username']) ?></div>
      <div class="usb-email"><?= htmlspecialchars($user['email']) ?></div>
    </div>
    <div class="usb-body">
      <div class="usb-stat">
        <span class="usb-stat-label">Status</span>
        <span class="usb-stat-value">
          <span class="badge badge-<?= $user['status'] ?>"><?= ucfirst($user['status']) ?></span>
        </span>
      </div>
      <div class="usb-stat">
        <span class="usb-stat-label">User ID</span>
        <span class="usb-stat-value" style="color:var(--accent-2);">#<?= $user['id'] ?></span>
      </div>
      <div class="usb-stat">
        <span class="usb-stat-label">Verified</span>
        <span class="usb-stat-value">
          <?= $user['email_verified']
            ? '<span style="color:var(--success)"><i class="fas fa-check"></i> Yes</span>'
            : '<span style="color:var(--warning)"><i class="fas fa-xmark"></i> No</span>' ?>
        </span>
      </div>
      <div class="usb-stat">
        <span class="usb-stat-label">Last Login</span>
        <span class="usb-stat-value" style="font-size:11.5px;">
          <?= $user['last_login'] ? date('d M Y', strtotime($user['last_login'])) : 'Never' ?>
        </span>
      </div>
      <div class="usb-stat">
        <span class="usb-stat-label">Joined</span>
        <span class="usb-stat-value" style="font-size:11.5px;">
          <?= date('d M Y', strtotime($user['created_at'])) ?>
        </span>
      </div>

      <div style="margin-top:14px;padding-top:14px;border-top:1px solid var(--glass-border);">
        <a href="user_delete.php?id=<?= $user_id ?>&csrf=<?= urlencode($csrf) ?>"
           class="btn btn-danger" style="width:100%;justify-content:center;font-size:12.5px;"
           onclick="return confirm('Permanently delete this user? This cannot be undone.')">
          <i class="fas fa-trash"></i> Delete Account
        </a>
      </div>
    </div>
  </div>

  <!-- ── Right: Tab Forms ──────────────────────────────────── -->
  <div>

    <!-- Tabs -->
    <div class="edit-tabs">
      <a href="?id=<?= $user_id ?>&tab=details"
         class="edit-tab <?= $active_tab==='details'?'active':'' ?>">
        <i class="fas fa-id-card"></i> Profile Details
      </a>
      <a href="?id=<?= $user_id ?>&tab=password"
         class="edit-tab <?= $active_tab==='password'?'active':'' ?>">
        <i class="fas fa-key"></i> Password
      </a>
      <a href="?id=<?= $user_id ?>&tab=avatar"
         class="edit-tab <?= $active_tab==='avatar'?'active':'' ?>">
        <i class="fas fa-image"></i> Avatar
      </a>
    </div>

    <!-- ════════════════════════════════════════
         TAB: DETAILS
    ════════════════════════════════════════ -->
    <?php if ($active_tab === 'details'): ?>
    <div class="form-card">
      <div class="form-card-header">
        <div class="form-card-icon" style="background:rgba(108,99,255,0.15);color:var(--accent-2);">
          <i class="fas fa-id-card"></i>
        </div>
        <div>
          <div class="form-card-title">Profile Details</div>
          <div class="form-card-subtitle">Update name, email, phone, bio, status and verification</div>
        </div>
      </div>
      <div class="form-card-body">
        <form method="POST" action="" novalidate>
          <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>" />
          <input type="hidden" name="action" value="update_details" />

          <div class="form-row-2">
            <div class="form-group">
              <label class="form-label">Full Name <span style="color:var(--danger)">*</span></label>
              <input type="text" name="full_name" class="form-control"
                     value="<?= htmlspecialchars($_POST['full_name'] ?? $user['full_name']) ?>"
                     placeholder="John Doe" required />
            </div>
            <div class="form-group">
              <label class="form-label">Username <span style="color:var(--danger)">*</span></label>
              <div style="position:relative;">
                <span style="position:absolute;left:14px;top:50%;transform:translateY(-50%);color:var(--text-muted);font-size:14px;">@</span>
                <input type="text" name="username" class="form-control" style="padding-left:30px;"
                       value="<?= htmlspecialchars($_POST['username'] ?? $user['username']) ?>"
                       placeholder="johndoe" required />
              </div>
            </div>
          </div>

          <div class="form-row-2">
            <div class="form-group">
              <label class="form-label">Email Address <span style="color:var(--danger)">*</span></label>
              <input type="email" name="email" class="form-control"
                     value="<?= htmlspecialchars($_POST['email'] ?? $user['email']) ?>"
                     placeholder="john@example.com" required />
            </div>
            <div class="form-group">
              <label class="form-label">Phone Number</label>
              <input type="tel" name="phone" class="form-control"
                     value="<?= htmlspecialchars($_POST['phone'] ?? $user['phone'] ?? '') ?>"
                     placeholder="+1 555 000 0000" />
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">Bio / About</label>
            <textarea name="bio" class="form-control" rows="3"
                      placeholder="Short bio about the user…"
                      style="resize:vertical;"><?= htmlspecialchars($_POST['bio'] ?? $user['bio'] ?? '') ?></textarea>
          </div>

          <div class="form-row-2">
            <div class="form-group">
              <label class="form-label">Account Status</label>
              <select name="status" class="form-control">
                <?php foreach (['active','inactive','pending','banned'] as $s): ?>
                  <option value="<?= $s ?>"
                    <?= ($user['status'] === $s) ? 'selected' : '' ?>>
                    <?= ucfirst($s) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">Email Verification</label>
              <div style="display:flex;align-items:center;gap:12px;margin-top:10px;">
                <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:14px;color:var(--text-secondary);">
                  <input type="checkbox" name="email_verified" class="cb"
                         <?= $user['email_verified'] ? 'checked' : '' ?> />
                  Mark email as verified
                </label>
              </div>
            </div>
          </div>

          <div class="form-footer">
            <a href="user_view.php?id=<?= $user_id ?>" class="btn btn-glass">
              <i class="fas fa-xmark"></i> Cancel
            </a>
            <button type="submit" class="btn btn-primary">
              <i class="fas fa-floppy-disk"></i> Save Changes
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- ════════════════════════════════════════
         TAB: PASSWORD
    ════════════════════════════════════════ -->
    <?php elseif ($active_tab === 'password'): ?>
    <div class="form-card">
      <div class="form-card-header">
        <div class="form-card-icon" style="background:rgba(251,191,36,0.15);color:var(--warning);">
          <i class="fas fa-key"></i>
        </div>
        <div>
          <div class="form-card-title">Reset Password</div>
          <div class="form-card-subtitle">Set a new password for this user's account</div>
        </div>
      </div>
      <div class="form-card-body">

        <div class="flash-alert flash-warning" style="margin-bottom:20px;">
          <i class="fas fa-triangle-exclamation"></i>
          <span>You are setting a new password on behalf of <strong><?= htmlspecialchars($user['full_name']) ?></strong>. The user won't be notified automatically — inform them separately.</span>
        </div>

        <form method="POST" action="" id="passwordForm" novalidate>
          <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>" />
          <input type="hidden" name="action" value="update_password" />

          <div class="form-group">
            <label class="form-label">New Password <span style="color:var(--danger)">*</span></label>
            <div style="position:relative;">
              <input type="password" name="new_password" id="newPassword" class="form-control"
                     style="padding-right:44px;" placeholder="Minimum 8 characters" autocomplete="new-password" />
              <button type="button" class="pass-toggle-btn" onclick="togglePw('newPassword',this)">
                <i class="fas fa-eye"></i>
              </button>
            </div>
            <div class="pw-strength"><div class="pw-bar" id="pwBar"></div></div>
            <div class="pw-rules" id="pwRules">
              <div class="pw-rule" id="rule-len">  <i class="fas fa-circle"></i> Min 8 characters</div>
              <div class="pw-rule" id="rule-upper"><i class="fas fa-circle"></i> Uppercase letter</div>
              <div class="pw-rule" id="rule-num">  <i class="fas fa-circle"></i> Number (0–9)</div>
              <div class="pw-rule" id="rule-spec"> <i class="fas fa-circle"></i> Special char (!@#…)</div>
            </div>
          </div>

          <div class="form-group" style="margin-top:4px;">
            <label class="form-label">Confirm Password <span style="color:var(--danger)">*</span></label>
            <div style="position:relative;">
              <input type="password" name="confirm_password" id="confirmPassword" class="form-control"
                     style="padding-right:44px;" placeholder="Repeat the new password" autocomplete="new-password" />
              <button type="button" class="pass-toggle-btn" onclick="togglePw('confirmPassword',this)">
                <i class="fas fa-eye"></i>
              </button>
            </div>
            <div id="matchMsg" style="font-size:12px;margin-top:6px;display:none;"></div>
          </div>

          <div class="form-footer">
            <a href="user_view.php?id=<?= $user_id ?>" class="btn btn-glass">Cancel</a>
            <button type="submit" class="btn btn-primary" id="pwSubmit">
              <i class="fas fa-key"></i> Update Password
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- ════════════════════════════════════════
         TAB: AVATAR
    ════════════════════════════════════════ -->
    <?php elseif ($active_tab === 'avatar'): ?>
    <div class="form-card">
      <div class="form-card-header">
        <div class="form-card-icon" style="background:rgba(45,212,191,0.15);color:var(--teal);">
          <i class="fas fa-image"></i>
        </div>
        <div>
          <div class="form-card-title">Profile Avatar</div>
          <div class="form-card-subtitle">Upload a new avatar image for this user (max 2MB)</div>
        </div>
      </div>
      <div class="form-card-body">

        <!-- Current avatar -->
        <div class="avatar-preview-wrap">
          <img src="assets/images/avatars/<?= htmlspecialchars($user['avatar'] ?? 'Avatar.png') ?>"
               onerror="this.src='assets/images/Avatar.png'"
               id="avatarCurrentImg" alt="Current avatar" />
          <div>
            <div style="font-size:13.5px;font-weight:600;color:var(--text-primary);">Current Avatar</div>
            <div style="font-size:12px;color:var(--text-muted);margin-top:2px;"><?= htmlspecialchars($user['avatar'] ?? 'Avatar.png') ?></div>
          </div>
        </div>

        <!-- Upload form -->
        <form method="POST" enctype="multipart/form-data" action="">
          <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>" />
          <input type="hidden" name="action" value="update_avatar" />

          <div class="avatar-drop" id="avatarDrop">
            <input type="file" name="avatar" id="avatarInput" accept="image/*" />
            <i class="fas fa-cloud-arrow-up avatar-drop-icon"></i>
            <div class="avatar-drop-text">Click or drag & drop an image</div>
            <div class="avatar-drop-sub">JPG, PNG, WEBP or GIF — max 2MB</div>
          </div>

          <!-- New image preview -->
          <div id="newPreviewWrap" style="display:none;margin-top:16px;" class="avatar-preview-wrap">
            <img id="newPreviewImg" src="" alt="New avatar preview"
                 style="width:64px;height:64px;border-radius:50%;object-fit:cover;border:2px solid var(--glass-border-lg);" />
            <div>
              <div style="font-size:13px;font-weight:600;color:var(--text-primary);">New Avatar Preview</div>
              <div id="newPreviewName" style="font-size:12px;color:var(--text-muted);margin-top:2px;"></div>
            </div>
          </div>

          <div class="form-footer">
            <button type="submit" name="remove_avatar" value="1" class="btn btn-danger"
                    onclick="return confirm('Remove avatar and use the default image?')"
                    <?= ($user['avatar'] === 'Avatar.png' || !$user['avatar']) ? 'disabled' : '' ?>>
              <i class="fas fa-trash"></i> Remove Avatar
            </button>
            <button type="submit" class="btn btn-primary" id="uploadBtn" disabled>
              <i class="fas fa-cloud-arrow-up"></i> Upload Avatar
            </button>
          </div>
        </form>

      </div>
    </div>
    <?php endif; ?>

  </div><!-- /.right -->
</div><!-- /.edit-layout -->

<?php
$extra_scripts = <<<'JS'
<style>
.pass-toggle-btn {
  position:absolute; right:12px; top:50%; transform:translateY(-50%);
  background:none; border:none; color:var(--text-secondary);
  cursor:pointer; font-size:14px; padding:4px;
  transition:color .2s;
}
.pass-toggle-btn:hover { color:var(--accent-2); }
</style>
<script>
// ── Toggle password visibility ─────────────────────────────
function togglePw(id, btn) {
  const input = document.getElementById(id);
  const icon  = btn.querySelector('i');
  const show  = input.type === 'password';
  input.type  = show ? 'text' : 'password';
  icon.className = show ? 'fas fa-eye-slash' : 'fas fa-eye';
}

// ── Password strength checker ──────────────────────────────
const newPw    = document.getElementById('newPassword');
const confirmPw= document.getElementById('confirmPassword');
const pwBar    = document.getElementById('pwBar');
const matchMsg = document.getElementById('matchMsg');

const rules = {
  len:   { el: document.getElementById('rule-len'),   fn: v => v.length >= 8 },
  upper: { el: document.getElementById('rule-upper'), fn: v => /[A-Z]/.test(v) },
  num:   { el: document.getElementById('rule-num'),   fn: v => /[0-9]/.test(v) },
  spec:  { el: document.getElementById('rule-spec'),  fn: v => /[^A-Za-z0-9]/.test(v) },
};

newPw?.addEventListener('input', () => {
  const v     = newPw.value;
  let passing = 0;
  for (const key in rules) {
    const ok = rules[key].fn(v);
    rules[key].el.classList.toggle('pass', ok);
    rules[key].el.querySelector('i').className = ok ? 'fas fa-circle-check' : 'fas fa-circle';
    if (ok) passing++;
  }
  const pct   = (passing / 4) * 100;
  const colors = ['','#f87171','#fbbf24','#34d399','#34d399'];
  pwBar.style.width      = pct + '%';
  pwBar.style.background = colors[passing];

  checkMatch();
});

confirmPw?.addEventListener('input', checkMatch);

function checkMatch() {
  if (!confirmPw || !confirmPw.value) { matchMsg.style.display='none'; return; }
  const match = newPw.value === confirmPw.value;
  matchMsg.style.display = 'block';
  matchMsg.innerHTML = match
    ? '<span style="color:var(--success)"><i class="fas fa-circle-check"></i> Passwords match</span>'
    : '<span style="color:var(--danger)"><i class="fas fa-circle-xmark"></i> Passwords do not match</span>';
}

// ── Avatar upload preview ──────────────────────────────────
const avatarInput    = document.getElementById('avatarInput');
const newPreviewWrap = document.getElementById('newPreviewWrap');
const newPreviewImg  = document.getElementById('newPreviewImg');
const newPreviewName = document.getElementById('newPreviewName');
const uploadBtn      = document.getElementById('uploadBtn');
const avatarDrop     = document.getElementById('avatarDrop');

avatarInput?.addEventListener('change', handleFileSelect);

function handleFileSelect() {
  const file = avatarInput.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = e => {
    newPreviewImg.src    = e.target.result;
    newPreviewName.textContent = file.name + ' (' + (file.size/1024).toFixed(1) + ' KB)';
    newPreviewWrap.style.display = 'flex';
    uploadBtn.disabled  = false;
    // Update sidebar avatar preview too
    const mainAvatar = document.getElementById('avatarPreviewMain');
    if (mainAvatar) mainAvatar.src = e.target.result;
  };
  reader.readAsDataURL(file);
}

// Drag & drop
avatarDrop?.addEventListener('dragover', e => {
  e.preventDefault();
  avatarDrop.classList.add('dragover');
});
avatarDrop?.addEventListener('dragleave', () => avatarDrop.classList.remove('dragover'));
avatarDrop?.addEventListener('drop', e => {
  e.preventDefault();
  avatarDrop.classList.remove('dragover');
  if (e.dataTransfer.files.length) {
    avatarInput.files = e.dataTransfer.files;
    handleFileSelect();
  }
});
</script>
JS;

require_once 'includes/footer.php';
?>
