<?php include __DIR__ . '/includes/auth_guard.php'; ?>
<?php
include __DIR__ . '/includes/header.php';

$table_name = 'user';
$page       = 'user.php';
$res        = $db->select($table_name, '*', '', '');

if (isset($_POST['submit'])) {
    unset($_POST['submit']);
    $updateData = $_POST;
    $db->update($table_name, $updateData, 'id = :id', [':id' => 1]);

    // Avoid warnings if output already started
    if (session_status() === PHP_SESSION_ACTIVE && !headers_sent()) {
        session_regenerate_id(true);
    }

    $_SESSION['loggedin'] = true;
    $_SESSION['name']     = $_POST['username'] ?? '';

    echo "<script>window.location.href='". $page ."'</script>";
    exit;
}
?>

<!-- Optional: ensure buttons are visible on dark themes -->
<style>
  .input-group .btn { border-width: 1px; }
  .btn-outline-light { color:#fff !important; border-color:#adb5bd !important; }
</style>

<!-- Form Start -->
<div class="container-fluid pt-4 px-4">
  <div class="row g-4">
    <div class="col-12">
      <div class="bg-secondary rounded h-100 p-4">
        <h2 class="mb-4">Update Credentials</h2>

        <form method="post" autocomplete="off">
          <div class="mb-3">
            <label class="form-label">User name or Email address</label>
            <input type="text"
                   name="username"
                   class="form-control"
                   value="<?= htmlspecialchars($res[0]['username'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                   required>
            <div id="emailHelp" class="form-text">We'll never share your email or username with anyone else.</div>
          </div>

          <div class="mb-3">
            <label class="form-label d-block">Password</label>
            <div class="input-group">
              <input type="password"
                     id="passwordField"
                     name="password"
                     class="form-control"
                     value="<?= htmlspecialchars($res[0]['password'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                     required>
              <button type="button" class="btn btn-secondary" onclick="generatePassword()" title="Generate a strong password">Generate</button>
              <button type="button" id="toggleBtn" class="btn btn-outline-light" onclick="togglePassword()" title="Show / Hide">Show</button>
              <button type="button" class="btn btn-success" onclick="copyPassword(event)" title="Copy to clipboard">Copy</button>
            </div>
            <small class="form-text text-muted">
              Generated password includes uppercase, lowercase, and numbers.
            </small>
          </div>

          <button type="submit" name="submit" class="btn btn-primary">Update Credentials</button>
        </form>

      </div>
    </div>
  </div>
</div>
<!-- Form End -->

<script>
// Generate a password with at least 1 uppercase, 1 lowercase, 1 digit; default length 12
function generatePassword(length = 12) {
  const lower = "abcdefghijklmnopqrstuvwxyz";
  const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  const digits = "0123456789";
  const all   = lower + upper + digits;

  // ensure required categories
  let pwd = [
    lower[Math.floor(Math.random() * lower.length)],
    upper[Math.floor(Math.random() * upper.length)],
    digits[Math.floor(Math.random() * digits.length)]
  ];
  // fill remaining
  for (let i = pwd.length; i < length; i++) {
    pwd.push(all[Math.floor(Math.random() * all.length)]);
  }
  // shuffle (Fisher–Yates)
  for (let i = pwd.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [pwd[i], pwd[j]] = [pwd[j], pwd[i]];
  }

  const pass  = pwd.join('');
  const field = document.getElementById("passwordField");
  field.value = pass;

  // briefly show then re-mask
  field.type = "text";
  const toggleBtn = document.getElementById('toggleBtn');
  if (toggleBtn) toggleBtn.textContent = 'Hide';
  setTimeout(() => { field.type = "password"; if (toggleBtn) toggleBtn.textContent = 'Show'; }, 1500);
}

function togglePassword() {
  const field = document.getElementById("passwordField");
  const btn   = document.getElementById("toggleBtn");
  if (field.type === "password") {
    field.type = "text";
    if (btn) btn.textContent = "Hide";
  } else {
    field.type = "password";
    if (btn) btn.textContent = "Show";
  }
}

async function copyPassword(ev) {
  const btn   = ev && ev.target ? ev.target : null;
  const field = document.getElementById("passwordField");
  const text  = field.value || "";
  if (!text) return;

  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text);
    } else {
      field.select();
      document.execCommand('copy');
      field.setSelectionRange(field.value.length, field.value.length);
    }
    if (btn) {
      const orig = btn.textContent;
      btn.textContent = "Copied!";
      setTimeout(() => { btn.textContent = orig; }, 1000);
    } else {
      alert("Copied!");
    }
  } catch (e) {
    alert("Could not copy to clipboard. Please copy manually.");
  }
}
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
</body>
</html>
