<?php use App\Helpers\Helper;
$isSuperAdmin = ((int)($user['role_id'] ?? 0) === 1);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="admin-page-title mb-1">Edit User</h1>
    <p class="text-muted small mb-0"><?= Helper::e($user['first_name'].' '.$user['last_name']) ?> &mdash; <code><?= Helper::e($user['email']) ?></code></p>
  </div>
  <a href="<?= APP_URL ?>/admin/users" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-left me-1"></i>Back to Users</a>
</div>

<div class="row justify-content-center">
  <div class="col-lg-8">
    <form method="POST" action="<?= APP_URL ?>/admin/users/<?= $user['id'] ?>" enctype="multipart/form-data">
      <?= Helper::csrf() ?>

      <div class="form-card mb-4">
        <div class="form-section-title">Profile Photo</div>
        <div class="d-flex align-items-center gap-4">
          <?php
            $avatarSrc = !empty($user['avatar'])
              ? APP_URL.'/uploads/avatars/'.Helper::e($user['avatar'])
              : 'https://ui-avatars.com/api/?name='.urlencode($user['first_name'].' '.$user['last_name']).'&background=1a3c5e&color=fff&size=80';
          ?>
          <img src="<?= $avatarSrc ?>" id="avatarPreview" alt="Avatar"
               class="rounded-circle" style="width:80px;height:80px;object-fit:cover;border:3px solid #e2e8f0">
          <div>
            <label class="form-label fw-600 mb-1">Upload New Photo</label>
            <input type="file" name="avatar" id="avatarInput" class="form-control" accept="image/jpeg,image/png,image/webp">
            <div class="form-text">JPG, PNG or WebP — max 2MB. Leave blank to keep current photo.</div>
          </div>
        </div>
      </div>

      <div class="form-card mb-4">
        <div class="form-section-title">Personal Information</div>
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label fw-600">First Name <span class="text-danger">*</span></label>
            <input type="text" name="first_name" class="form-control" value="<?= Helper::e($user['first_name']) ?>" required>
          </div>
          <div class="col-md-6">
            <label class="form-label fw-600">Last Name <span class="text-danger">*</span></label>
            <input type="text" name="last_name" class="form-control" value="<?= Helper::e($user['last_name']) ?>" required>
          </div>
          <div class="col-md-6">
            <label class="form-label fw-600">Email</label>
            <input type="email" class="form-control bg-light" value="<?= Helper::e($user['email']) ?>" disabled>
            <div class="form-text">Email cannot be changed here.</div>
          </div>
          <div class="col-md-6">
            <label class="form-label fw-600">Phone</label>
            <input type="tel" name="phone" class="form-control" value="<?= Helper::e($user['phone']??'') ?>" placeholder="+255 700 000 000">
          </div>
        </div>
      </div>

      <div class="form-card mb-4">
        <div class="form-section-title">Role & Status</div>
        <?php if ($isSuperAdmin): ?>
        <div class="alert alert-warning d-flex align-items-center gap-2 mb-3 py-2" style="font-size:.875rem">
          <i class="bi bi-shield-lock-fill text-warning fs-5"></i>
          <span><strong>Protected Account:</strong> The Super Admin role and status cannot be changed.</span>
        </div>
        <input type="hidden" name="role_id" value="<?= $user['role_id'] ?>">
        <input type="hidden" name="status"  value="<?= Helper::e($user['status']) ?>">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label fw-600">Role</label>
            <input class="form-control bg-light" value="Super Admin" disabled>
          </div>
          <div class="col-md-6">
            <label class="form-label fw-600">Status</label>
            <input class="form-control bg-light" value="Active" disabled>
          </div>
        </div>
        <?php else: ?>
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label fw-600">Role <span class="text-danger">*</span></label>
            <select name="role_id" class="form-select" required>
              <?php foreach ($roles as $r): ?>
              <option value="<?= $r['id'] ?>" <?= $r['id']==$user['role_id']?'selected':'' ?>><?= Helper::e($r['display_name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label fw-600">Status</label>
            <select name="status" class="form-select">
              <option value="active"   <?= $user['status']==='active'  ?'selected':'' ?>>Active</option>
              <option value="inactive" <?= $user['status']==='inactive'?'selected':'' ?>>Inactive</option>
            </select>
          </div>
        </div>
        <?php endif; ?>
      </div>

      <div class="form-card mb-4">
        <div class="form-section-title">Change Password <span class="text-muted fw-400 small">(leave blank to keep current)</span></div>
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label fw-600">New Password</label>
            <div class="input-group">
              <input type="password" name="password" id="pwdInput" class="form-control" minlength="8" placeholder="Min. 8 characters">
              <button type="button" class="btn btn-outline-secondary" onclick="togglePwd('pwdInput','eyeIcon1')"><i class="bi bi-eye" id="eyeIcon1"></i></button>
            </div>
          </div>
          <div class="col-md-6">
            <label class="form-label fw-600">Confirm Password</label>
            <div class="input-group">
              <input type="password" name="password_confirm" id="pwdConfirm" class="form-control" minlength="8" placeholder="Repeat password">
              <button type="button" class="btn btn-outline-secondary" onclick="togglePwd('pwdConfirm','eyeIcon2')"><i class="bi bi-eye" id="eyeIcon2"></i></button>
            </div>
          </div>
          <div class="col-12" id="pwdError" style="display:none">
            <div class="alert alert-danger py-2 mb-0">Passwords do not match.</div>
          </div>
        </div>
      </div>

      <div class="d-flex justify-content-end gap-2">
        <a href="<?= APP_URL ?>/admin/users" class="btn btn-outline-secondary px-4">Cancel</a>
        <button type="submit" class="btn btn-primary px-4"><i class="bi bi-save me-2"></i>Save Changes</button>
      </div>
    </form>
  </div>
</div>

<script>
document.getElementById('avatarInput').addEventListener('change', function() {
  if (this.files && this.files[0]) {
    const reader = new FileReader();
    reader.onload = e => document.getElementById('avatarPreview').src = e.target.result;
    reader.readAsDataURL(this.files[0]);
  }
});
function togglePwd(inputId, iconId) {
  const inp  = document.getElementById(inputId);
  const icon = document.getElementById(iconId);
  inp.type = inp.type === 'password' ? 'text' : 'password';
  icon.className = inp.type === 'password' ? 'bi bi-eye' : 'bi bi-eye-slash';
}

document.querySelector('form').addEventListener('submit', function(e) {
  const pwd  = document.getElementById('pwdInput').value;
  const conf = document.getElementById('pwdConfirm').value;
  const err  = document.getElementById('pwdError');
  if (pwd && pwd !== conf) {
    e.preventDefault();
    err.style.display = '';
    return;
  }
  err.style.display = 'none';
});
</script>
